Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
153cdbe798 | ||
|
|
063f05bdba | ||
|
|
bc513d666e | ||
|
|
3793aaae65 | ||
|
|
ade1fd4673 | ||
|
|
e2e9d6f4f9 | ||
|
|
9c8fbaf1cc | ||
|
|
8e8be164bd | ||
|
|
e7d5022d02 | ||
|
|
83d1bafcf8 | ||
|
|
2abf5a1804 | ||
|
|
6884559b6b | ||
|
|
8d805ad17d | ||
|
|
5efb272dcb | ||
|
|
456fea3c17 | ||
|
|
8f357f8767 | ||
|
|
73ca207301 | ||
|
|
34031fe89d | ||
|
|
4e14adfc01 | ||
|
|
8e4b0771c8 | ||
|
|
4565893787 | ||
|
|
4ff25cad78 | ||
|
|
6d8a9a9302 | ||
|
|
8d945a63a4 | ||
|
|
c72cdc39a8 | ||
|
|
c93e2f71f1 | ||
|
|
bc26d3c75f | ||
|
|
eadd1952fe | ||
|
|
fd7e69f43a | ||
|
|
26a13bdeb2 | ||
|
|
89dc845f1b | ||
|
|
d0cda6cc36 | ||
|
|
bedfbe7afd | ||
|
|
6f2cb0b995 | ||
|
|
a6aaf55c3c | ||
|
|
f2aa714b17 | ||
|
|
2464907a9c | ||
|
|
304a384cd0 | ||
|
|
5dfb1c6a6c | ||
|
|
9e84837a68 | ||
|
|
600db80998 | ||
|
|
e6a0a607d2 | ||
|
|
0cff2f3a0a | ||
|
|
2e9768c3b5 | ||
|
|
1df9368330 | ||
|
|
7014fc06fe | ||
|
|
464ea59a4c | ||
|
|
dba8d9199d | ||
|
|
9358348549 | ||
|
|
1764f092ae | ||
|
|
8c25786a1c | ||
|
|
f358478355 | ||
|
|
e6ec42c015 | ||
|
|
9e7aabe7a7 | ||
|
|
6396857b66 | ||
|
|
51e498e8e7 | ||
|
|
85a39183f0 | ||
|
|
09ce9e83b4 | ||
|
|
63b0e15a9f | ||
|
|
4013e5e2ac | ||
|
|
69988fa0cc | ||
|
|
fcf92878a3 | ||
|
|
9fa1536c78 | ||
|
|
8a4f6b429d | ||
|
|
53c5e87dca | ||
|
|
9737dd70b6 | ||
|
|
57794f6588 | ||
|
|
dd79170859 | ||
|
|
6f972ef2d5 | ||
|
|
8ec4baac6d | ||
|
|
9bf160f379 | ||
|
|
aaf533535b | ||
|
|
508c5bfd23 | ||
|
|
63e224aa5b | ||
|
|
46d051ab8a | ||
|
|
53659c73f0 | ||
|
|
226260def4 | ||
|
|
cb24374230 | ||
|
|
2db01c9906 | ||
|
|
55f07becd0 | ||
|
|
3740431e96 | ||
|
|
26ef5b63ff | ||
|
|
33360a3e1e | ||
|
|
859d42a7fa | ||
|
|
eac9ba5f7e | ||
|
|
0b7da6f2a9 | ||
|
|
1c725a611f | ||
|
|
763291c5ba | ||
|
|
d0de92a019 | ||
|
|
4acd6fd56f | ||
|
|
3c23179842 | ||
|
|
c6be577be3 | ||
|
|
db3a7972a4 | ||
|
|
dc44eebbac | ||
|
|
88b0ffa95c | ||
|
|
55150e58db | ||
|
|
a02cb73e75 | ||
|
|
7801f06252 | ||
|
|
ce3234f0c2 | ||
|
|
42422b4a48 | ||
|
|
54ffe54d73 | ||
|
|
14651c1cc4 | ||
|
|
f428647995 | ||
|
|
be482fefbc | ||
|
|
0f1db0fb22 | ||
|
|
a292bddbe8 | ||
|
|
2aa4e6960d | ||
|
|
c947b6fc6f | ||
|
|
0385acd539 | ||
|
|
c92f7e5e03 | ||
|
|
c49ddf85cb | ||
|
|
da02d23032 | ||
|
|
f977687b27 | ||
|
|
31077727e1 | ||
|
|
6a783a701c | ||
|
|
8a5db6b89e | ||
|
|
c46006858f | ||
|
|
0e5366a81a | ||
|
|
318ba07ed5 | ||
|
|
391bbb6bc0 | ||
|
|
572252b187 | ||
|
|
894b86cd14 | ||
|
|
1006902d07 | ||
|
|
49fecf56af | ||
|
|
ca59cd8155 | ||
|
|
9820581723 | ||
|
|
9079306f8f | ||
|
|
3b2f739254 | ||
|
|
c6c841f7c0 | ||
|
|
66c3a4bb2e | ||
|
|
1b317798a4 | ||
|
|
95feb975ea | ||
|
|
bf1d2d4793 | ||
|
|
1f66b1c616 | ||
|
|
8cee52fcd6 | ||
|
|
44692cde8e | ||
|
|
23359ee714 | ||
|
|
25004356b5 | ||
|
|
7e4e5ff452 | ||
|
|
d63c1005b7 | ||
|
|
bf71bca11a | ||
|
|
c35b87a1da | ||
|
|
afa520a68a | ||
|
|
b67734b8e1 | ||
|
|
d124da717d | ||
|
|
40417b99b1 | ||
|
|
ba7d29990c | ||
|
|
b18c5bdb1e | ||
|
|
1191872b3e | ||
|
|
ae5a533baf | ||
|
|
9cc7c0e26a | ||
|
|
7ca5e2bac4 | ||
|
|
e064c31175 | ||
|
|
8959e239fe | ||
|
|
06c9566df4 | ||
|
|
108f5cd9c1 | ||
|
|
9b86b54ae1 | ||
|
|
40e0884ee7 | ||
|
|
e1fa4e7890 | ||
|
|
4161b8817b | ||
|
|
4554190912 | ||
|
|
b714ad8eb6 | ||
|
|
6cd5c1eed3 | ||
|
|
6784e2a2de | ||
|
|
7f69debe1d | ||
|
|
f8df7c2a6a | ||
|
|
b3fb2b82f2 | ||
|
|
04d0c57cb0 | ||
|
|
27b0fe62c8 | ||
|
|
096beb22d7 | ||
|
|
21766a5dc6 | ||
|
|
fd5e8b63b2 | ||
|
|
2f514e6464 | ||
|
|
74d2c614fd | ||
|
|
da0d8c45e6 | ||
|
|
e87d8116a6 | ||
|
|
8aaff066b3 | ||
|
|
685c9d1981 | ||
|
|
81ae25035e | ||
|
|
530ff36a16 | ||
|
|
9fd52e7bc4 | ||
|
|
0c2ca68dcd | ||
|
|
e7c92eae71 | ||
|
|
7b26e323ac | ||
|
|
b0069e3bc9 | ||
|
|
8582bc903b | ||
|
|
8690284ac2 | ||
|
|
c9e485ac88 | ||
|
|
9d577880e0 | ||
|
|
09bacfb3e5 | ||
|
|
3fd9cec67d | ||
|
|
ac7a1e0cb0 | ||
|
|
53ba0a2347 | ||
|
|
83cc89e1b3 | ||
|
|
655c4a91e5 | ||
|
|
083f269605 | ||
|
|
9880bac0c6 | ||
|
|
0f87776d16 | ||
|
|
ed291459d1 | ||
|
|
bc1eb7f996 | ||
|
|
8366965a03 | ||
|
|
904f77191c | ||
|
|
ec9f56cf1e | ||
|
|
980527cdde | ||
|
|
efe794c63f | ||
|
|
65a677ea91 | ||
|
|
dabf63fc58 | ||
|
|
1da95e09b5 | ||
|
|
ad195a985e | ||
|
|
0e06584780 | ||
|
|
a6f44ecad5 | ||
|
|
d527fa9a80 | ||
|
|
ffe360ee80 | ||
|
|
8fd9c9b80e | ||
|
|
d77f2fe8df | ||
|
|
86c44825d9 | ||
|
|
b5d8bb5548 | ||
|
|
9000be1951 | ||
|
|
38ba5154f9 | ||
|
|
9f670031b1 | ||
|
|
c0dd7baeaa | ||
|
|
1c96dcfc4a | ||
|
|
2a3821e1e7 | ||
|
|
8b61b1d719 | ||
|
|
431df5c334 | ||
|
|
2b49a01eb4 | ||
|
|
3bc438a06d | ||
|
|
57d6b7dc8e | ||
|
|
5d87257516 | ||
|
|
cb9ab7d1af | ||
|
|
598f00c536 | ||
|
|
426dbf1457 | ||
|
|
ba1b139f40 | ||
|
|
40dc4b788d | ||
|
|
69d5ec6477 | ||
|
|
96cb5538da | ||
|
|
c3101ea5f6 | ||
|
|
493e6559df | ||
|
|
8945002652 | ||
|
|
8f30f3558a | ||
|
|
15ba07198d | ||
|
|
39fff2bfc9 | ||
|
|
8339c2d86b | ||
|
|
29ca2d1c50 | ||
|
|
8b2cd301c9 | ||
|
|
5240320d99 | ||
|
|
25205d579b | ||
|
|
32c904f504 | ||
|
|
9e3a62a283 | ||
|
|
050e172949 | ||
|
|
b231fe8f4e | ||
|
|
14c2fd8aed | ||
|
|
27ac32648c | ||
|
|
f6c3a4b34a | ||
|
|
fcf0513356 | ||
|
|
26f51acc0c | ||
|
|
9a36ad35e4 | ||
|
|
4771eaaa7e | ||
|
|
170a642858 | ||
|
|
2dd4fb9e58 | ||
|
|
77c95ed14a | ||
|
|
75b3467f89 | ||
|
|
7c77f4a75e | ||
|
|
a36403ee14 | ||
|
|
31c99f3e6e | ||
|
|
fdd85b2df3 | ||
|
|
1e971d4ec3 | ||
|
|
1274349fc9 | ||
|
|
f2065c3ec8 | ||
|
|
bb34c1e02f | ||
|
|
41ac2482d8 | ||
|
|
9baacea029 | ||
|
|
1d87208dca | ||
|
|
af315b7775 | ||
|
|
212d21761b | ||
|
|
eb48200149 | ||
|
|
814db9020a | ||
|
|
893a729093 | ||
|
|
43b06d11eb | ||
|
|
3e9e8ca299 | ||
|
|
0a6ce5bf07 | ||
|
|
813eb7fb32 | ||
|
|
e30056eb5d | ||
|
|
7f039fa2b4 | ||
|
|
9be3a9c6d3 | ||
|
|
a8989b0810 | ||
|
|
c9f27e3157 | ||
|
|
26f1e17b7c | ||
|
|
47fa7563c0 | ||
|
|
f2fc197df7 | ||
|
|
647ebea95b | ||
|
|
eebc4d4ee4 | ||
|
|
e1ff89d3d9 | ||
|
|
11d72a2336 | ||
|
|
68e6544da8 | ||
|
|
a26f7e30a4 | ||
|
|
b989a47b9e | ||
|
|
a7f98989b3 | ||
|
|
4aaded50ac | ||
|
|
3089841a05 | ||
|
|
eeabdd24fd | ||
|
|
8c82ed7d8c | ||
|
|
5fd289afb5 | ||
|
|
8d0213c7bb | ||
|
|
7e8b83aefe | ||
|
|
136432b97b | ||
|
|
cbcf71da8a | ||
|
|
9bc58aa9fe | ||
|
|
74e3fd8878 | ||
|
|
c857f4a1e7 | ||
|
|
fb853086e6 | ||
|
|
54f4130bab | ||
|
|
2acc11875b | ||
|
|
0c1b341ce9 | ||
|
|
b4d89a54e3 | ||
|
|
c7d3ae137f | ||
|
|
e71ae4fda1 | ||
|
|
8c111ffaf2 | ||
|
|
238c7b512a | ||
|
|
68e5be5214 | ||
|
|
b417da22a2 | ||
|
|
3758363dd3 | ||
|
|
b7587e419b | ||
|
|
4decb78017 | ||
|
|
129e0c36fa | ||
|
|
a784ff2cd8 | ||
|
|
52badae681 | ||
|
|
2bfd46d5f5 | ||
|
|
10240aaa4e | ||
|
|
4855d59e99 | ||
|
|
59594878ab | ||
|
|
7fc552ab67 | ||
|
|
5197800b55 | ||
|
|
6fe29dfe53 | ||
|
|
ea84410eb6 | ||
|
|
0a8a52ea3c | ||
|
|
d115339a99 | ||
|
|
0c01f0dba2 | ||
|
|
7b35b2eb80 | ||
|
|
3508205328 | ||
|
|
0c7ec55414 | ||
|
|
8cf43373c8 | ||
|
|
e14e402c2f |
No files matched your search
@@ -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']
|
||||
@@ -0,0 +1,116 @@
|
||||
name: Paperize CI/CD Pipeline
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
tags: [ 'v*' ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
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@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6
|
||||
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
|
||||
|
||||
- name: Run Android lint
|
||||
run: ./gradlew :app: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@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
|
||||
- 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@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # 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@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
pattern: paperize-v*
|
||||
path: ./apk-artifact
|
||||
merge-multiple: true
|
||||
|
||||
- name: Create Draft Release
|
||||
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3
|
||||
with:
|
||||
files: ./apk-artifact/paperize-v*.apk
|
||||
draft: true
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
name: CodeQL
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
schedule:
|
||||
- cron: "24 6 * * 3"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
jobs:
|
||||
analyze-actions:
|
||||
name: Analyze GitHub Actions
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
|
||||
with:
|
||||
languages: actions
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL analysis
|
||||
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # 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@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: temurin
|
||||
cache: gradle
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
|
||||
with:
|
||||
languages: java-kotlin
|
||||
build-mode: manual
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: Build application for analysis
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Perform CodeQL analysis
|
||||
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
|
||||
@@ -1,43 +0,0 @@
|
||||
# Simple workflow for deploying static content to GitHub Pages
|
||||
name: Deploy static content to Pages
|
||||
|
||||
on:
|
||||
# Runs on pushes targeting the default branch
|
||||
push:
|
||||
branches: ["master"]
|
||||
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
||||
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
|
||||
concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# Single deploy job since we're just deploying
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v5
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
# Upload entire repository
|
||||
path: '.'
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
## v4.2.1
|
||||
|
||||
- Log live wallpaper queue failures instead of silently ignoring them.
|
||||
- The combined home and lock interval saves as soon as typing pauses, like the separate intervals.
|
||||
- Remove debug logging from release builds, including a log written on every home-screen swipe with the live wallpaper.
|
||||
- Simplify error handling, settings storage, scheduling, and duplicated wallpaper queue, effect, and UI code.
|
||||
|
||||
## v4.2.0
|
||||
|
||||
### Library and albums
|
||||
- Make image imports and folder refreshes cancellable and transactional, with accurate progress and useful failure feedback.
|
||||
- Preserve library entries when a document provider is temporarily unavailable, avoid duplicate imports, and refresh folder metadata and covers consistently.
|
||||
- Preserve library data when upgrading older database versions.
|
||||
- Improve album deletion, selection cleanup, sorting, and empty-album actions.
|
||||
|
||||
### Wallpaper reliability
|
||||
- Keep home and lock schedules consistent across restarts, manual changes, and settings edits.
|
||||
- Prevent rapid settings edits from overwriting newer album selections or pause/resume actions.
|
||||
- Share wallpaper application and rendering between manual changes and scheduled jobs, with consistent failure recovery.
|
||||
- Correct static image sizing, thin-image decoding, and FIT/STRETCH fallback rendering.
|
||||
|
||||
### Live wallpaper and interface
|
||||
- Fix crossfade completion and preserve pending wallpaper changes when folding, resizing, or recreating the rendering surface.
|
||||
- Improve OpenGL resource cleanup, blur rendering, and memory use.
|
||||
- Respect animation settings in previews and improve sorting accessibility and settings feedback.
|
||||
- Remove redundant UI, unused dependencies, obsolete compatibility code, and low-value tests and comments.
|
||||
|
||||
## v4.1.1
|
||||
|
||||
- Fixed manual changes triggering an immediate extra automatic change by deferring
|
||||
the next run for the full interval and preserving it across settings updates.
|
||||
- Added Simplified Chinese translations for setup, settings, wallpaper controls,
|
||||
notifications, and accessibility labels, with Android app-language support.
|
||||
- Corrected the privacy notice to explain that Paperize displays its own
|
||||
notifications and does not read notifications from other apps.
|
||||
|
||||
## New Contributors
|
||||
|
||||
* @zxiaoshen made their first contribution in https://github.com/Anthonyy232/Paperize/pull/605
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v4.1.0...v4.1.1
|
||||
|
||||
## v4.1.0
|
||||
|
||||
- Added a Set wallpaper action to image previews, with separate home, lock, and
|
||||
combined home-and-lock targets that preserve each screen's scaling and effects.
|
||||
- Reset the affected automatic countdown after a successful manual change from
|
||||
Paperize, its launcher shortcut, or its Quick Settings tile.
|
||||
- Added live-wallpaper intervals as short as one minute while the wallpaper is
|
||||
visible, with lifecycle-aware pausing and timer resets after manual changes.
|
||||
- Replaced the undersized status-bar asset with a dedicated notification icon.
|
||||
- Updated Paperize for the Android 17 SDK and refreshed Kotlin, Gradle, Compose,
|
||||
AndroidX, Material, Coil, Zoomable, and GitHub Actions dependencies.
|
||||
- Expanded emulator coverage for Android wallpaper colors, every static and live
|
||||
visual effect, OpenGL shaders, scheduling policy, and foldable display sizing.
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v4.0.3...v4.1.0
|
||||
|
||||
## v4.0.3
|
||||
|
||||
- Kept scheduled static changes in the device's natural orientation, even when a
|
||||
landscape game or app is in the foreground.
|
||||
- Rendered FIT, FILL, STRETCH, and NONE against one physical display panel to fix
|
||||
black canvases, excessive stretching, zoom, and inconsistent home/lock alignment.
|
||||
- Restored centered static FILL behavior by default and added an explicit horizontal
|
||||
scrolling option for users who want wide wallpapers to move across home pages.
|
||||
- Added a persistent pause/resume control that keeps selected albums intact, while
|
||||
leaving manual static and live wallpaper changes available when paused.
|
||||
- Removed the unnecessary network-state permission and unused network image loader.
|
||||
- Updated Hilt and the coroutine test library and expanded rotation, scaling,
|
||||
scrolling, pause/resume, static-effect, live-renderer, and scheduler verification.
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v4.0.2...v4.0.3
|
||||
|
||||
## v4.0.2
|
||||
|
||||
- Reloaded the current live wallpaper at native resolution after fold, unfold,
|
||||
surface-size, and scaling changes without advancing the wallpaper queue.
|
||||
- Made adaptive brightness update the wallpaper already on screen and removed
|
||||
the brightness dip that could occur halfway through live crossfades.
|
||||
- Kept live vignette shading continuous across large images split into multiple
|
||||
GPU texture tiles.
|
||||
- Prevented a delayed effect-slider save from overwriting a switch or other
|
||||
setting changed immediately afterward.
|
||||
- Restored the launcher app shortcut for gesture apps and other launchers, with
|
||||
automatic routing to the configured static or live wallpaper engine.
|
||||
- Added the missing daily album refresh to live schedules and hardened boot
|
||||
recovery so valid jobs are restored without duplicates and stale jobs are removed.
|
||||
- Removed two unused legacy serialization and document-file dependencies from
|
||||
the release package.
|
||||
- Expanded device coverage for every static effect and verified synchronized,
|
||||
independent, manual, live, and reboot scheduling paths.
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v4.0.1...v4.0.2
|
||||
|
||||
## v4.0.1
|
||||
|
||||
- Restored native static FILL scrolling so wide wallpapers move between their real
|
||||
left and right edges without synthetic launcher-sized overflow.
|
||||
- Added independent brightness, blur, vignette, and grayscale controls for home
|
||||
and lock screens, including when both screens share one album and schedule.
|
||||
- Refreshed folder-backed albums whenever Paperize returns to the foreground so
|
||||
added and removed files appear without restarting the app.
|
||||
- Improved foldable sizing on Android 17 by including inactive built-in panels
|
||||
while excluding external displays.
|
||||
- Made wallpaper changes commit queue and current-wallpaper state only after
|
||||
Android accepts the bitmap, with rejected changes restored for retry.
|
||||
- Corrected live wallpaper parallax enablement, intensity, edge traversal, and
|
||||
launcher-offset clamping, and clarified that it responds to home-page swipes.
|
||||
- Added device regressions for EXIF rotation, static FILL overflow, and folded
|
||||
display sizing, plus focused queue and live-renderer unit coverage.
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v4.0.0...v4.0.1
|
||||
|
||||
## v4.0.0
|
||||
|
||||
- Completely rewrote Paperize for Android 12 and newer with a modern Compose interface.
|
||||
- Added static and live wallpaper modes with independent home and lock screen settings.
|
||||
- Added scaling, blur, darken, vignette, grayscale, adaptive brightness, parallax,
|
||||
double-tap, shuffle, interval, and manual wallpaper controls.
|
||||
- Added current-wallpaper previews, Quick Settings support, and progress indicators
|
||||
for large wallpaper and folder imports.
|
||||
- Improved folder scanning, queue refreshes, bitmap memory usage, scheduling, and
|
||||
wallpaper rendering reliability.
|
||||
- Fixed home and lock screen synchronization, foldable display sizing, EXIF rotation,
|
||||
and FIT, FILL, STRETCH, and NONE scaling behavior.
|
||||
- Removed the obsolete all-files storage permission in favor of Android's scoped
|
||||
document access.
|
||||
- Updated dependencies and repaired the release workflow for signed, versioned APKs.
|
||||
|
||||
**Upgrade note:** Updating from Paperize 3 resets local albums and settings once
|
||||
because Paperize 4 uses a new storage model. Users of the 4.0.0 alpha are not reset
|
||||
again.
|
||||
|
||||
## New Contributors
|
||||
|
||||
* @gpunto made their first contribution in https://github.com/Anthonyy232/Paperize/pull/415
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v3.2.1...v4.0.0
|
||||
@@ -1,97 +1,149 @@
|
||||
|
||||
<div align="center">
|
||||
<img style="display: block; border-radius: 9999px;" src="https://github.com/user-attachments/assets/e8fb14f5-ec8e-440e-a2ac-8065322b0e28" alt="">
|
||||
<h1>
|
||||
Paperize
|
||||
<p><img style="display: block; border-radius: 9999px;" src="https://img.shields.io/github/downloads/Anthonyy232/Paperize/total" alt=""></p>
|
||||
</h1>
|
||||
<p align="center"></p>
|
||||
<p>Paperize is a dynamic wallpaper changer application designed to keep your device's aesthetic fresh and exciting</p>
|
||||
<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>
|
||||
|
||||
[](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>
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
- **Dynamic Wallpaper Changer**: Set your wallpaper to change at specific time intervals
|
||||
- **Supports Various Image Types**: Paperize can handle a wide range of image types
|
||||
- Including: JPEG, PNG, AVIF, WEBP
|
||||
- **Folder Support**: Organize your wallpapers into folders for auto-updating
|
||||
- **Home and Lock Screen Wallpaper**: Choose the same or separate albums for your home screen and lock screen
|
||||
- **Wallpaper effects**: Change the brightness and the blur of your wallpaper
|
||||
- **On-Device Storage**: All your wallpapers and settings are stored on your device
|
||||
|
||||
|
||||
<div align="center">
|
||||
<br/>
|
||||
<img src="https://github.com/Anthonyy232/Paperize/assets/60626873/57122f72-78f8-45ed-a9ac-de943061d6a2" width="30%" alt="onboarding" />
|
||||
<img src="https://github.com/user-attachments/assets/f054e7f1-d67f-4500-a547-64bccd986bbd" width="30%" alt="wallpaper" />
|
||||
<img src="https://github.com/user-attachments/assets/cdf0d989-ae11-44ba-b33c-4aeec6b6116e" width="30%" alt="interval" />
|
||||
<img src="https://github.com/Anthonyy232/Paperize/assets/60626873/4ce1b28d-f4b2-4048-a261-203156222263" width="30%" alt="album" />
|
||||
<img src="https://github.com/user-attachments/assets/d23f290d-bb2c-4b89-9321-b426e45864f9" width="30%" alt="settings" />
|
||||
<br/>
|
||||
<video controls src="https://github.com/user-attachments/assets/ce7f5c7c-66a7-45fc-bb28-a53d8d9cf733" muted="muted"></video>
|
||||
</div>
|
||||
- **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
|
||||
|
||||
---
|
||||
|
||||
## Download
|
||||
[<img src="https://github.com/Anthonyy232/Paperize/assets/60626873/1c034414-21cd-4a0a-838d-89fe7bd56910" alt="Download app from GitHub" height="80">](https://github.com/Anthonyy232/Paperize/releases)
|
||||
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Download app from F-Droid" height="80">](https://f-droid.org/en/packages/com.anthonyla.paperize/)
|
||||
[<img src="https://gitlab.com/IzzyOnDroid/repo/-/raw/master/assets/IzzyOnDroid.png" alt="Download app from IzzyOnDroid" height="80">](https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize)
|
||||
|
||||
[<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)
|
||||
|
||||
---
|
||||
|
||||
## Localization
|
||||
I want to allow more people to use the app. Currently, most of the translations are provided using machine translation and AI -- which is not optimal.
|
||||
|
||||
I would love some help translating the app! Help me out with that [here](https://crowdin.com/project/paperize/invite?h=d8d7a7513d2beb0c96ba9b2a5f85473e2084922)!
|
||||
Help translate Paperize into your language! Currently, most translations are provided using machine translation — contributions from native speakers are greatly appreciated.
|
||||
|
||||
[](https://crowdin.com/project/paperize)
|
||||
**[Contribute on Crowdin →](https://crowdin.com/project/paperize/invite?h=d8d7a7513d2beb0c96ba9b2a5f85473e2084922)**
|
||||
|
||||
## Technologies
|
||||
---
|
||||
|
||||
- [Kotlin](https://kotlinlang.org/) - A programming language that is used for Android app development
|
||||
- [Jetpack Compose](https://developer.android.com/develop/ui/compose) - A declarative UI toolkit for building native Android UI
|
||||
- [Material 3](https://m3.material.io/) - A UI design system for modern UI guidelines
|
||||
- [Dagger Hilt](https://dagger.dev/hilt/) - A dependency injection library
|
||||
- [Room](https://developer.android.com/training/data-storage/room) - A persistence library that provides an abstraction layer over SQLite interfacing with Kotlin
|
||||
- [AboutLibraries](https://github.com/mikepenz/AboutLibraries) - A library to offer some information of libraries
|
||||
- [Lottie Compose](https://github.com/airbnb/lottie) - A library that provides Lottie animation support for Jetpack Compose
|
||||
- [Landscapist](https://github.com/skydoves/landscapist) - A Compose and KPP image loading library that streamlines Glide, Coil, and Fresco
|
||||
- [Zoomable](https://github.com/usuiat/Zoomable) - A library that provides a zoomable and pannable view, which can be used with any view you want
|
||||
- [AnimatedFABMenu](https://github.com/rajaumair7890/AnimatedFABMenu) - A animated floating action button with Material 3 design
|
||||
- [DocumentFileCompat](https://github.com/ItzNotABug/DocumentFileCompat) - A DocumentFile wrapper that caches the result to improve efficiency
|
||||
- [LazyColumnScrollbar](https://github.com/nanihadesuka/LazyColumnScrollbar) - A Compose scrollbar library
|
||||
- [compose-collapsing-toolbar](https://github.com/onebone/compose-collapsing-toolbar) - A Compose library that provides a collapsing toolbar
|
||||
## Tech Stack
|
||||
|
||||
Thanks to the creators and maintainers of the open-source libraries used in this project.
|
||||
| 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/) |
|
||||
|
||||
## Build
|
||||
<details>
|
||||
<summary><b>View all dependencies</b></summary>
|
||||
|
||||
This project is built using Kotlin, Java, and Gradle. Here are the steps to build the project:
|
||||
- [Zoomable](https://github.com/usuiat/Zoomable) — Zoomable and pannable views
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
- `AlbumRepository` owns library mutations. Imports, reordering, removal, covers,
|
||||
and queue invalidation use Room transactions; provider scans run outside them.
|
||||
- `DocumentSource` and `WallpaperRenderer` (domain interfaces, Android implementations in
|
||||
`data/source`) keep use cases free of document-provider and bitmap-decoding details.
|
||||
- `WallpaperRepository` owns rotation queues and current-wallpaper records.
|
||||
Queue creation checks and writes in one transaction, including synchronized screens.
|
||||
Static changes and the live wallpaper engine both dequeue through
|
||||
`ChangeWallpaperUseCase.dequeueNext`.
|
||||
- `WallpaperController` shares static wallpaper application between the service
|
||||
and worker. Callers hold `WallpaperChangeLock` through application and schedule
|
||||
updates. The controller recycles applied bitmaps.
|
||||
- `SettingsCoordinator` persists wallpaper settings edits and applies their side effects
|
||||
(schedules, queues, immediate changes) one at a time; ViewModels only hold UI state.
|
||||
`WallpaperChangeService` helpers are the single way to start a manual change.
|
||||
- Repositories and use cases throw on failure. ViewModels, services, and workers
|
||||
catch at the edge, using `runCatchingCancellable` where they need a `Result`, so
|
||||
coroutine cancellation always propagates. Progress belongs to UI state.
|
||||
- Room migrations preserve versions 1–3 when upgrading to version 4. New schema
|
||||
changes must include a migration; destructive fallback is disabled.
|
||||
|
||||
## Building from Source
|
||||
|
||||
### Prerequisites
|
||||
- Java 8 (1.8)
|
||||
- Android Studio Jellyfish | 2024.2.1 or later
|
||||
- Android Gradle Plugin 8.7.0 or later
|
||||
- Gradle 8.10.2
|
||||
- Minimum SDK 26
|
||||
|
||||
### Steps
|
||||
- Open a terminal and run the following git command: <pre>git clone https://github.com/Anthonyy232/Paperize.git </pre>
|
||||
- Launch Android Studio and choose Open an existing Android Studio project. Navigate to the cloned repository and select the root folder of the project.
|
||||
- In Android Studio, click on Build -> Generate Signed Bundle / APK and follow the instructions to generate an APK
|
||||
- Alternatively, click `▶ Run` and build the app and run it immediately
|
||||
| Requirement | Version |
|
||||
|-------------|---------|
|
||||
| Java | 17 |
|
||||
| Android Gradle Plugin | 9.3.2 |
|
||||
| Gradle | 9.7.1 |
|
||||
| Compile SDK | 37 (Android 17) |
|
||||
| Minimum SDK | 31 (Android 12) |
|
||||
| Target SDK | 36 |
|
||||
|
||||
### Build Steps
|
||||
|
||||
## Contributions
|
||||
1. **Clone the repository**
|
||||
```bash
|
||||
git clone https://github.com/Anthonyy232/Paperize.git
|
||||
cd Paperize
|
||||
```
|
||||
|
||||
All contributions to the app is welcome. Feel free to report any issues and create pull requests for any issues or pull requests.
|
||||
2. **Open in Android Studio**
|
||||
- Launch Android Studio
|
||||
- Select `File > Open` and navigate to the cloned repository
|
||||
|
||||
Inspiration from j4velin for their wallpaper changer app
|
||||
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
|
||||
|
||||
## Donations
|
||||
---
|
||||
|
||||
If you want to donate, you can do so using GitHub sponsorship (one-time or monthly). I appreciate the thought, thanks!
|
||||
### Verification
|
||||
|
||||
Set `ANDROID_HOME` to your Android SDK directory, or configure `sdk.dir` in
|
||||
`local.properties`. Use the checked-in Gradle wrapper:
|
||||
|
||||
```bash
|
||||
./gradlew testDebugUnitTest lintDebug assembleDebug
|
||||
./gradlew connectedDebugAndroidTest
|
||||
```
|
||||
|
||||
On Windows, use `gradlew.bat`. Device tests require a running Android emulator or
|
||||
connected device (API 31 or newer). They cover rendering, scheduling, document
|
||||
provider failures, import rollback, album cleanup, and library controls.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Feel free to:
|
||||
|
||||
- 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!
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
Contact on my GitHub profile
|
||||
|
||||
[Anthony La](https://github.com/Anthonyy232) © GNU GPL v3.0
|
||||
This project is licensed under the **GNU General Public License v3.0** — see the [LICENSE](LICENSE) file for details.
|
||||
+82
-79
@@ -1,26 +1,42 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("com.google.devtools.ksp")
|
||||
id("com.google.dagger.hilt.android")
|
||||
id("com.mikepenz.aboutlibraries.plugin")
|
||||
id("org.jetbrains.kotlin.plugin.serialization")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
alias(libs.plugins.androidApplication)
|
||||
alias(libs.plugins.kotlinCompose)
|
||||
alias(libs.plugins.hiltAndroid)
|
||||
alias(libs.plugins.ksp)
|
||||
alias(libs.plugins.kotlinSerialization)
|
||||
}
|
||||
|
||||
ksp {
|
||||
arg("room.schemaLocation", "$projectDir/schemas")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.anthonyla.paperize"
|
||||
compileSdk = 35
|
||||
compileSdk = 37
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
val storeFilePath = System.getenv("SIGNING_KEYSTORE_PATH")
|
||||
if (storeFilePath != null) {
|
||||
storeFile = file(storeFilePath)
|
||||
storePassword = System.getenv("SIGNING_STORE_PASSWORD")
|
||||
keyAlias = System.getenv("SIGNING_KEY_ALIAS")
|
||||
keyPassword = System.getenv("SIGNING_KEY_PASSWORD")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets.getByName("androidTest").assets.directories.add("$projectDir/schemas")
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.anthonyla.paperize"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 32
|
||||
versionName = "2.3.0"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 58
|
||||
versionName = "4.2.1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
useSupportLibrary = true
|
||||
@@ -30,99 +46,86 @@ android {
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
viewBinding = true
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
composeOptions {
|
||||
kotlinCompilerExtensionVersion = "1.5.15"
|
||||
}
|
||||
|
||||
androidResources {
|
||||
@Suppress("UnstableApiUsage")
|
||||
generateLocaleConfig = true
|
||||
}
|
||||
|
||||
ndkVersion = "26.3.11579264"
|
||||
buildToolsVersion = "34.0.0"
|
||||
dependenciesInfo {
|
||||
includeInApk = false
|
||||
includeInBundle = false
|
||||
}
|
||||
|
||||
aboutLibraries {
|
||||
excludeFields = arrayOf("generated")
|
||||
}
|
||||
}
|
||||
|
||||
androidComponents {
|
||||
onVariants(selector().withBuildType("release")) {
|
||||
it.packaging.resources.excludes.add("META-INF/**")
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.core:core-ktx:1.13.1")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6")
|
||||
implementation("androidx.activity:activity-compose:1.9.2")
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui:1.7.3")
|
||||
implementation("androidx.compose.ui:ui-graphics:1.7.3")
|
||||
implementation("androidx.compose.ui:ui-tooling-preview:1.7.3")
|
||||
implementation("androidx.compose.material3:material3:1.3.0")
|
||||
implementation("androidx.navigation:navigation-compose:2.8.2")
|
||||
implementation("androidx.compose.material:material:1.7.3")
|
||||
implementation("androidx.datastore:datastore:1.1.1")
|
||||
implementation("androidx.datastore:datastore-preferences:1.1.1")
|
||||
implementation("androidx.compose.material:material-icons-extended:1.7.3")
|
||||
implementation("androidx.hilt:hilt-navigation-compose:1.2.0")
|
||||
implementation("androidx.compose.animation:animation:1.7.3")
|
||||
implementation("androidx.core:core-splashscreen:1.2.0-alpha02")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.6")
|
||||
implementation("com.google.code.gson:gson:2.11.0")
|
||||
implementation("androidx.documentfile:documentfile:1.1.0-alpha01")
|
||||
implementation("net.engawapg.lib:zoomable:2.0.0-beta01")
|
||||
implementation("com.github.skydoves:landscapist-glide:2.4.0")
|
||||
implementation("androidx.work:work-runtime-ktx:2.10.0-beta01")
|
||||
implementation("androidx.hilt:hilt-work:1.2.0")
|
||||
implementation("com.airbnb.android:lottie-compose:6.5.2")
|
||||
implementation("com.google.accompanist:accompanist-permissions:0.36.0")
|
||||
implementation("com.mikepenz:aboutlibraries-core:11.2.3")
|
||||
implementation("com.mikepenz:aboutlibraries-compose-m3:11.2.3")
|
||||
implementation("androidx.compose.foundation:foundation:1.7.3")
|
||||
implementation("com.github.nanihadesuka:LazyColumnScrollbar:2.2.0")
|
||||
implementation("com.joaomgcd:taskerpluginlibrary:0.4.10")
|
||||
implementation("com.google.ar.sceneform:filament-android:1.17.1")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
|
||||
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.7.3")
|
||||
debugImplementation("androidx.compose.ui:ui-tooling:1.7.3")
|
||||
debugImplementation("androidx.compose.ui:ui-test-manifest:1.7.3")
|
||||
implementation("com.google.dagger:hilt-android:2.52")
|
||||
ksp("com.google.dagger:hilt-android-compiler:2.52")
|
||||
implementation("androidx.room:room-runtime:2.6.1")
|
||||
ksp("androidx.room:room-compiler:2.6.1")
|
||||
implementation("androidx.room:room-ktx:2.6.1")
|
||||
implementation("com.lazygeniouz:dfc:1.0.8")
|
||||
implementation ("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
|
||||
implementation("com.github.android:renderscript-intrinsics-replacement-toolkit:b6363490c3")
|
||||
implementation("me.onebone:toolbar-compose:2.3.5")
|
||||
}
|
||||
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.coil.compose)
|
||||
implementation(libs.coil.gif)
|
||||
implementation(libs.coil.svg)
|
||||
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.androidx.documentfile)
|
||||
implementation(libs.androidx.exifinterface)
|
||||
implementation(libs.zoomable)
|
||||
implementation(libs.androidx.work.runtime.ktx)
|
||||
implementation(libs.androidx.hilt.work)
|
||||
implementation(libs.androidx.foundation)
|
||||
implementation(libs.androidx.profileinstaller)
|
||||
implementation(libs.reorderable)
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.mockk)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
androidTestImplementation(libs.androidx.ui.test.junit4)
|
||||
debugImplementation(platform(libs.androidx.compose.bom))
|
||||
debugImplementation(libs.androidx.ui.tooling)
|
||||
debugImplementation(libs.androidx.ui.test.manifest)
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.android.compiler)
|
||||
ksp(libs.androidx.hilt.compiler)
|
||||
implementation(libs.androidx.room.runtime)
|
||||
ksp(libs.androidx.room.compiler)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
implementation (libs.kotlinx.serialization.json)
|
||||
}
|
||||
Vendored
+5
-34
@@ -1,37 +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
|
||||
-keepclassmembers class com.anthonyla.paperize.feature.wallpaper.domain.model.Album {
|
||||
!transient <fields>;
|
||||
}
|
||||
-keepclassmembers class com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder {
|
||||
!transient <fields>;
|
||||
}
|
||||
-keepclassmembers class com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper {
|
||||
!transient <fields>;
|
||||
}
|
||||
-keepclassmembers class com.anthonyla.paperize.feature.wallpaper.domain.model.Folder {
|
||||
!transient <fields>;
|
||||
# Strip debug and verbose logging from release builds.
|
||||
-assumenosideeffects class android.util.Log {
|
||||
public static int d(...);
|
||||
public static int v(...);
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
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 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)
|
||||
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)
|
||||
assertEquals(1, found.size)
|
||||
assertEquals("photo.PNG", found.single().name)
|
||||
assertEquals(42L, found.single().lastModified)
|
||||
assertEquals(2, provider.queries)
|
||||
}
|
||||
|
||||
@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)
|
||||
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) }
|
||||
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().insertWallpaper(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().getWallpaperCountByAlbum("one"))
|
||||
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().getWallpaperCountByAlbum("album"))
|
||||
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
|
||||
}
|
||||
}
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import java.io.File
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class WallpaperUtilInstrumentedTest {
|
||||
|
||||
private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
private val files = mutableListOf<File>()
|
||||
|
||||
@After
|
||||
fun cleanUp() {
|
||||
files.forEach(File::delete)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun 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.STRETCH
|
||||
)
|
||||
|
||||
assertNotNull(result)
|
||||
assertEquals(20, result?.width)
|
||||
assertEquals(40, result?.height)
|
||||
result?.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticFillRetainsWideSourceOverflow() {
|
||||
val image = createJpeg(width = 400, height = 200)
|
||||
|
||||
val scrolling = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 100,
|
||||
height = 200,
|
||||
scaling = ScalingType.FILL,
|
||||
preserveSourceOverflow = true
|
||||
)
|
||||
val exactCanvas = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 100,
|
||||
height = 200,
|
||||
scaling = ScalingType.FILL,
|
||||
preserveSourceOverflow = false
|
||||
)
|
||||
|
||||
assertEquals(400, scrolling?.width)
|
||||
assertEquals(200, scrolling?.height)
|
||||
assertEquals(100, exactCanvas?.width)
|
||||
assertEquals(200, exactCanvas?.height)
|
||||
scrolling?.recycle()
|
||||
exactCanvas?.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun 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 android17FoldableSizingIncludesInactiveBuiltInPanel() {
|
||||
assumeTrue(Build.VERSION.SDK_INT >= 37)
|
||||
val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||
val builtInDisplays = displayManager.getDisplays(
|
||||
"android.hardware.display.category.BUILT_IN_DISPLAYS"
|
||||
)
|
||||
assertTrue("Expected both foldable panels", builtInDisplays.size >= 2)
|
||||
|
||||
val expected = selectLargestDisplayDimensions(
|
||||
builtInDisplays.flatMap { display ->
|
||||
display.supportedModes.map { mode ->
|
||||
mode.physicalWidth to mode.physicalHeight
|
||||
}
|
||||
}
|
||||
)
|
||||
val actual = getDeviceScreenSize(context)
|
||||
|
||||
assertNotNull(expected)
|
||||
assertEquals(expected?.first, actual.width)
|
||||
assertEquals(expected?.second, actual.height)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticRenderSizeDoesNotRotateWithForegroundAppConfiguration() {
|
||||
val landscapeConfiguration = Configuration(context.resources.configuration).apply {
|
||||
orientation = Configuration.ORIENTATION_LANDSCAPE
|
||||
}
|
||||
val landscapeContext = context.createConfigurationContext(landscapeConfiguration)
|
||||
val naturalPanel = getDeviceScreenSize(context)
|
||||
val renderSize = getDeviceScreenSize(landscapeContext)
|
||||
|
||||
assertEquals(naturalPanel.width, renderSize.width)
|
||||
assertEquals(naturalPanel.height, renderSize.height)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun disabledStaticEffectsLeaveBitmapUntouched() {
|
||||
val source = mutableBitmap(32, 32, Color.rgb(240, 80, 20))
|
||||
|
||||
val result = processBitmap(
|
||||
source = source,
|
||||
enableDarken = false,
|
||||
darkenPercent = 100,
|
||||
enableBlur = false,
|
||||
blurPercent = 100,
|
||||
enableVignette = false,
|
||||
vignettePercent = 100,
|
||||
enableGrayscale = false,
|
||||
grayscalePercent = 100
|
||||
)
|
||||
|
||||
assertSame(source, result)
|
||||
assertEquals(Color.rgb(240, 80, 20), result.getPixel(16, 16))
|
||||
result.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticDarkenAndGrayscaleEffectsChangePixels() {
|
||||
val white = mutableBitmap(32, 32, Color.WHITE)
|
||||
val darkened = processBitmap(
|
||||
source = white,
|
||||
enableDarken = true,
|
||||
darkenPercent = 100
|
||||
)
|
||||
assertTrue(Color.red(darkened.getPixel(16, 16)) <= 2)
|
||||
if (darkened !== white) white.recycle()
|
||||
darkened.recycle()
|
||||
|
||||
val red = mutableBitmap(32, 32, Color.RED)
|
||||
val grayscale = processBitmap(
|
||||
source = red,
|
||||
enableGrayscale = true,
|
||||
grayscalePercent = 100
|
||||
)
|
||||
val grayPixel = grayscale.getPixel(16, 16)
|
||||
assertTrue(kotlin.math.abs(Color.red(grayPixel) - Color.green(grayPixel)) <= 2)
|
||||
assertTrue(kotlin.math.abs(Color.green(grayPixel) - Color.blue(grayPixel)) <= 2)
|
||||
if (grayscale !== red) red.recycle()
|
||||
grayscale.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticVignetteDarkensEdgesMoreThanCenter() {
|
||||
val source = mutableBitmap(96, 96, Color.WHITE)
|
||||
val result = processBitmap(
|
||||
source = source,
|
||||
enableVignette = true,
|
||||
vignettePercent = 75
|
||||
)
|
||||
|
||||
val center = Color.red(result.getPixel(48, 48))
|
||||
val corner = Color.red(result.getPixel(0, 0))
|
||||
assertTrue("Expected vignette corner ($corner) below center ($center)", corner < center)
|
||||
if (result !== source) source.recycle()
|
||||
result.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticBlurSoftensSharpBoundary() {
|
||||
val source = Bitmap.createBitmap(96, 96, Bitmap.Config.ARGB_8888)
|
||||
for (y in 0 until source.height) {
|
||||
for (x in 0 until source.width) {
|
||||
source.setPixel(x, y, if (x < 48) Color.BLACK else Color.WHITE)
|
||||
}
|
||||
}
|
||||
|
||||
val result = processBitmap(
|
||||
source = source,
|
||||
enableBlur = true,
|
||||
blurPercent = 60
|
||||
)
|
||||
|
||||
val boundary = Color.red(result.getPixel(48, 48))
|
||||
assertTrue("Expected blurred boundary, got $boundary", boundary in 2..253)
|
||||
if (result !== source) source.recycle()
|
||||
result.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticWallpaperChangesRefreshAospWallpaperColors() {
|
||||
assumeTrue(
|
||||
"Wallpaper color extraction test is destructive and must run only on an emulator",
|
||||
Build.FINGERPRINT.contains("/emu") ||
|
||||
Build.FINGERPRINT.contains("generic") ||
|
||||
Build.MODEL.contains("Emulator", ignoreCase = true) ||
|
||||
Build.MODEL.contains("sdk", ignoreCase = true)
|
||||
)
|
||||
val wallpaperManager = WallpaperManager.getInstance(context)
|
||||
val red = mutableBitmap(256, 256, Color.rgb(230, 20, 20))
|
||||
val blue = mutableBitmap(256, 256, Color.rgb(20, 20, 230))
|
||||
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(red, WallpaperManager.FLAG_SYSTEM)
|
||||
val redPrimary = awaitPrimaryWallpaperColor(wallpaperManager) { color ->
|
||||
Color.red(color) > Color.blue(color) * 2
|
||||
}
|
||||
|
||||
wallpaperManager.setBitmapChecked(blue, WallpaperManager.FLAG_SYSTEM)
|
||||
val bluePrimary = awaitPrimaryWallpaperColor(wallpaperManager) { color ->
|
||||
Color.blue(color) > Color.red(color) * 2
|
||||
}
|
||||
|
||||
assertTrue(Color.red(redPrimary) > Color.blue(redPrimary))
|
||||
assertTrue(Color.blue(bluePrimary) > Color.red(bluePrimary))
|
||||
} finally {
|
||||
red.recycle()
|
||||
blue.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun awaitPrimaryWallpaperColor(
|
||||
wallpaperManager: WallpaperManager,
|
||||
predicate: (Int) -> Boolean
|
||||
): Int {
|
||||
val deadline = SystemClock.uptimeMillis() + 10_000L
|
||||
var lastColor: Int? = null
|
||||
while (SystemClock.uptimeMillis() < deadline) {
|
||||
lastColor = wallpaperManager
|
||||
.getWallpaperColors(WallpaperManager.FLAG_SYSTEM)
|
||||
?.primaryColor
|
||||
?.toArgb()
|
||||
if (lastColor != null && predicate(lastColor)) return lastColor
|
||||
SystemClock.sleep(100L)
|
||||
}
|
||||
throw AssertionError("Wallpaper colors did not refresh; last primary color was $lastColor")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
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.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..3) {
|
||||
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)
|
||||
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().getCurrentWallpaper("album", ScreenType.HOME)?.id)
|
||||
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) }
|
||||
}
|
||||
}
|
||||
|
||||
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 = if (version == 1) create.replace("`mediaType` TEXT NOT NULL, ", "")
|
||||
else create.replace("PRIMARY KEY(`id`)", "`cropOffsetX` REAL, `cropOffsetY` REAL, `cropScale` REAL, PRIMARY KEY(`id`)")
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
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.Wallpaper
|
||||
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 wallpapers = WallpaperRepositoryImpl(db)
|
||||
private val albums = AlbumRepositoryImpl(com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db)
|
||||
|
||||
@After fun close() = db.close()
|
||||
|
||||
@Test fun cancellingAChunkedFolderImportRollsBackAllRows() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val folder = Folder.empty("folder", "album").copy(
|
||||
wallpapers = (0..599).map { Wallpaper.empty("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().getWallpaperCountByAlbum("album"))
|
||||
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 = Wallpaper.empty("first", "album").copy(uri = "content://first")
|
||||
db.wallpaperDao().insertWallpaper(first.toEntity())
|
||||
db.wallpaperQueueDao().rebuildQueue("album", ScreenType.HOME, listOf("first"))
|
||||
db.folderDao().insertFolder(Folder.empty("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().getWallpaperCountByAlbum("album"))
|
||||
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 = Wallpaper.empty("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(Folder.empty("folder", "album").toEntity())
|
||||
val later = Wallpaper.empty("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().deleteWallpapersByFolder("folder")
|
||||
db.folderDao().refreshFolderCovers("album")
|
||||
assertNull(db.folderDao().getFolderById("folder")?.coverUri)
|
||||
}
|
||||
|
||||
@Test fun concurrentImportsDeduplicateInsideTheTransaction() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val image = Wallpaper.empty("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().getWallpaperCountByAlbum("album"))
|
||||
|
||||
db.folderDao().insertFolder(Folder.empty("folder", "album").toEntity())
|
||||
assertEquals(1, albums.addWallpapersToAlbum("album", listOf(image.copy(id = "folder-image", folderId = "folder"))))
|
||||
db.folderDao().deleteFolderById("folder")
|
||||
assertEquals(0, albums.addWallpapersToAlbum("album", listOf(image.copy(id = "stale", folderId = "folder"))))
|
||||
}
|
||||
|
||||
@Test fun reorderPersistsNestedImagesWithoutOverwritingMetadata() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val first = Wallpaper.empty("first", "album").copy(uri = "content://first", folderId = "folder")
|
||||
val second = first.copy(id = "second", uri = "content://second")
|
||||
val folder = Folder.empty("folder", "album").copy(wallpapers = listOf(first, second))
|
||||
albums.addFolderToAlbum("album", folder)
|
||||
wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, false)
|
||||
db.wallpaperDao().updateWallpaper(first.copy(fileName = "new-name.jpg").toEntity())
|
||||
|
||||
albums.reorderAlbum("album", listOf(folder.copy(wallpapers = listOf(second, first))), emptyList())
|
||||
assertEquals(listOf("second", "first"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
|
||||
assertEquals("new-name.jpg", db.wallpaperDao().getWallpaperById("first")?.fileName)
|
||||
assertEquals("content://second", db.folderDao().getFolderById("folder")?.coverUri)
|
||||
assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun failedReorderRollsBackEarlierRowsAndPreservesQueue() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val first = Wallpaper.empty("first", "album").copy(uri = "content://first")
|
||||
val second = first.copy(id = "second", uri = "content://second")
|
||||
albums.addWallpapersToAlbum("album", listOf(first, second))
|
||||
wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, false)
|
||||
db.openHelper.writableDatabase.execSQL("""
|
||||
CREATE TRIGGER reject_order BEFORE UPDATE OF displayOrder ON wallpapers
|
||||
WHEN NEW.id = 'first' BEGIN SELECT RAISE(ABORT, 'test write failure'); END
|
||||
""")
|
||||
assertTrue(runCatching { albums.reorderAlbum("album", emptyList(), listOf(second, first)) }.isFailure)
|
||||
assertEquals(listOf("first", "second"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
|
||||
assertEquals(listOf("first", "second"), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
|
||||
}
|
||||
|
||||
@Test fun concurrentQueueCreationKeepsBothScreensInSyncAndDoesNotRefillConsumedItems() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
albums.addWallpapersToAlbum("album", (1..8).map {
|
||||
Wallpaper.empty("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 })
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
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 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
|
||||
)
|
||||
preferences.updateScheduleSettings(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, homeEffects = effects, lockEffects = effects, liveEffects = effects,
|
||||
adaptiveBrightness = true
|
||||
))
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
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, Folder.empty().copy(name = stored).displayName)
|
||||
assertEquals(displayed, Wallpaper.empty().copy(fileName = stored).displayFileName)
|
||||
}
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package com.anthonyla.paperize.presentation
|
||||
|
||||
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.screens.album_view.components.SortBottomSheet
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.SortOption
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.WallpaperItem
|
||||
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.domain.model.Album
|
||||
import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import androidx.compose.ui.semantics.SemanticsActions
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
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.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,
|
||||
appSettings = AppSettings(), wallpaperMode = mode.value,
|
||||
onToggleChanger = {}, onSelectAlbum = { _, _ -> },
|
||||
onUpdateScheduleSettings = { latest = it },
|
||||
onUpdateScheduleSettingsDebounced = { latest = it },
|
||||
onChangeWallpaperNow = {}, homeWallpaperUri = null, lockWallpaperUri = null
|
||||
)
|
||||
}
|
||||
}
|
||||
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<Result<Album>>()
|
||||
var attempts = 0
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
LibraryScreen(emptyList(), {}, { name ->
|
||||
assertEquals("Mountains", name)
|
||||
attempts++
|
||||
if (attempts == 1) pending.await()
|
||||
else Result.success(Album.empty(id = "album", name = name))
|
||||
})
|
||||
}
|
||||
}
|
||||
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.save)).performClick().assertIsNotEnabled()
|
||||
compose.runOnIdle { pending.complete(Result.failure(IllegalStateException("Storage unavailable"))) }
|
||||
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 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(AlbumSummary.empty("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")
|
||||
}
|
||||
|
||||
}
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper.renderer
|
||||
|
||||
import android.graphics.Bitmap
|
||||
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 rendererDrawsTheFinalCrossfadeFrameAndRejectsSupersededUploads() {
|
||||
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.destroy()
|
||||
file.delete()
|
||||
replacement.delete()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyLiveWallpaperShaderCompilesAndLinksOnDevice() {
|
||||
listOf(
|
||||
GLShaders.BLUR_FRAGMENT_SHADER,
|
||||
GLShaders.EFFECTS_FRAGMENT_SHADER
|
||||
).forEach { fragmentShader ->
|
||||
val program = GLUtil.createProgram(GLShaders.VERTEX_SHADER, fragmentShader)
|
||||
assertTrue(program != 0)
|
||||
GLES20.glDeleteProgram(program)
|
||||
}
|
||||
}
|
||||
|
||||
@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)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+171
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,83 +2,115 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.USE_EXACT_ALARM"/>
|
||||
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
||||
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Permissions -->
|
||||
<uses-permission android:name="android.permission.SET_WALLPAPER" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.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"
|
||||
android:required="false" />
|
||||
|
||||
<application
|
||||
android:name=".PaperizeApplication"
|
||||
android:allowBackup="false"
|
||||
android:name=".App"
|
||||
android:persistent="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:icon="@mipmap/app_icon"
|
||||
android:fullBackupContent="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Paperize" tools:targetApi="tiramisu">
|
||||
<activity
|
||||
android:name=".feature.wallpaper.presentation.MainActivity"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.Paperize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data android:resource="@xml/shortcuts" android:name="android.app.shortcuts" />
|
||||
</activity>
|
||||
<activity android:name=".feature.wallpaper.app_shortcut.BroadcastActivity"
|
||||
android:theme="@android:style/Theme.NoDisplay">
|
||||
</activity>
|
||||
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver" />
|
||||
<service android:name=".feature.wallpaper.wallpaper_service.HomeWallpaperService" />
|
||||
<service android:name=".feature.wallpaper.wallpaper_service.LockWallpaperService" />
|
||||
<service
|
||||
android:name=".feature.wallpaper.wallpaper_tile.ChangeWallpaperTileService"
|
||||
android:exported="true"
|
||||
android:label="@string/change_wallpaper"
|
||||
android:icon="@drawable/notification_icon"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter> <action android:name="android.service.quicksettings.action.QS_TILE" /> </intent-filter>
|
||||
</service>
|
||||
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.TIME_SET" />
|
||||
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
android:theme="@style/Theme.Paperize">
|
||||
|
||||
<!-- Disable default WorkManager initialization (using custom Configuration.Provider) -->
|
||||
<provider
|
||||
android:name="androidx.startup.InitializationProvider"
|
||||
android:authorities="${applicationId}.androidx-startup"
|
||||
android:exported="false"
|
||||
tools:node="merge">
|
||||
<meta-data android:name="androidx.emoji2.text.EmojiCompatInitializer"
|
||||
<meta-data
|
||||
android:name="androidx.work.WorkManagerInitializer"
|
||||
android:value="androidx.startup"
|
||||
tools:node="remove" />
|
||||
</provider>
|
||||
|
||||
<!-- Main Activity -->
|
||||
<activity
|
||||
android:name=".feature.wallpaper.tasker_shortcut.ActivityConfigBasicAction"
|
||||
android:name=".presentation.MainActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="uiMode|density|orientation|screenSize|screenLayout|keyboardHidden|keyboard"
|
||||
android:theme="@style/Theme.App.Starting">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.app.shortcuts"
|
||||
android:resource="@xml/shortcuts" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".service.shortcut.WallpaperShortcutActivity"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="false"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity=""
|
||||
android:theme="@android:style/Theme.NoDisplay" />
|
||||
|
||||
<service
|
||||
android:name=".service.wallpaper.WallpaperChangeService"
|
||||
android:enabled="true"
|
||||
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"
|
||||
android:exported="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="Change wallpaper">
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter>
|
||||
<action android:name="com.twofortyfouram.locale.intent.action.EDIT_SETTING" />
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".feature.wallpaper.tasker_shortcut.ActivityConfigBasicEvent"
|
||||
</service>
|
||||
|
||||
<!-- Live Wallpaper Service -->
|
||||
<service
|
||||
android:name=".service.livewallpaper.PaperizeLiveWallpaperService"
|
||||
android:enabled="true"
|
||||
android:exported="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="Change wallpaper event">
|
||||
android:label="@string/live_wallpaper_name"
|
||||
android:permission="android.permission.BIND_WALLPAPER">
|
||||
<intent-filter>
|
||||
<action android:name="net.dinglisch.android.tasker.ACTION_EDIT_EVENT" />
|
||||
<action android:name="android.service.wallpaper.WallpaperService" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<meta-data
|
||||
android:name="android.service.wallpaper"
|
||||
android:resource="@xml/wallpaper" />
|
||||
</service>
|
||||
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
</manifest>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -1,20 +0,0 @@
|
||||
package com.anthonyla.paperize
|
||||
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
|
||||
/**
|
||||
* Application class for Hilt
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class App: Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
val channel = NotificationChannel("wallpaper_service_channel", "Paperize", NotificationManager.IMPORTANCE_LOW)
|
||||
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.anthonyla.paperize
|
||||
|
||||
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 com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.DataResetManager
|
||||
import com.anthonyla.paperize.service.worker.WallpaperScheduler
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltAndroidApp
|
||||
class PaperizeApplication : Application(), Configuration.Provider, DefaultLifecycleObserver {
|
||||
|
||||
@Inject
|
||||
lateinit var workerFactory: HiltWorkerFactory
|
||||
|
||||
@Inject
|
||||
lateinit var wallpaperScheduler: WallpaperScheduler
|
||||
|
||||
override fun onCreate() {
|
||||
super<Application>.onCreate()
|
||||
|
||||
// Must run before any other initialization that accesses DB/preferences
|
||||
DataResetManager.performResetIfNeeded(this)
|
||||
|
||||
createNotificationChannel()
|
||||
|
||||
// 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
|
||||
get() = Configuration.Builder()
|
||||
.setWorkerFactory(workerFactory)
|
||||
.build()
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val channel = NotificationChannel(
|
||||
Constants.NOTIFICATION_CHANNEL_ID,
|
||||
getString(R.string.app_name),
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
).apply {
|
||||
description = getString(R.string.notification_channel_description)
|
||||
setShowBadge(false)
|
||||
}
|
||||
|
||||
val notificationManager = getSystemService(NotificationManager::class.java)
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
wallpaperScheduler.refreshAlbumsNow()
|
||||
}
|
||||
}
|
||||
@@ -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,8 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
enum class ScalingConstants {
|
||||
FIT,
|
||||
FILL,
|
||||
STRETCH,
|
||||
NONE
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
enum class ScalingType {
|
||||
/**
|
||||
* Fill the screen, cropping if necessary
|
||||
*/
|
||||
FILL,
|
||||
|
||||
/**
|
||||
* Fit the entire image, adding letterboxing/pillarboxing if necessary
|
||||
*/
|
||||
FIT,
|
||||
|
||||
STRETCH,
|
||||
|
||||
/**
|
||||
* Display at original size
|
||||
*/
|
||||
NONE;
|
||||
|
||||
companion object {
|
||||
fun fromString(value: String?): ScalingType {
|
||||
return entries.find { it.name.equals(value, ignoreCase = true) } ?: FILL
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
enum class ScreenType {
|
||||
HOME,
|
||||
LOCK,
|
||||
BOTH,
|
||||
LIVE;
|
||||
|
||||
companion object {
|
||||
fun fromString(value: String?): ScreenType {
|
||||
return entries.find { it.name.equals(value, ignoreCase = true) } ?: BOTH
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Constants for application settings
|
||||
*/
|
||||
object SettingsConstants {
|
||||
const val SETTINGS_DATASTORE = "settings_datastore"
|
||||
const val DARK_MODE_TYPE = "dark_mode_type"
|
||||
const val AMOLED_THEME_TYPE = "amoled_theme_type"
|
||||
const val DYNAMIC_THEME_TYPE = "dynamic_theme_type"
|
||||
const val ANIMATE_TYPE = "animate_type"
|
||||
const val ENABLE_CHANGER = "enable_changer"
|
||||
const val ENABLE_HOME_WALLPAPER = "home_wallpaper"
|
||||
const val ENABLE_LOCK_WALLPAPER = "lock_wallpaper"
|
||||
const val CURRENT_HOME_WALLPAPER = "current_home_wallpaper"
|
||||
const val CURRENT_LOCK_WALLPAPER = "current_lock_wallpaper"
|
||||
const val HOME_ALBUM_NAME = "home_album_name"
|
||||
const val LOCK_ALBUM_NAME = "lock_album_name"
|
||||
const val HOME_WALLPAPER_CHANGE_INTERVAL = "home_wallpaper_change_interval"
|
||||
const val LOCK_WALLPAPER_CHANGE_INTERVAL = "lock_wallpaper_change_interval"
|
||||
const val WALLPAPER_CHANGE_INTERVAL_DEFAULT = 15
|
||||
const val WALLPAPER_CHANGE_INTERVAL_MIN = 1
|
||||
const val FIRST_LAUNCH = "first_launch"
|
||||
const val FIRST_SET = "first_set"
|
||||
const val LAST_SET_TIME = "last_set_time"
|
||||
const val NEXT_SET_TIME = "next_set_time"
|
||||
const val HOME_DARKEN_PERCENTAGE = "home_darken_percentage"
|
||||
const val LOCK_DARKEN_PERCENTAGE = "darken_darken_percentage"
|
||||
const val DARKEN = "darken"
|
||||
const val WALLPAPER_SCALING = "wallpaper_scaling"
|
||||
const val SCHEDULE_SEPARATELY = "schedule_separately"
|
||||
const val BLUR = "blur"
|
||||
const val HOME_BLUR_PERCENTAGE = "home_blur_percentage"
|
||||
const val LOCK_BLUR_PERCENTAGE = "lock_blur_percentage"
|
||||
const val VIGNETTE = "vignette"
|
||||
const val HOME_VIGNETTE_PERCENTAGE = "home_vignette_percentage"
|
||||
const val LOCK_VIGNETTE_PERCENTAGE = "lock_vignette_percentage"
|
||||
const val HOME_NEXT_SET_TIME = "next_set_time_1"
|
||||
const val LOCK_NEXT_SET_TIME = "next_set_time_2"
|
||||
const val NEXT_HOME_WALLPAPER = "next_home_wallpaper"
|
||||
const val NEXT_LOCK_WALLPAPER = "next_lock_wallpaper"
|
||||
const val GRAYSCALE = "grayscale"
|
||||
const val HOME_GRAYSCALE_PERCENTAGE = "home_grayscale_percentage"
|
||||
const val LOCK_GRAYSCALE_PERCENTAGE = "lock_grayscale_percentage"
|
||||
const val CHANGE_START_TIME = "change_start_time"
|
||||
const val START_HOUR = "start_hour"
|
||||
const val START_MINUTE = "start_minute"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
class EmptyAlbumException : Exception("Album has no wallpapers")
|
||||
|
||||
class NoValidWallpaperException : Exception("No readable wallpaper found")
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* 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,
|
||||
LIVE;
|
||||
|
||||
companion object {
|
||||
fun fromString(value: String?): WallpaperMode {
|
||||
return entries.find { it.name.equals(value, ignoreCase = true) } ?: STATIC
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,507 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.content.res.Resources
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.ColorMatrix
|
||||
import android.graphics.ColorMatrixColorFilter
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.Log
|
||||
import android.util.Size
|
||||
import android.view.WindowManager
|
||||
import android.view.WindowMetrics
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import androidx.core.net.toUri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.anthonyla.paperize.core.ScreenMetricsCompat.getScreenSize
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.google.android.renderscript.Toolkit
|
||||
import com.lazygeniouz.dfc.file.DocumentFileCompat
|
||||
|
||||
|
||||
enum class Type { HOME, LOCK, SINGLE, REFRESH }
|
||||
|
||||
/**
|
||||
* Get the dimensions of the image from the uri
|
||||
*/
|
||||
fun Uri.getImageDimensions(context: Context): Size? {
|
||||
return try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val exif = ExifInterface(inputStream)
|
||||
var width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
|
||||
var height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
|
||||
if (width == 0 || height == 0) {
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeStream(
|
||||
context.contentResolver.openInputStream(this),
|
||||
null,
|
||||
options
|
||||
)
|
||||
width = options.outWidth
|
||||
height = options.outHeight
|
||||
}
|
||||
Size(width, height)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error getting image dimensions: $e")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the inSampleSize for the image
|
||||
*/
|
||||
fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
|
||||
if (imageSize.width > width || imageSize.height > height) {
|
||||
val heightRatio = (imageSize.height.toFloat() / height.toFloat()).fastRoundToInt()
|
||||
val widthRatio = (imageSize.width.toFloat() / width.toFloat()).fastRoundToInt()
|
||||
return if (heightRatio < widthRatio) { heightRatio } else { widthRatio }
|
||||
}
|
||||
else { return 1 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the screen size of the device without orientation
|
||||
* https://stackoverflow.com/a/70087378
|
||||
*/
|
||||
object ScreenMetricsCompat {
|
||||
private val api: Api =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30() else Api()
|
||||
fun getScreenSize(context: Context): Size = api.getScreenSize(context)
|
||||
@Suppress("DEPRECATION")
|
||||
private open class Api {
|
||||
open fun getScreenSize(context: Context): Size {
|
||||
val display = context.getSystemService(WindowManager::class.java).defaultDisplay
|
||||
val metrics = if (display != null) {
|
||||
DisplayMetrics().also { display.getRealMetrics(it) }
|
||||
} else {
|
||||
Resources.getSystem().displayMetrics
|
||||
}
|
||||
return Size(metrics.widthPixels, metrics.heightPixels)
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.R)
|
||||
private class ApiLevel30 : Api() {
|
||||
override fun getScreenSize(context: Context): Size {
|
||||
val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics
|
||||
return Size(metrics.bounds.width(), metrics.bounds.height())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get device screen size with orientation
|
||||
*/
|
||||
fun getDeviceScreenSize(context: Context): Size {
|
||||
val orientation = context.resources.configuration.orientation
|
||||
val size = getScreenSize(context)
|
||||
return if (orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||
Size(size.width, size.height)
|
||||
} else {
|
||||
Size(size.height, size.width)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a bitmap from a URI that is scaled down to the device's screen size
|
||||
*/
|
||||
fun retrieveBitmap(
|
||||
context: Context,
|
||||
wallpaper: Uri,
|
||||
width: Int,
|
||||
height: Int
|
||||
): Bitmap? {
|
||||
val imageSize = wallpaper.getImageDimensions(context) ?: return null
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
try {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
|
||||
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
|
||||
decoder.setTargetSampleSize(
|
||||
calculateInSampleSize(
|
||||
imageSize,
|
||||
width,
|
||||
height
|
||||
)
|
||||
)
|
||||
decoder.isMutableRequired = true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize =
|
||||
calculateInSampleSize(imageSize, width, height)
|
||||
inMutable = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize =
|
||||
calculateInSampleSize(imageSize, width, height)
|
||||
inMutable = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fit width method
|
||||
* The bitmap will fit into the given width while maintaining the same aspect ratio
|
||||
*/
|
||||
fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
return try {
|
||||
val aspectRatio = source.height.toFloat() / source.width.toFloat()
|
||||
val newHeight = (width * aspectRatio).toInt()
|
||||
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(newBitmap)
|
||||
val scaledBitmap = Bitmap.createScaledBitmap(source, width, newHeight, true)
|
||||
val top = (height - newHeight) / 2f
|
||||
canvas.drawBitmap(scaledBitmap, 0f, top, null)
|
||||
scaledBitmap.recycle()
|
||||
newBitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error fitting bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fit method
|
||||
*/
|
||||
fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
return try {
|
||||
val aspectRatio = source.width.toFloat() / source.height.toFloat()
|
||||
val newWidth: Int
|
||||
val newHeight: Int
|
||||
if (width > height * aspectRatio) {
|
||||
newWidth = width
|
||||
newHeight = (width / aspectRatio).toInt()
|
||||
} else {
|
||||
newHeight = height
|
||||
newWidth = (height * aspectRatio).toInt()
|
||||
}
|
||||
val scaledBitmap = Bitmap.createScaledBitmap(source, newWidth, newHeight, true)
|
||||
val x = ((width - newWidth) / 2f)
|
||||
val y = ((height - newHeight) / 2f)
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
canvas.drawBitmap(scaledBitmap, x, y, null)
|
||||
scaledBitmap.recycle()
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error filling bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stretch the bitmap to fit the given width and height
|
||||
*/
|
||||
fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
return try {
|
||||
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(newBitmap)
|
||||
val bitmap = Bitmap.createScaledBitmap(source, width, height, true)
|
||||
canvas.drawBitmap(bitmap, 0f, 0f, null)
|
||||
bitmap.recycle()
|
||||
newBitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error stretching bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Darken the bitmap by a certain percentage - 0 is darkest, 100 is original
|
||||
*/
|
||||
fun darkenBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
return try {
|
||||
val safePercentage = (100 - percent).coerceIn(0, 100)
|
||||
val factor = 1 - safePercentage / 100f
|
||||
val canvas = Canvas(source)
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(factor, factor, factor, 1f)
|
||||
})
|
||||
}
|
||||
canvas.drawBitmap(source, 0f, 0f, paint)
|
||||
source
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error darkening bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Blur the bitmap by a certain percentage
|
||||
*/
|
||||
fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
return try {
|
||||
val factor = percent.toFloat().div(100f) * 20f
|
||||
Toolkit.blur(source, factor.toInt())
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error darkening bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a vignette effect to the bitmap
|
||||
*/
|
||||
fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
return try {
|
||||
val image = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(image)
|
||||
canvas.drawBitmap(source, 0f, 0f, Paint())
|
||||
val rad: Int = if (source.width < source.height) {
|
||||
val o = (source.height * 2) / 100
|
||||
source.height - o * percent / 3
|
||||
} else {
|
||||
val o = (source.width * 2) / 100
|
||||
source.width - o * percent / 3
|
||||
}
|
||||
val rect = Rect(0, 0, source.width, source.height)
|
||||
val rectF = RectF(rect)
|
||||
val colors = intArrayOf(0, 0, Color.BLACK)
|
||||
val pos = floatArrayOf(0.0f, 0.1f, 1.0f)
|
||||
val linGradLR: Shader = RadialGradient(
|
||||
rect.centerX().toFloat(),
|
||||
rect.centerY().toFloat(),
|
||||
rad.toFloat(),
|
||||
colors,
|
||||
pos,
|
||||
Shader.TileMode.CLAMP
|
||||
)
|
||||
val paint = Paint().apply {
|
||||
shader = linGradLR
|
||||
isAntiAlias = true
|
||||
isDither = true
|
||||
alpha = 128
|
||||
}
|
||||
canvas.drawRect(rectF, paint)
|
||||
image
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error applying vignette effect: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a grey filter to the bitmap based on a percentage
|
||||
*/
|
||||
fun grayBitmap(bitmap: Bitmap, percent: Int): Bitmap {
|
||||
val factor = percent / 100f
|
||||
val colorMatrix = ColorMatrix().apply {
|
||||
setSaturation(1 - factor)
|
||||
}
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(colorMatrix)
|
||||
}
|
||||
val grayBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(grayBitmap)
|
||||
canvas.drawBitmap(bitmap, 0f, 0f, paint)
|
||||
|
||||
return grayBitmap
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the brightness of a bitmap (0-100)
|
||||
* https://gist.github.com/httnn/b1d772caf76cdc0c11e2
|
||||
*/
|
||||
fun calculateBrightness(bitmap: Bitmap, pixelSpacing: Int = 1): Int {
|
||||
var brightness = 0.0
|
||||
val pixels = IntArray(bitmap.width * bitmap.height)
|
||||
bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
|
||||
for (i in pixels.indices step pixelSpacing.coerceAtLeast(1)) {
|
||||
val color = pixels[i]
|
||||
val R = Color.red(color)
|
||||
val G = Color.green(color)
|
||||
val B = Color.blue(color)
|
||||
brightness += 0.299*R + 0.587*G + 0.114*B
|
||||
}
|
||||
return (brightness / (pixels.size / pixelSpacing)).toInt()
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve wallpaper URIs from a folder directory URI
|
||||
*/
|
||||
fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
|
||||
return try {
|
||||
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
|
||||
listFilesRecursive(folderDocumentFile, context)
|
||||
} catch (_: Exception) {
|
||||
val folderDocumentFile = DocumentFile.fromTreeUri(context, folderUri.toUri())
|
||||
listFilesRecursive(folderDocumentFile, context)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to recursively list files in a directory for DocumentFileCompat
|
||||
*/
|
||||
fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<String> {
|
||||
val files = mutableListOf<String>()
|
||||
parent?.listFiles()?.forEach { file ->
|
||||
if (file.isDirectory()) {
|
||||
files.addAll(listFilesRecursive(file, context))
|
||||
} else {
|
||||
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
|
||||
if (file.extension in allowedExtensions) {
|
||||
files.add(file.uri.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
/** Overloaded version of the function for DocumentFile */
|
||||
fun listFilesRecursive(parent: DocumentFile?, context: Context): List<String> {
|
||||
val files = mutableListOf<String>()
|
||||
parent?.listFiles()?.forEach { file ->
|
||||
if (file.isDirectory) {
|
||||
files.addAll(listFilesRecursive(file, context))
|
||||
} else {
|
||||
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
|
||||
if ((file.name?.substringAfterLast(".") ?: "") in allowedExtensions) {
|
||||
files.add(file.uri.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to find the first valid URI from a list of wallpapers
|
||||
* It will search through all wallpapers of an album first, and then all wallpapers of every folder of an album
|
||||
*/
|
||||
fun findFirstValidUri(context: Context, wallpapers: List<Wallpaper>, folders: List<Folder>): String? {
|
||||
wallpapers.forEach { wallpaper ->
|
||||
try {
|
||||
val file = DocumentFileCompat.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
|
||||
if (file?.exists() == true) {
|
||||
return wallpaper.wallpaperUri
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
val file = DocumentFile.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
|
||||
if (file?.exists() == true) {
|
||||
return wallpaper.wallpaperUri
|
||||
}
|
||||
}
|
||||
}
|
||||
folders.forEach { folder ->
|
||||
folder.wallpapers.forEach { wallpaper ->
|
||||
try {
|
||||
val file = DocumentFileCompat.fromSingleUri(context, wallpaper.toUri())
|
||||
if (file?.exists() == true) {
|
||||
return wallpaper
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
val file = DocumentFile.fromSingleUri(context, wallpaper.toUri())
|
||||
if (file?.exists() == true) {
|
||||
return wallpaper
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the folder name from the folder URI
|
||||
*/
|
||||
fun getFolderNameFromUri(folderUri: String, context: Context): String? {
|
||||
return try {
|
||||
DocumentFileCompat.fromTreeUri(context, folderUri.toUri())?.name
|
||||
} catch (_: Exception) {
|
||||
DocumentFile.fromTreeUri(context, folderUri.toUri())?.name
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a URI is valid
|
||||
*/
|
||||
fun isValidUri(context: Context, uriString: String?): Boolean {
|
||||
val uri = uriString?.toUri()
|
||||
return try {
|
||||
uri?.let {
|
||||
val inputStream = context.contentResolver.openInputStream(it)
|
||||
inputStream?.close()
|
||||
}
|
||||
true
|
||||
} catch (_: Exception) { false }
|
||||
}
|
||||
|
||||
/**
|
||||
* Darkens the bitmap by the given percentage and returns it
|
||||
* 0 - lightest, 100 - darkest
|
||||
*/
|
||||
fun processBitmap(
|
||||
width: Int,
|
||||
height: Int,
|
||||
source: Bitmap,
|
||||
darken: Boolean,
|
||||
darkenPercent: Int,
|
||||
scaling: ScalingConstants,
|
||||
blur: Boolean,
|
||||
blurPercent: Int,
|
||||
vignette: Boolean,
|
||||
vignettePercent: Int,
|
||||
grayscale: Boolean,
|
||||
grayscalePercent: Int
|
||||
): Bitmap? {
|
||||
try {
|
||||
var processedBitmap = source
|
||||
|
||||
// Apply wallpaper scaling effects
|
||||
processedBitmap = when (scaling) {
|
||||
ScalingConstants.FILL -> fillBitmap(processedBitmap, width, height)
|
||||
ScalingConstants.FIT -> fitBitmap(processedBitmap, width, height)
|
||||
ScalingConstants.STRETCH -> stretchBitmap(processedBitmap, width, height)
|
||||
ScalingConstants.NONE -> processedBitmap
|
||||
}
|
||||
|
||||
// Apply brightness effect
|
||||
if (darken && darkenPercent < 100) {
|
||||
processedBitmap = darkenBitmap(processedBitmap, darkenPercent)
|
||||
}
|
||||
|
||||
// Apply blur effect
|
||||
if (blur && blurPercent > 0) {
|
||||
processedBitmap = blurBitmap(processedBitmap, blurPercent)
|
||||
}
|
||||
|
||||
// Apply vignette effect
|
||||
if (vignette && vignettePercent > 0) {
|
||||
processedBitmap = vignetteBitmap(processedBitmap, vignettePercent)
|
||||
}
|
||||
|
||||
// Apply gray effect
|
||||
if (grayscale && grayscalePercent > 0) {
|
||||
processedBitmap = grayBitmap(processedBitmap, grayscalePercent)
|
||||
}
|
||||
|
||||
return processedBitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e("PaperizeWallpaperChanger", "Error darkening bitmap", e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.anthonyla.paperize.core.constants
|
||||
|
||||
object Constants {
|
||||
// Database
|
||||
const val DATABASE_NAME = "paperize_database"
|
||||
const val DATABASE_VERSION = 4
|
||||
|
||||
// DataStore
|
||||
const val PREFERENCES_NAME = "paperize_preferences"
|
||||
|
||||
// Notifications
|
||||
const val NOTIFICATION_CHANNEL_ID = "paperize_channel"
|
||||
const val NOTIFICATION_ID = 1
|
||||
|
||||
// Services
|
||||
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 MAX_WORK_RETRY_ATTEMPTS = 3
|
||||
|
||||
// Intents
|
||||
const val EXTRA_SCREEN_TYPE = "screen_type"
|
||||
|
||||
// Wallpaper
|
||||
const val DEFAULT_BLUR_PERCENTAGE = 0
|
||||
const val DEFAULT_DARKEN_PERCENTAGE = 0
|
||||
const val DEFAULT_VIGNETTE_PERCENTAGE = 0
|
||||
const val DEFAULT_PARALLAX_INTENSITY = 50
|
||||
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
|
||||
|
||||
// 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 DEBOUNCE_DELAY_MS = 500L
|
||||
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
|
||||
|
||||
// Luminance coefficients (ITU-R BT.709 standard)
|
||||
const val LUMINANCE_RED = 0.2126
|
||||
const val LUMINANCE_GREEN = 0.7152
|
||||
const val LUMINANCE_BLUE = 0.0722
|
||||
|
||||
// Adaptive brightness thresholds (based on WallYou implementation)
|
||||
const val LIGHT_BRIGHTNESS_MIN = 0.8f
|
||||
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
|
||||
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)
|
||||
|
||||
// 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", "bmp", "gif", "tiff", "tif", "svg"
|
||||
)
|
||||
|
||||
// Renderer
|
||||
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
|
||||
|
||||
// Wallpaper loading
|
||||
const val MAX_WALLPAPER_LOAD_RETRIES = 10
|
||||
}
|
||||
|
||||
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"
|
||||
|
||||
// Live Wallpaper Mode Settings (effect keys are built in SettingsRepositoryImpl)
|
||||
const val LIVE_ALBUM_ID = "live_album_id"
|
||||
const val LIVE_INTERVAL_MINUTES = "live_interval_minutes"
|
||||
|
||||
// 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"
|
||||
const val HOME_SCROLLING_ENABLED = "home_scrolling_enabled"
|
||||
|
||||
const val ADAPTIVE_BRIGHTNESS = "adaptive_brightness"
|
||||
const val FIRST_LAUNCH = "first_launch"
|
||||
const val WALLPAPER_MODE = "wallpaper_mode"
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.net.toUri
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
|
||||
object BatteryOptimizationUtil {
|
||||
private const val TAG = "BatteryOptimizationUtil"
|
||||
|
||||
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
|
||||
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
|
||||
fun requestIgnoreBatteryOptimizations(context: Context) {
|
||||
try {
|
||||
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
|
||||
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)
|
||||
try {
|
||||
val fallbackIntent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
context.startActivity(fallbackIntent)
|
||||
} catch (e2: Exception) {
|
||||
Log.e(TAG, "Error opening battery optimization settings", e2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
object BrightnessCalculator {
|
||||
|
||||
/** 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
|
||||
|
||||
return Constants.LUMINANCE_RED * r + Constants.LUMINANCE_GREEN * g + Constants.LUMINANCE_BLUE * b
|
||||
}
|
||||
|
||||
/** 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
|
||||
|
||||
val rowBuffer = IntArray(w)
|
||||
var totalLuminance = 0.0
|
||||
var pixelCount = 0
|
||||
|
||||
for (y in 0 until h step sampleSize) {
|
||||
bitmap.getPixels(rowBuffer, 0, w, 0, y, w, 1)
|
||||
for (x in 0 until w step sampleSize) {
|
||||
totalLuminance += calculateLuminance(rowBuffer[x])
|
||||
pixelCount++
|
||||
}
|
||||
}
|
||||
|
||||
return (totalLuminance / pixelCount).toFloat()
|
||||
}
|
||||
|
||||
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 {
|
||||
isDarkMode && brightness > lightBrightnessMin -> targetBrightnessDark / brightness
|
||||
!isDarkMode && brightness < darkBrightnessMax -> targetBrightnessLight / brightness
|
||||
else -> 1.0f
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
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.
|
||||
*/
|
||||
object DataResetManager {
|
||||
private const val TAG = "DataResetManager"
|
||||
|
||||
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)
|
||||
*/
|
||||
private const val TARGET_RESET_VERSION = 4
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
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
|
||||
}
|
||||
|
||||
Log.w(TAG, "Performing data reset: upgrading from version $lastResetVersion to $TARGET_RESET_VERSION")
|
||||
|
||||
return try {
|
||||
context.deleteDatabase(Constants.DATABASE_NAME)
|
||||
context.preferencesDataStoreFile(Constants.PREFERENCES_NAME).delete()
|
||||
Log.i(TAG, "Data reset completed successfully")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error during data reset", e)
|
||||
false
|
||||
} 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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.CancellationSignal
|
||||
import android.provider.DocumentsContract
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.runCatchingCancellable
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
fun Uri.isValid(contentResolver: ContentResolver): Boolean {
|
||||
if (scheme != "content") return false
|
||||
|
||||
return try {
|
||||
contentResolver.query(this, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
} ?: 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Only a successful, complete query with no rows proves that a document was removed. */
|
||||
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(android.provider.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")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
)
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
suspend fun Uri.scanFolderImages(context: Context, onProgress: ((found: Int) -> Unit)? = null): List<ScannedImage> {
|
||||
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<ScannedImage>()
|
||||
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
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
onProgress?.invoke(results.size)
|
||||
return results
|
||||
}
|
||||
|
||||
private const val PROGRESS_REPORT_INTERVAL = 512
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.content.ContextCompat
|
||||
|
||||
object PermissionUtil {
|
||||
|
||||
fun hasNotificationPermission(context: Context): Boolean {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.POST_NOTIFICATIONS
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
object QueueBuilder {
|
||||
fun mergeWithExistingQueue(
|
||||
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.shuffled()
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Bitmap
|
||||
import androidx.core.graphics.createBitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.ColorMatrix
|
||||
import android.graphics.ColorMatrixColorFilter
|
||||
import android.graphics.HardwareRenderer
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.PorterDuff
|
||||
import android.graphics.PorterDuffXfermode
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.RenderEffect
|
||||
import android.graphics.RenderNode
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.HardwareBuffer
|
||||
import android.media.ImageReader
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.util.Size
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
import android.view.WindowMetrics
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import androidx.core.graphics.scale
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
|
||||
private const val TAG = "WallpaperUtil"
|
||||
private const val BUILT_IN_DISPLAY_CATEGORY =
|
||||
"android.hardware.display.category.BUILT_IN_DISPLAYS"
|
||||
|
||||
fun Uri.getExifOrientation(context: Context): Int {
|
||||
return try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val exif = ExifInterface(inputStream)
|
||||
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
|
||||
} ?: ExifInterface.ORIENTATION_UNDEFINED
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Error reading EXIF orientation: $e")
|
||||
ExifInterface.ORIENTATION_UNDEFINED
|
||||
}
|
||||
}
|
||||
|
||||
fun getExifTransformationMatrix(orientation: Int, width: Int, height: Int): Matrix {
|
||||
val matrix = Matrix()
|
||||
|
||||
when (orientation) {
|
||||
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> {
|
||||
matrix.setScale(-1f, 1f)
|
||||
matrix.postTranslate(width.toFloat(), 0f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> {
|
||||
matrix.setRotate(180f)
|
||||
matrix.postTranslate(width.toFloat(), height.toFloat())
|
||||
}
|
||||
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
|
||||
matrix.setScale(1f, -1f)
|
||||
matrix.postTranslate(0f, height.toFloat())
|
||||
}
|
||||
ExifInterface.ORIENTATION_TRANSPOSE -> {
|
||||
matrix.setRotate(90f)
|
||||
matrix.postScale(-1f, 1f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> {
|
||||
matrix.setRotate(90f)
|
||||
matrix.postTranslate(height.toFloat(), 0f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_TRANSVERSE -> {
|
||||
matrix.setRotate(-90f)
|
||||
matrix.postScale(-1f, 1f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> {
|
||||
matrix.setRotate(-90f)
|
||||
matrix.postTranslate(0f, width.toFloat())
|
||||
}
|
||||
}
|
||||
|
||||
return matrix
|
||||
}
|
||||
|
||||
fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
|
||||
if (imageSize.width == 0 || imageSize.height == 0) return 1
|
||||
if (width == 0 || height == 0) return 1
|
||||
|
||||
if (imageSize.width > width || imageSize.height > height) {
|
||||
// Integer division (floor) ensures inSampleSize is never larger than needed,
|
||||
// guaranteeing the decoded bitmap is at least as wide/tall as the target.
|
||||
// fastRoundToInt() can round UP, producing a bitmap smaller than the target.
|
||||
val heightRatio = imageSize.height / height
|
||||
val widthRatio = imageSize.width / width
|
||||
return minOf(heightRatio, widthRatio).coerceAtLeast(1)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
fun getDeviceScreenSize(context: Context): Size {
|
||||
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val metrics: WindowMetrics = windowManager.currentWindowMetrics
|
||||
val currentWindow = metrics.bounds.width() to metrics.bounds.height()
|
||||
|
||||
// Display.Mode dimensions are reported in the panel's natural orientation. Prefer them
|
||||
// over currentWindowMetrics so a scheduled change while a landscape game is foregrounded
|
||||
// cannot permanently rotate and over-crop the wallpaper bitmap.
|
||||
val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||
val builtInDisplays = displayManager
|
||||
?.getDisplays(BUILT_IN_DISPLAY_CATEGORY)
|
||||
.orEmpty()
|
||||
val candidateDisplays = if (builtInDisplays.isNotEmpty()) {
|
||||
// Android 17+ returns all built-in panels, including currently inactive panels.
|
||||
builtInDisplays.asSequence()
|
||||
} else {
|
||||
// Compatibility fallback for releases where the built-in category is unknown.
|
||||
// Exclude presentation and app-owned virtual displays.
|
||||
displayManager?.displays
|
||||
?.asSequence()
|
||||
?.filter { display ->
|
||||
display.flags and Display.FLAG_PRESENTATION == 0 &&
|
||||
display.flags and Display.FLAG_PRIVATE == 0
|
||||
}
|
||||
.orEmpty()
|
||||
}
|
||||
val supportedModes = candidateDisplays
|
||||
.flatMap { display ->
|
||||
display.supportedModes.asSequence().map { mode ->
|
||||
mode.physicalWidth to mode.physicalHeight
|
||||
}
|
||||
}
|
||||
.toList()
|
||||
val selected = selectWallpaperDisplayDimensions(currentWindow, supportedModes)
|
||||
return Size(selected.first, selected.second)
|
||||
}
|
||||
|
||||
internal fun selectWallpaperDisplayDimensions(
|
||||
currentWindow: Pair<Int, Int>,
|
||||
supportedModes: Iterable<Pair<Int, Int>>
|
||||
): Pair<Int, Int> = selectLargestDisplayDimensions(supportedModes)
|
||||
?: currentWindow.takeIf { (width, height) -> width > 0 && height > 0 }
|
||||
?: (1 to 1)
|
||||
|
||||
internal fun selectLargestDisplayDimensions(
|
||||
candidates: Iterable<Pair<Int, Int>>
|
||||
): Pair<Int, Int>? = candidates
|
||||
.filter { (width, height) -> width > 0 && height > 0 }
|
||||
.maxWithOrNull(
|
||||
compareBy<Pair<Int, Int>>(
|
||||
{ (width, height) -> width.toLong() * height.toLong() },
|
||||
{ (width, height) -> maxOf(width, height) },
|
||||
{ (width, height) -> minOf(width, height) }
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether a static wallpaper should retain source overflow for launcher-managed scrolling.
|
||||
*
|
||||
* FIT/STRETCH/NONE use an exact launcher canvas so Android cannot rescale them into FILL.
|
||||
*/
|
||||
internal fun usesLauncherManagedScrolling(
|
||||
screenType: com.anthonyla.paperize.core.ScreenType,
|
||||
scaling: ScalingType,
|
||||
scrollingEnabled: Boolean
|
||||
): Boolean =
|
||||
scrollingEnabled &&
|
||||
(screenType == com.anthonyla.paperize.core.ScreenType.HOME ||
|
||||
screenType == com.anthonyla.paperize.core.ScreenType.BOTH) &&
|
||||
scaling == ScalingType.FILL
|
||||
|
||||
fun retrieveBitmap(
|
||||
context: Context,
|
||||
wallpaperUri: Uri,
|
||||
width: Int,
|
||||
height: Int,
|
||||
scaling: ScalingType = ScalingType.FIT,
|
||||
preserveSourceOverflow: Boolean = false
|
||||
): Bitmap? {
|
||||
// ImageDecoder reports dimensions after applying EXIF orientation.
|
||||
var decodedWithImageDecoder = false
|
||||
val bitmap = try {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
|
||||
val result = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||
val (targetW, targetH) = calculateDecodeSize(
|
||||
info.size.width, info.size.height, width, height, scaling
|
||||
)
|
||||
decoder.setTargetSize(targetW, targetH)
|
||||
// Crop during decode to avoid allocating fill-scale overflow.
|
||||
if (scaling == ScalingType.FILL && !preserveSourceOverflow &&
|
||||
(targetW > width || targetH > height)
|
||||
) {
|
||||
val cropX = ((targetW - width) / 2).coerceAtLeast(0)
|
||||
val cropY = ((targetH - height) / 2).coerceAtLeast(0)
|
||||
decoder.setCrop(android.graphics.Rect(cropX, cropY, cropX + width, cropY + height))
|
||||
}
|
||||
|
||||
decoder.isMutableRequired = true
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
}
|
||||
decodedWithImageDecoder = true
|
||||
result
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "ImageDecoder failed, falling back to BitmapFactory: $e")
|
||||
try {
|
||||
val sampleSize = context.contentResolver.openInputStream(wallpaperUri)?.use { stream ->
|
||||
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeStream(stream, null, opts)
|
||||
if (scaling == ScalingType.NONE || opts.outWidth <= 0 || opts.outHeight <= 0) 1
|
||||
else calculateInSampleSize(Size(opts.outWidth, opts.outHeight), width, height)
|
||||
} ?: 1
|
||||
context.contentResolver.openInputStream(wallpaperUri)?.use { stream ->
|
||||
BitmapFactory.decodeStream(stream, null, BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
inMutable = true
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
})
|
||||
}
|
||||
} catch (oom: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM during BitmapFactory fallback for $wallpaperUri: $oom")
|
||||
null
|
||||
}
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM during retrieveBitmap for $wallpaperUri: $e")
|
||||
null
|
||||
}
|
||||
|
||||
// Only apply EXIF orientation for the BitmapFactory path — ImageDecoder already handles it
|
||||
val oriented = if (decodedWithImageDecoder) bitmap else bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
|
||||
|
||||
// An exact canvas prevents the launcher from undoing the selected scaling mode.
|
||||
return oriented?.let {
|
||||
if (preserveSourceOverflow && scaling == ScalingType.FILL) {
|
||||
scaleToFillPreservingOverflow(it, width, height)
|
||||
} else {
|
||||
finalizeToCanvas(it, width, height, scaling)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale [source] just enough to cover one screen while retaining any overflow.
|
||||
*
|
||||
* The returned bitmap may be wider than [width] or taller than [height]. That overflow is what a
|
||||
* launcher uses to scroll a static wallpaper without moving past the source image's real edge.
|
||||
*/
|
||||
private fun scaleToFillPreservingOverflow(
|
||||
source: Bitmap,
|
||||
width: Int,
|
||||
height: Int
|
||||
): Bitmap {
|
||||
val scale = maxOf(
|
||||
width.toFloat() / source.width,
|
||||
height.toFloat() / source.height
|
||||
)
|
||||
val targetW = (source.width * scale).fastRoundToInt()
|
||||
val targetH = (source.height * scale).fastRoundToInt()
|
||||
if (targetW == source.width && targetH == source.height) return source
|
||||
|
||||
val scaled = source.scale(targetW, targetH)
|
||||
if (scaled !== source) source.recycle()
|
||||
return scaled
|
||||
}
|
||||
|
||||
/** Render either decoder's output onto the requested canvas; consumes [source]. */
|
||||
internal fun finalizeToCanvas(source: Bitmap, canvasW: Int, canvasH: Int, scaling: ScalingType): Bitmap {
|
||||
if (source.width == canvasW && source.height == canvasH) return source
|
||||
val widthRatio = canvasW.toFloat() / source.width
|
||||
val heightRatio = canvasH.toFloat() / source.height
|
||||
val scale = when (scaling) {
|
||||
ScalingType.FILL -> maxOf(widthRatio, heightRatio)
|
||||
ScalingType.FIT -> minOf(widthRatio, heightRatio)
|
||||
ScalingType.NONE, ScalingType.STRETCH -> 1f
|
||||
}
|
||||
val width = if (scaling == ScalingType.STRETCH) canvasW.toFloat() else source.width * scale
|
||||
val height = if (scaling == ScalingType.STRETCH) canvasH.toFloat() else source.height * scale
|
||||
val left = (canvasW - width) / 2f
|
||||
val top = (canvasH - height) / 2f
|
||||
val result = createBitmap(canvasW, canvasH)
|
||||
Canvas(result).apply {
|
||||
drawColor(Color.BLACK)
|
||||
drawBitmap(source, null, RectF(left, top, left + width, top + height), Paint(Paint.FILTER_BITMAP_FLAG))
|
||||
}
|
||||
source.recycle()
|
||||
return result
|
||||
}
|
||||
|
||||
private fun applyExifOrientation(source: Bitmap, uri: Uri, context: Context): Bitmap {
|
||||
val orientation = uri.getExifOrientation(context)
|
||||
if (orientation == ExifInterface.ORIENTATION_UNDEFINED || orientation == ExifInterface.ORIENTATION_NORMAL) {
|
||||
return source
|
||||
}
|
||||
|
||||
return try {
|
||||
val matrix = getExifTransformationMatrix(orientation, source.width, source.height)
|
||||
val rotated = Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
|
||||
if (rotated != source) {
|
||||
source.recycle() // Recycle old bitmap to free memory
|
||||
}
|
||||
rotated
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error applying EXIF orientation: $e")
|
||||
source
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM applying EXIF orientation: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawVignette(canvas: Canvas, width: Int, height: Int, percent: Int) {
|
||||
val centerX = width / 2f
|
||||
val centerY = height / 2f
|
||||
val radius = (kotlin.math.hypot(centerX, centerY) *
|
||||
(1 - percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))
|
||||
.coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
shader = RadialGradient(
|
||||
centerX, centerY, radius,
|
||||
intArrayOf(
|
||||
Color.TRANSPARENT,
|
||||
Color.argb((Constants.VIGNETTE_INNER_ALPHA * 255).toInt(), 0, 0, 0),
|
||||
Color.argb((Constants.VIGNETTE_OUTER_ALPHA * 255).toInt(), 0, 0, 0)
|
||||
),
|
||||
Constants.VIGNETTE_GRADIENT_POSITIONS, Shader.TileMode.CLAMP
|
||||
)
|
||||
}
|
||||
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust bitmap brightness by a multiplier
|
||||
* @param brightnessFactor Brightness multiplier (e.g., 0.7 to darken, 1.5 to brighten)
|
||||
*/
|
||||
fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
if (brightnessFactor == 1.0f) return source
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "adjustBitmapBrightness received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return adjustBitmapBrightness(mutableCopy, brightnessFactor)
|
||||
}
|
||||
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(brightnessFactor, brightnessFactor, brightnessFactor, 1f)
|
||||
})
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
}
|
||||
|
||||
fun getAdaptiveBrightnessMultiplier(context: Context, brightness: Float): Float {
|
||||
val isDarkMode = (context.resources.configuration.uiMode and
|
||||
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
|
||||
return BrightnessCalculator.getAdaptiveMultiplier(isDarkMode, brightness)
|
||||
}
|
||||
|
||||
fun adaptiveBrightnessAdjustment(context: Context, source: Bitmap): Bitmap {
|
||||
val brightness = BrightnessCalculator.calculateBitmapBrightness(source)
|
||||
return adjustBitmapBrightness(source, getAdaptiveBrightnessMultiplier(context, brightness))
|
||||
}
|
||||
|
||||
fun processBitmap(
|
||||
source: Bitmap,
|
||||
enableDarken: Boolean = false,
|
||||
darkenPercent: Int = 0,
|
||||
enableBlur: Boolean = false,
|
||||
blurPercent: Int = 0,
|
||||
enableVignette: Boolean = false,
|
||||
vignettePercent: Int = 0,
|
||||
enableGrayscale: Boolean = false,
|
||||
grayscalePercent: Int = 0
|
||||
): Bitmap {
|
||||
val hasDarken = enableDarken && darkenPercent > 0
|
||||
val hasBlur = enableBlur && blurPercent > 0
|
||||
val hasVignette = enableVignette && vignettePercent > 0
|
||||
val hasGrayscale = enableGrayscale && grayscalePercent > 0
|
||||
if (!hasDarken && !hasBlur && !hasVignette && !hasGrayscale) return source
|
||||
|
||||
try {
|
||||
return processBitmapGpu(
|
||||
source,
|
||||
hasDarken, darkenPercent,
|
||||
hasBlur, blurPercent,
|
||||
hasVignette, vignettePercent,
|
||||
hasGrayscale, grayscalePercent
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "GPU effects pipeline failed, falling back to CPU: $e")
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.w(TAG, "OOM in GPU effects pipeline, falling back to CPU: $e")
|
||||
}
|
||||
|
||||
return processBitmapCpu(
|
||||
source,
|
||||
hasDarken, darkenPercent,
|
||||
hasVignette, vignettePercent,
|
||||
hasGrayscale, grayscalePercent
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* GPU-accelerated effects pipeline.
|
||||
*
|
||||
* Chains darken, blur, and grayscale as [RenderEffect]s on a single [RenderNode],
|
||||
* draws the vignette overlay on the same canvas, and reads back the result once.
|
||||
*/
|
||||
private fun processBitmapGpu(
|
||||
source: Bitmap,
|
||||
hasDarken: Boolean, darkenPercent: Int,
|
||||
hasBlur: Boolean, blurPercent: Int,
|
||||
hasVignette: Boolean, vignettePercent: Int,
|
||||
hasGrayscale: Boolean, grayscalePercent: Int
|
||||
): Bitmap {
|
||||
val w = source.width
|
||||
val h = source.height
|
||||
|
||||
val imageReader = ImageReader.newInstance(
|
||||
w, h, PixelFormat.RGBA_8888, 1,
|
||||
HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
|
||||
)
|
||||
val renderNode = RenderNode("EffectsChain")
|
||||
val hardwareRenderer = HardwareRenderer()
|
||||
|
||||
try {
|
||||
hardwareRenderer.setSurface(imageReader.surface)
|
||||
hardwareRenderer.setContentRoot(renderNode)
|
||||
renderNode.setPosition(0, 0, w, h)
|
||||
|
||||
var effect: RenderEffect? = null
|
||||
|
||||
if (hasDarken) {
|
||||
val factor = (100 - darkenPercent.coerceIn(0, 100)) / 100f
|
||||
val cm = ColorMatrix().apply { setScale(factor, factor, factor, 1f) }
|
||||
val darkenEffect = RenderEffect.createColorFilterEffect(ColorMatrixColorFilter(cm))
|
||||
effect = darkenEffect
|
||||
}
|
||||
|
||||
if (hasBlur) {
|
||||
val radius = (blurPercent.coerceIn(0, 100) / 100f) * Constants.MAX_BLUR_RADIUS
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP)
|
||||
effect = if (effect != null) {
|
||||
RenderEffect.createChainEffect(blurEffect, effect)
|
||||
} else {
|
||||
blurEffect
|
||||
}
|
||||
}
|
||||
|
||||
if (hasGrayscale) {
|
||||
val factor = grayscalePercent.coerceIn(0, 100) / 100f
|
||||
val cm = ColorMatrix().apply { setSaturation(1 - factor) }
|
||||
val gsEffect = RenderEffect.createColorFilterEffect(ColorMatrixColorFilter(cm))
|
||||
effect = if (effect != null) {
|
||||
RenderEffect.createChainEffect(gsEffect, effect)
|
||||
} else {
|
||||
gsEffect
|
||||
}
|
||||
}
|
||||
|
||||
if (effect != null) {
|
||||
renderNode.setRenderEffect(effect)
|
||||
}
|
||||
|
||||
val canvas = renderNode.beginRecording()
|
||||
canvas.drawBitmap(source, 0f, 0f, null)
|
||||
|
||||
if (hasVignette) {
|
||||
drawVignette(canvas, w, h, vignettePercent)
|
||||
}
|
||||
|
||||
renderNode.endRecording()
|
||||
|
||||
hardwareRenderer.createRenderRequest()
|
||||
.setWaitForPresent(true)
|
||||
.syncAndDraw()
|
||||
|
||||
return checkNotNull(imageReader.acquireNextImage()) { "Failed to acquire rendered image" }.use { image ->
|
||||
checkNotNull(image.hardwareBuffer) { "Failed to acquire hardware buffer" }.use { buffer ->
|
||||
val bitmap = checkNotNull(Bitmap.wrapHardwareBuffer(buffer, null)) { "Failed to wrap hardware buffer" }
|
||||
try {
|
||||
checkNotNull(bitmap.copy(Bitmap.Config.ARGB_8888, true)) { "Failed to copy hardware bitmap" }
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
hardwareRenderer.destroy()
|
||||
renderNode.discardDisplayList()
|
||||
imageReader.close()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback when the GPU pipeline fails. Darken, grayscale and vignette are plain canvas
|
||||
* operations; blur requires [RenderEffect], so it is skipped here.
|
||||
*/
|
||||
private fun processBitmapCpu(
|
||||
source: Bitmap,
|
||||
hasDarken: Boolean, darkenPercent: Int,
|
||||
hasVignette: Boolean, vignettePercent: Int,
|
||||
hasGrayscale: Boolean, grayscalePercent: Int
|
||||
): Bitmap {
|
||||
// The caller owns and recycles [source] if a copy is returned.
|
||||
val result = if (source.isMutable) source else source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
val canvas = Canvas(result)
|
||||
if (hasDarken || hasGrayscale) {
|
||||
val colorMatrix = ColorMatrix()
|
||||
if (hasGrayscale) colorMatrix.setSaturation(1 - grayscalePercent.coerceIn(0, 100) / 100f)
|
||||
if (hasDarken) {
|
||||
val factor = (100 - darkenPercent.coerceIn(0, 100)) / 100f
|
||||
colorMatrix.postConcat(ColorMatrix().apply { setScale(factor, factor, factor, 1f) })
|
||||
}
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(colorMatrix)
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
canvas.drawBitmap(result, 0f, 0f, paint)
|
||||
}
|
||||
if (hasVignette) drawVignette(canvas, result.width, result.height, vignettePercent)
|
||||
return result
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.anthonyla.paperize.data
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.core.content.ContextCompat.startActivity
|
||||
|
||||
/**
|
||||
* Opens an email intent to contact the developer.
|
||||
*/
|
||||
fun SendContactIntent(context: Context) {
|
||||
val authorEmail = "anthonyyla.dev@gmail.com"
|
||||
val cc = ""
|
||||
val subject = "[Support] Paperize"
|
||||
val bodyText = "This is regarding the Paperize app for Android:\n"
|
||||
val mailto = "mailto:" + Uri.encode(authorEmail) +
|
||||
"?cc=" + Uri.encode(cc) +
|
||||
"&subject=" + Uri.encode(subject) +
|
||||
"&body=" + Uri.encode(bodyText)
|
||||
|
||||
val emailIntent = Intent(Intent.ACTION_SENDTO)
|
||||
emailIntent.setData(Uri.parse(mailto))
|
||||
startActivity(context, emailIntent, null)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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 { 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()
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.anthonyla.paperize.data.database
|
||||
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import com.anthonyla.paperize.data.database.converters.TypeConverters as PaperizeTypeConverters
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
@Database(
|
||||
entities = [
|
||||
AlbumEntity::class,
|
||||
WallpaperEntity::class,
|
||||
FolderEntity::class,
|
||||
WallpaperQueueEntity::class,
|
||||
WallpaperCurrentEntity::class
|
||||
],
|
||||
version = Constants.DATABASE_VERSION,
|
||||
exportSchema = true
|
||||
)
|
||||
@TypeConverters(PaperizeTypeConverters::class)
|
||||
abstract class PaperizeDatabase : RoomDatabase() {
|
||||
abstract fun albumDao(): AlbumDao
|
||||
abstract fun wallpaperDao(): WallpaperDao
|
||||
abstract fun folderDao(): FolderDao
|
||||
abstract fun wallpaperQueueDao(): WallpaperQueueDao
|
||||
abstract fun wallpaperCurrentDao(): WallpaperCurrentDao
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.anthonyla.paperize.data.database.converters
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
class TypeConverters {
|
||||
@TypeConverter
|
||||
fun fromScreenType(value: ScreenType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toScreenType(value: String): ScreenType = ScreenType.fromString(value)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import com.anthonyla.paperize.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
|
||||
|
||||
@Dao
|
||||
interface AlbumDao {
|
||||
@Query("""
|
||||
SELECT
|
||||
a.id,
|
||||
a.name,
|
||||
a.coverUri,
|
||||
a.createdAt,
|
||||
a.modifiedAt,
|
||||
(SELECT COUNT(*) FROM wallpapers w WHERE w.albumId = a.id) as wallpaperCount,
|
||||
(SELECT COUNT(*) FROM folders f WHERE f.albumId = a.id) as folderCount
|
||||
FROM albums a
|
||||
ORDER BY a.modifiedAt DESC
|
||||
""")
|
||||
fun getAlbumSummaries(): Flow<List<AlbumSummaryEntity>>
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM albums WHERE id = :albumId")
|
||||
fun getAlbumWithDetails(albumId: String): Flow<AlbumWithDetails?>
|
||||
|
||||
@Query("SELECT * FROM albums WHERE id = :albumId")
|
||||
suspend fun getAlbumById(albumId: String): AlbumEntity?
|
||||
|
||||
@Query("SELECT * FROM albums WHERE name = :name LIMIT 1")
|
||||
suspend fun getAlbumByName(name: String): AlbumEntity?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAlbum(album: AlbumEntity)
|
||||
|
||||
@Query("DELETE FROM albums WHERE id = :albumId")
|
||||
suspend fun deleteAlbumById(albumId: String)
|
||||
|
||||
@Query("UPDATE albums SET coverUri = :coverUri, modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumCover(albumId: String, coverUri: String?, modifiedAt: Long)
|
||||
|
||||
@Query("UPDATE albums SET modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumModifiedTime(albumId: String, modifiedAt: Long)
|
||||
|
||||
@Query("DELETE FROM albums")
|
||||
suspend fun deleteAllAlbums()
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface FolderDao {
|
||||
@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
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM folders WHERE id = :folderId")
|
||||
fun getFolderWithWallpapers(folderId: String): Flow<FolderWithWallpapers?>
|
||||
|
||||
@Query("SELECT * FROM folders WHERE id = :folderId")
|
||||
suspend fun getFolderById(folderId: String): FolderEntity?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertFolder(folder: FolderEntity)
|
||||
|
||||
@Query("UPDATE folders SET displayOrder = :order WHERE id = :folderId AND albumId = :albumId")
|
||||
suspend fun updateFolderOrder(albumId: String, folderId: String, order: Int)
|
||||
|
||||
@Query("UPDATE folders SET coverUri = :coverUri WHERE id = :folderId")
|
||||
suspend fun updateFolderCover(folderId: String, coverUri: 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)
|
||||
|
||||
@Query("DELETE FROM folders WHERE id = :folderId")
|
||||
suspend fun deleteFolderById(folderId: String)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface WallpaperCurrentDao {
|
||||
|
||||
/**
|
||||
* Return the wallpaper entity that was last applied for this album/screen,
|
||||
* or null if none has been recorded yet (or if it was deleted via CASCADE).
|
||||
*/
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
|
||||
WHERE wc.albumId = :albumId AND wc.screenType = :screenType
|
||||
LIMIT 1
|
||||
""")
|
||||
suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity?
|
||||
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
|
||||
WHERE wc.albumId = :albumId AND wc.screenType = :screenType
|
||||
LIMIT 1
|
||||
""")
|
||||
fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<WallpaperEntity?>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertCurrentWallpaper(entity: WallpaperCurrentEntity)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
|
||||
@Dao
|
||||
interface WallpaperDao {
|
||||
@Query("DELETE FROM wallpapers WHERE albumId = :albumId AND id IN (:ids)")
|
||||
suspend fun deleteAlbumWallpapers(albumId: String, ids: List<String>): Int
|
||||
|
||||
@Query("SELECT uri FROM wallpapers WHERE albumId = :albumId AND folderId IS :folderId")
|
||||
suspend fun getUrisInCollection(albumId: String, folderId: String?): List<String>
|
||||
|
||||
@Query("SELECT COALESCE(MAX(displayOrder), -1) FROM wallpapers WHERE albumId = :albumId")
|
||||
suspend fun getMaxOrder(albumId: String): Int
|
||||
|
||||
@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>
|
||||
|
||||
@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?
|
||||
|
||||
@Query("SELECT * FROM wallpapers WHERE id = :wallpaperId")
|
||||
suspend fun getWallpaperById(wallpaperId: String): WallpaperEntity?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertWallpaper(wallpaper: WallpaperEntity)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertWallpapers(wallpapers: List<WallpaperEntity>)
|
||||
|
||||
@Update
|
||||
suspend fun updateWallpaper(wallpaper: WallpaperEntity)
|
||||
|
||||
@Query("UPDATE wallpapers SET displayOrder = :order WHERE id = :wallpaperId AND albumId = :albumId")
|
||||
suspend fun updateAlbumWallpaperOrder(albumId: String, wallpaperId: String, order: Int)
|
||||
|
||||
@Query("DELETE FROM wallpapers WHERE folderId = :folderId")
|
||||
suspend fun deleteWallpapersByFolder(folderId: String)
|
||||
|
||||
@Query("SELECT COUNT(*) FROM wallpapers WHERE albumId = :albumId")
|
||||
suspend fun getWallpaperCountByAlbum(albumId: String): Int
|
||||
|
||||
@Query("SELECT id FROM wallpapers WHERE albumId = :albumId")
|
||||
suspend fun getWallpaperIdsByAlbum(albumId: String): List<String>
|
||||
|
||||
@Query("SELECT id FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder, id")
|
||||
suspend fun getOrderedWallpaperIdsByAlbum(albumId: String): List<String>
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
|
||||
|
||||
@Dao
|
||||
interface WallpaperQueueDao {
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_queue wq ON w.id = wq.wallpaperId
|
||||
WHERE wq.albumId = :albumId AND wq.screenType = :screenType
|
||||
ORDER BY wq.queuePosition ASC
|
||||
LIMIT 1
|
||||
""")
|
||||
suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): WallpaperEntity?
|
||||
|
||||
@Transaction
|
||||
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity? {
|
||||
val wallpaper = getNextWallpaperInQueue(albumId, screenType)
|
||||
if (wallpaper != null) {
|
||||
deleteQueueItem(albumId, screenType, wallpaper.id)
|
||||
}
|
||||
return wallpaper
|
||||
}
|
||||
|
||||
@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(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertQueueItems(items: List<WallpaperQueueEntity>)
|
||||
|
||||
@Query("""
|
||||
DELETE FROM wallpaper_queue
|
||||
WHERE albumId = :albumId AND screenType = :screenType
|
||||
AND wallpaperId = :wallpaperId
|
||||
""")
|
||||
suspend fun deleteQueueItem(albumId: String, screenType: ScreenType, wallpaperId: String)
|
||||
|
||||
@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)
|
||||
|
||||
@Query("DELETE FROM wallpaper_queue WHERE albumId = :albumId")
|
||||
suspend fun clearAllQueues(albumId: String)
|
||||
|
||||
@Query("DELETE FROM wallpaper_queue")
|
||||
suspend fun deleteAllQueueItems()
|
||||
|
||||
@Transaction
|
||||
suspend fun rebuildQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperIds: List<String>
|
||||
) {
|
||||
clearQueue(albumId, screenType)
|
||||
val items = wallpaperIds.mapIndexed { index, wallpaperId ->
|
||||
WallpaperQueueEntity(
|
||||
albumId = albumId,
|
||||
wallpaperId = wallpaperId,
|
||||
screenType = screenType,
|
||||
queuePosition = index
|
||||
)
|
||||
}
|
||||
insertQueueItems(items)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(tableName = "albums")
|
||||
data class AlbumEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
val name: String,
|
||||
val coverUri: String?,
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
val modifiedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
data class AlbumSummaryEntity(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val coverUri: String?,
|
||||
val wallpaperCount: Int,
|
||||
val folderCount: Int,
|
||||
val createdAt: Long,
|
||||
val modifiedAt: Long
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(
|
||||
tableName = "folders",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [
|
||||
Index(value = ["albumId"]),
|
||||
Index(value = ["uri"])
|
||||
]
|
||||
)
|
||||
data class FolderEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
|
||||
val albumId: String,
|
||||
|
||||
val name: String,
|
||||
val uri: String,
|
||||
val coverUri: String?,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
/**
|
||||
* Room entity tracking the last-applied wallpaper per (album, screen).
|
||||
*
|
||||
* A CASCADE on both FKs means: if the album or wallpaper is deleted the entry
|
||||
* disappears automatically — the service will then fall back to a normal queue
|
||||
* advance instead of reapplying a stale URI.
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "wallpaper_current",
|
||||
primaryKeys = ["albumId", "screenType"],
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
),
|
||||
ForeignKey(
|
||||
entity = WallpaperEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["wallpaperId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [Index(value = ["wallpaperId"])]
|
||||
)
|
||||
data class WallpaperCurrentEntity(
|
||||
val albumId: String,
|
||||
|
||||
val screenType: ScreenType,
|
||||
|
||||
val wallpaperId: String,
|
||||
|
||||
val appliedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(
|
||||
tableName = "wallpapers",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
),
|
||||
ForeignKey(
|
||||
entity = FolderEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["folderId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [
|
||||
Index(value = ["albumId"]),
|
||||
Index(value = ["folderId"]),
|
||||
Index(value = ["uri"])
|
||||
]
|
||||
)
|
||||
data class WallpaperEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
|
||||
val albumId: String,
|
||||
|
||||
val folderId: String? = null,
|
||||
|
||||
val uri: String,
|
||||
val fileName: String,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
// Legacy: always derived from [folderId] ("DIRECT" or "FOLDER").
|
||||
val sourceType: String = "DIRECT",
|
||||
val addedAt: Long = System.currentTimeMillis(),
|
||||
|
||||
// Legacy: Paperize only stores images.
|
||||
val mediaType: String = "IMAGE",
|
||||
)
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
@Entity(
|
||||
tableName = "wallpaper_queue",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
),
|
||||
ForeignKey(
|
||||
entity = WallpaperEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["wallpaperId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [
|
||||
Index(value = ["albumId", "screenType"]),
|
||||
Index(value = ["wallpaperId"]),
|
||||
Index(value = ["queuePosition"])
|
||||
]
|
||||
)
|
||||
data class WallpaperQueueEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0,
|
||||
|
||||
val albumId: String,
|
||||
|
||||
val wallpaperId: String,
|
||||
|
||||
val screenType: ScreenType,
|
||||
val queuePosition: Int,
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.anthonyla.paperize.data.database.relations
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
|
||||
data class AlbumWithDetails(
|
||||
@Embedded
|
||||
val album: AlbumEntity,
|
||||
|
||||
@Relation(
|
||||
parentColumn = "id",
|
||||
entityColumn = "albumId",
|
||||
entity = WallpaperEntity::class
|
||||
)
|
||||
val wallpapers: List<WallpaperEntity> = emptyList(),
|
||||
|
||||
@Relation(
|
||||
parentColumn = "id",
|
||||
entityColumn = "albumId",
|
||||
entity = FolderEntity::class
|
||||
)
|
||||
val folders: List<FolderEntity> = emptyList()
|
||||
)
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.anthonyla.paperize.data.database.relations
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
|
||||
data class FolderWithWallpapers(
|
||||
@Embedded
|
||||
val folder: FolderEntity,
|
||||
|
||||
@Relation(
|
||||
parentColumn = "id",
|
||||
entityColumn = "folderId",
|
||||
entity = WallpaperEntity::class
|
||||
)
|
||||
val wallpapers: List<WallpaperEntity> = emptyList()
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
|
||||
fun AlbumEntity.toDomainModel(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList(),
|
||||
folders: List<com.anthonyla.paperize.domain.model.Folder> = emptyList()
|
||||
): Album = Album(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
wallpapers = wallpapers,
|
||||
folders = folders,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
)
|
||||
|
||||
fun Album.toEntity(): AlbumEntity = AlbumEntity(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
)
|
||||
|
||||
fun AlbumWithDetails.toDomainModel(): Album {
|
||||
val wallpapersByFolder = wallpapers.groupBy { it.folderId }
|
||||
|
||||
val domainWallpapers = wallpapersByFolder[null]?.map { it.toDomainModel() } ?: emptyList()
|
||||
|
||||
val domainFolders = folders.map { folderEntity ->
|
||||
val folderWallpapers = wallpapersByFolder[folderEntity.id]?.map { it.toDomainModel() } ?: emptyList()
|
||||
folderEntity.toDomainModel(folderWallpapers)
|
||||
}
|
||||
|
||||
return album.toDomainModel(
|
||||
wallpapers = domainWallpapers,
|
||||
folders = domainFolders
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
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
|
||||
|
||||
fun FolderEntity.toDomainModel(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList()
|
||||
): Folder = Folder(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
name = name,
|
||||
uri = uri,
|
||||
coverUri = coverUri,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
wallpapers = wallpapers,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun Folder.toEntity(): FolderEntity = FolderEntity(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
name = name,
|
||||
uri = uri,
|
||||
coverUri = coverUri,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun FolderWithWallpapers.toDomainModel(): Folder = folder.toDomainModel(
|
||||
wallpapers = wallpapers.map { it.toDomainModel() }
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
fun WallpaperEntity.toDomainModel(): Wallpaper = Wallpaper(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
folderId = folderId,
|
||||
uri = uri,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
folderId = folderId,
|
||||
uri = uri,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
sourceType = if (folderId == null) "DIRECT" else "FOLDER",
|
||||
addedAt = addedAt
|
||||
)
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.anthonyla.paperize.data
|
||||
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
|
||||
/**
|
||||
* Remember the current offset of a [LazyListState].
|
||||
* Source:
|
||||
* https://stackoverflow.com/a/75677163
|
||||
* https://stackoverflow.com/a/70558512
|
||||
*/
|
||||
@Composable
|
||||
fun rememberCurrentOffset(state: LazyListState): State<Int> {
|
||||
val position = remember { derivedStateOf { state.firstVisibleItemIndex } }
|
||||
val itemOffset = remember { derivedStateOf { state.firstVisibleItemScrollOffset } }
|
||||
val lastPosition = rememberPrevious(position.value)
|
||||
val lastItemOffset = rememberPrevious(itemOffset.value)
|
||||
val currentOffset = remember { mutableIntStateOf(0) }
|
||||
|
||||
LaunchedEffect(position.value, itemOffset.value) {
|
||||
currentOffset.intValue = when {
|
||||
lastPosition == null || position.value == 0 -> itemOffset.value
|
||||
lastPosition == position.value -> currentOffset.intValue + (itemOffset.value - (lastItemOffset ?: 0))
|
||||
lastPosition > position.value -> currentOffset.intValue - (lastItemOffset ?: 0)
|
||||
else -> currentOffset.intValue + itemOffset.value
|
||||
}
|
||||
}
|
||||
|
||||
return currentOffset
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun <T> rememberPrevious(
|
||||
current: T,
|
||||
shouldUpdate: (prev: T?, curr: T) -> Boolean = { prev, curr -> prev != curr },
|
||||
): T? {
|
||||
val ref = rememberRef<T>()
|
||||
SideEffect {
|
||||
if (shouldUpdate(ref.value, current)) {
|
||||
ref.value = current
|
||||
}
|
||||
}
|
||||
return ref.value
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun <T> rememberRef(): MutableState<T?> {
|
||||
return remember {
|
||||
object : MutableState<T?> {
|
||||
override var value: T? = null
|
||||
override fun component1(): T? = value
|
||||
override fun component2(): (T?) -> Unit = { value = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import androidx.room.withTransaction
|
||||
import com.anthonyla.paperize.core.util.generateId
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModel
|
||||
import com.anthonyla.paperize.data.mapper.toEntity
|
||||
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 com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
@Singleton
|
||||
class AlbumRepositoryImpl @Inject constructor(
|
||||
private val documents: DocumentSource,
|
||||
private val database: PaperizeDatabase
|
||||
) : AlbumRepository {
|
||||
private val albumDao = database.albumDao()
|
||||
private val wallpaperDao = database.wallpaperDao()
|
||||
private val folderDao = database.folderDao()
|
||||
|
||||
companion object {
|
||||
private const val WALLPAPER_BATCH_SIZE = 500
|
||||
}
|
||||
|
||||
override fun getAlbumSummaries(): Flow<List<AlbumSummary>> =
|
||||
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 fun getFolderById(folderId: String): Flow<Folder?> =
|
||||
folderDao.getFolderWithWallpapers(folderId).map { it?.toDomainModel() }
|
||||
|
||||
override suspend fun createAlbum(name: String, coverUri: String?): Album {
|
||||
val now = System.currentTimeMillis()
|
||||
val album = Album(id = generateId(), name = name, coverUri = coverUri, createdAt = now, modifiedAt = now)
|
||||
albumDao.insertAlbum(album.toEntity())
|
||||
return album
|
||||
}
|
||||
|
||||
override suspend fun deleteAlbum(albumId: String) {
|
||||
albumDao.deleteAlbumById(albumId)
|
||||
}
|
||||
|
||||
override suspend fun addWallpapersToAlbum(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (saved: Int, total: Int) -> Unit
|
||||
): 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
|
||||
): 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
|
||||
}
|
||||
|
||||
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_BATCH_SIZE).forEach { chunk ->
|
||||
wallpaperDao.insertWallpapers(chunk.map { it.toEntity() })
|
||||
saved += chunk.size
|
||||
onProgress(saved, total)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun reorderAlbum(
|
||||
albumId: String,
|
||||
folders: List<Folder>,
|
||||
wallpapers: List<Wallpaper>
|
||||
) {
|
||||
database.withTransaction {
|
||||
folders.forEachIndexed { index, folder ->
|
||||
folderDao.updateFolderOrder(albumId, folder.id, index)
|
||||
}
|
||||
// Rotation follows direct images, then each folder in the saved order.
|
||||
(wallpapers.asSequence() + folders.asSequence().flatMap { it.wallpapers })
|
||||
.forEachIndexed { index, wallpaper ->
|
||||
wallpaperDao.updateAlbumWallpaperOrder(albumId, wallpaper.id, index)
|
||||
}
|
||||
folderDao.refreshFolderCovers(albumId)
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
database.wallpaperQueueDao().clearAllQueues(albumId)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeWallpapersFromAlbum(
|
||||
albumId: String,
|
||||
wallpaperIds: List<String>
|
||||
) {
|
||||
if (wallpaperIds.isEmpty()) return
|
||||
database.withTransaction {
|
||||
wallpaperIds.chunked(WALLPAPER_BATCH_SIZE).forEach {
|
||||
wallpaperDao.deleteAlbumWallpapers(albumId, it)
|
||||
}
|
||||
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())
|
||||
}
|
||||
removed
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
|
||||
if (album.coverUri != newCoverUri) {
|
||||
albumDao.updateAlbumCover(albumId, newCoverUri, System.currentTimeMillis())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
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.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 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
|
||||
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = Constants.PREFERENCES_NAME
|
||||
)
|
||||
|
||||
private val DARK_MODE = booleanPreferencesKey(PreferenceKeys.DARK_MODE)
|
||||
private val DYNAMIC_THEMING = booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)
|
||||
private val ANIMATE = booleanPreferencesKey(PreferenceKeys.ANIMATE)
|
||||
private val FIRST_LAUNCH = booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)
|
||||
private val WALLPAPER_MODE = stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)
|
||||
private val ENABLE_CHANGER = booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)
|
||||
private val SEPARATE_SCHEDULES = booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)
|
||||
private val SHUFFLE_ENABLED = booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)
|
||||
private val HOME_ENABLED = booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)
|
||||
private val LOCK_ENABLED = booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)
|
||||
private val HOME_ALBUM_ID = stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)
|
||||
private val LOCK_ALBUM_ID = stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)
|
||||
private val LIVE_ALBUM_ID = stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)
|
||||
private val HOME_INTERVAL_MINUTES = intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)
|
||||
private val LOCK_INTERVAL_MINUTES = intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)
|
||||
private val LIVE_INTERVAL_MINUTES = intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)
|
||||
private val HOME_SCALING_TYPE = stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)
|
||||
private val LOCK_SCALING_TYPE = stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)
|
||||
private val LIVE_SCALING_TYPE = stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)
|
||||
private val HOME_SCROLLING_ENABLED = booleanPreferencesKey(PreferenceKeys.HOME_SCROLLING_ENABLED)
|
||||
private val ADAPTIVE_BRIGHTNESS = booleanPreferencesKey(PreferenceKeys.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(
|
||||
@ApplicationContext context: Context
|
||||
) : SettingsRepository {
|
||||
private val dataStore = context.dataStore
|
||||
|
||||
override suspend fun getAppSettings(): AppSettings = getAppSettingsFlow().first()
|
||||
|
||||
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
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun getWallpaperMode(): WallpaperMode = getWallpaperModeFlow().first()
|
||||
|
||||
override fun getWallpaperModeFlow(): Flow<WallpaperMode> =
|
||||
dataStore.data.map { WallpaperMode.fromString(it[WALLPAPER_MODE]) }
|
||||
|
||||
override suspend fun updateWallpaperMode(mode: WallpaperMode) {
|
||||
dataStore.edit { it[WALLPAPER_MODE] = mode.name }
|
||||
}
|
||||
|
||||
override suspend fun getScheduleSettings(): ScheduleSettings = getScheduleSettingsFlow().first()
|
||||
|
||||
override fun getScheduleSettingsFlow(): Flow<ScheduleSettings> = dataStore.data.map(::scheduleSettings)
|
||||
|
||||
override suspend fun updateScheduleSettings(settings: ScheduleSettings) {
|
||||
updateScheduleSettings { settings }
|
||||
}
|
||||
|
||||
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.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 clearAllSettings() {
|
||||
dataStore.edit { it.clear() }
|
||||
}
|
||||
|
||||
override suspend fun clearScheduleSettings() = updateScheduleSettings(ScheduleSettings())
|
||||
|
||||
override suspend fun updateAlbumId(screen: ScreenType, albumId: String?) {
|
||||
dataStore.edit { prefs -> albumIdKeys(screen).forEach { prefs.setOrRemove(it, 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 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 active = if (WallpaperMode.fromString(prefs[WALLPAPER_MODE]) == WallpaperMode.LIVE) {
|
||||
prefs[LIVE_ALBUM_ID] != null
|
||||
} else {
|
||||
(prefs[HOME_ENABLED] == true && prefs[HOME_ALBUM_ID] != null) ||
|
||||
(prefs[LOCK_ENABLED] == true && prefs[LOCK_ALBUM_ID] != null)
|
||||
}
|
||||
if (!active) prefs[ENABLE_CHANGER] = false
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateDarkMode(enabled: Boolean) {
|
||||
dataStore.edit { it[DARK_MODE] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateDynamicTheming(enabled: Boolean) {
|
||||
dataStore.edit { it[DYNAMIC_THEMING] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateAnimate(enabled: Boolean) {
|
||||
dataStore.edit { it[ANIMATE] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateFirstLaunch(isFirstLaunch: Boolean) {
|
||||
dataStore.edit { it[FIRST_LAUNCH] = isFirstLaunch }
|
||||
}
|
||||
|
||||
override suspend fun updateEnableChanger(enabled: Boolean) {
|
||||
dataStore.edit { it[ENABLE_CHANGER] = 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,
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import androidx.room.withTransaction
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
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.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
@Singleton
|
||||
class WallpaperRepositoryImpl @Inject constructor(
|
||||
private val database: PaperizeDatabase
|
||||
) : WallpaperRepository {
|
||||
|
||||
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 getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperQueueDao.getAndDequeueWallpaper(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override suspend fun removeWallpaperFromQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
wallpaperQueueDao.deleteQueueItem(albumId, screenType, wallpaperId)
|
||||
}
|
||||
|
||||
override suspend fun restoreWallpaperToQueueFront(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
wallpaperQueueDao.restoreQueueItem(albumId, screenType, wallpaperId)
|
||||
}
|
||||
|
||||
override suspend fun ensureWallpaperQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
shuffle: Boolean
|
||||
) {
|
||||
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)
|
||||
if (otherQueue.isEmpty()) available.shuffled()
|
||||
else QueueBuilder.mergeWithExistingQueue(otherQueue.map { it.wallpaperId }, available)
|
||||
} else {
|
||||
wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId)
|
||||
}
|
||||
wallpaperQueueDao.rebuildQueue(albumId, screenType, ids)
|
||||
if (otherScreen != null && otherQueue.isEmpty()) {
|
||||
wallpaperQueueDao.rebuildQueue(albumId, otherScreen, ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clearAllQueues() {
|
||||
wallpaperQueueDao.deleteAllQueueItems()
|
||||
}
|
||||
|
||||
override suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperCurrentDao.getCurrentWallpaper(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<Wallpaper?> =
|
||||
wallpaperCurrentDao.getCurrentWallpaperFlow(albumId, screenType).map { it?.toDomainModel() }
|
||||
|
||||
override suspend fun setCurrentWallpaper(albumId: String, screenType: ScreenType, wallpaperId: String) {
|
||||
wallpaperCurrentDao.upsertCurrentWallpaper(
|
||||
WallpaperCurrentEntity(albumId = albumId, screenType = screenType, wallpaperId = wallpaperId)
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.anthonyla.paperize.data.settings
|
||||
|
||||
/**
|
||||
* Interface for the data store that handles the settings for application
|
||||
*/
|
||||
interface SettingsDataStore {
|
||||
suspend fun putBoolean(key: String, value: Boolean)
|
||||
suspend fun putString(key: String, value: String)
|
||||
suspend fun putInt(key: String, value: Int)
|
||||
suspend fun getBoolean(key: String): Boolean?
|
||||
suspend fun getString(key: String): String?
|
||||
suspend fun getInt(key: String): Int?
|
||||
suspend fun deleteBoolean(key: String)
|
||||
suspend fun deleteString(key: String)
|
||||
suspend fun deleteInt(key: String)
|
||||
suspend fun clearPreferences()
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package com.anthonyla.paperize.data.settings
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.anthonyla.paperize.core.SettingsConstants.SETTINGS_DATASTORE
|
||||
import kotlinx.coroutines.flow.first
|
||||
import javax.inject.Inject
|
||||
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = SETTINGS_DATASTORE)
|
||||
|
||||
class SettingsDataStoreImpl(private val context: Context) : SettingsDataStore {
|
||||
override suspend fun putBoolean(key: String, value: Boolean) {
|
||||
val preferencesKey = booleanPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
it[preferencesKey] = value
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun putString(key: String, value: String) {
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
it[preferencesKey] = value
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun putInt(key: String, value: Int) {
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
it[preferencesKey] = value.toString()
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getBoolean(key: String): Boolean? {
|
||||
val head = context.dataStore.data.first()
|
||||
val preferencesKey = booleanPreferencesKey(key)
|
||||
return head[preferencesKey]
|
||||
}
|
||||
|
||||
override suspend fun getString(key: String): String? {
|
||||
return try {
|
||||
val head = context.dataStore.data.first()
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
head[preferencesKey]
|
||||
} catch (exception: Exception) {
|
||||
exception.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getInt(key: String): Int? {
|
||||
return try {
|
||||
val head = context.dataStore.data.first()
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
head[preferencesKey]?.toInt()
|
||||
} catch (exception: Exception) {
|
||||
exception.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteBoolean(key: String) {
|
||||
val preferencesKey = booleanPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
if (it.contains(preferencesKey)) {
|
||||
it.remove(preferencesKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteString(key: String) {
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
if (it.contains(preferencesKey)) {
|
||||
it.remove(preferencesKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteInt(key: String) {
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
if (it.contains(preferencesKey)) {
|
||||
it.remove(preferencesKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clearPreferences() {
|
||||
context.dataStore.edit {
|
||||
it.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.anthonyla.paperize.data.source
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.provider.DocumentsContract
|
||||
import androidx.core.net.toUri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.anthonyla.paperize.core.util.isDocumentMissing
|
||||
import com.anthonyla.paperize.core.util.scanFolderImages
|
||||
import com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import com.anthonyla.paperize.domain.source.SourceFolder
|
||||
import com.anthonyla.paperize.domain.source.SourceImage
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
|
||||
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, onProgress: (Int) -> Unit): SourceFolder = withContext(Dispatchers.IO) {
|
||||
val tree = uri.toUri()
|
||||
val images = tree.scanFolderImages(context, onProgress).map {
|
||||
SourceImage(it.uri.toString(), it.name, it.lastModified)
|
||||
}
|
||||
SourceFolder(DocumentFile.fromTreeUri(context, tree)?.name ?: uri.substringAfterLast('/'), images)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.anthonyla.paperize.data.source
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
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 kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
class AndroidWallpaperRenderer @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context
|
||||
) : 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)
|
||||
var bitmap = retrieveBitmap(context, wallpaper.uri.toUri(), size.width, size.height, scaling,
|
||||
usesLauncherManagedScrolling(screen, scaling, settings.homeScrollingEnabled)) ?: 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,22 @@
|
||||
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.data.settings.SettingsDataStore
|
||||
import com.anthonyla.paperize.data.settings.SettingsDataStoreImpl
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.data_source.AlbumDatabase
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.data_source.SelectedAlbumDatabase
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.repository.AlbumRepositoryImpl
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.repository.SelectedAlbumRepositoryImpl
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
|
||||
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
|
||||
@@ -18,65 +24,33 @@ import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* AppModule provides dependencies for the application for Dagger Hilt to inject
|
||||
*/
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object AppModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumDatabase(app: Application): AlbumDatabase {
|
||||
return Room.databaseBuilder(
|
||||
app,
|
||||
AlbumDatabase::class.java,
|
||||
AlbumDatabase.DATABASE_NAME
|
||||
).fallbackToDestructiveMigration().addMigrations().build()
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSelectedAlbumDatabase(app: Application): SelectedAlbumDatabase {
|
||||
return Room.databaseBuilder(
|
||||
app,
|
||||
SelectedAlbumDatabase::class.java,
|
||||
SelectedAlbumDatabase.DATABASE_NAME
|
||||
).fallbackToDestructiveMigration().addMigrations().build()
|
||||
}
|
||||
fun providePaperizeDatabase(app: Application): PaperizeDatabase =
|
||||
Room.databaseBuilder(app, PaperizeDatabase::class.java, Constants.DATABASE_NAME)
|
||||
.addMigrations(*LIBRARY_MIGRATIONS)
|
||||
.build()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumDao(db: AlbumDatabase) = db.albumDao
|
||||
fun provideWallpaperManager(@ApplicationContext context: Context): WallpaperManager =
|
||||
WallpaperManager.getInstance(context)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumRepository(
|
||||
db: AlbumDatabase
|
||||
): AlbumRepository {
|
||||
return AlbumRepositoryImpl(db.albumDao)
|
||||
}
|
||||
fun provideDocumentSource(source: AndroidDocumentSource): DocumentSource = source
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSelectedAlbumDao(db: SelectedAlbumDatabase) = db.selectedAlbumDao
|
||||
fun provideWallpaperRenderer(renderer: AndroidWallpaperRenderer): WallpaperRenderer = renderer
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSelectedAlbumRepository(
|
||||
db: SelectedAlbumDatabase
|
||||
): SelectedAlbumRepository {
|
||||
return SelectedAlbumRepositoryImpl(db.selectedAlbumDao)
|
||||
}
|
||||
fun provideAlbumRepository(repository: AlbumRepositoryImpl): AlbumRepository = repository
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSettingsDataStore (
|
||||
@ApplicationContext context: Context
|
||||
): SettingsDataStore = SettingsDataStoreImpl(context)
|
||||
fun provideWallpaperRepository(repository: WallpaperRepositoryImpl): WallpaperRepository = repository
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideContext(
|
||||
@ApplicationContext context: Context,
|
||||
): Context { return context }
|
||||
}
|
||||
fun provideSettingsRepository(repository: SettingsRepositoryImpl): SettingsRepository = repository
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
data class Album(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val coverUri: String?,
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
val folders: List<Folder> = emptyList(),
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
val modifiedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
companion object {
|
||||
fun empty(id: String = "", name: String = "") = Album(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = null
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
/**
|
||||
* Lightweight summary of an Album for list displays.
|
||||
* Prevents loading potentially thousands of Wallpaper objects into memory
|
||||
* when just displaying a list of albums.
|
||||
*/
|
||||
data class AlbumSummary(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val coverUri: String?,
|
||||
val wallpaperCount: Int,
|
||||
val folderCount: Int,
|
||||
val createdAt: Long,
|
||||
val modifiedAt: Long
|
||||
) {
|
||||
companion object {
|
||||
fun empty(id: String = "", name: String = "") = AlbumSummary(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = null,
|
||||
wallpaperCount = 0,
|
||||
folderCount = 0,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
modifiedAt = System.currentTimeMillis()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
data class AppSettings(
|
||||
val darkMode: Boolean? = null, // null = system default, true = dark, false = light
|
||||
val dynamicTheming: Boolean = false,
|
||||
val animate: Boolean = true,
|
||||
val firstLaunch: Boolean = true
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import android.net.Uri
|
||||
|
||||
data class Folder(
|
||||
val id: String,
|
||||
val albumId: String,
|
||||
val name: String,
|
||||
val uri: String,
|
||||
val coverUri: String?,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
val displayName: String
|
||||
get() = Uri.decode(name).let { decoded ->
|
||||
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun empty(id: String = "", albumId: String = "") = Folder(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
name = "",
|
||||
uri = "",
|
||||
coverUri = null,
|
||||
dateModified = 0L
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
/** A decoded and processed wallpaper that has not yet been committed as current. */
|
||||
data class PreparedWallpaper(
|
||||
val bitmap: Bitmap,
|
||||
val albumId: String,
|
||||
val screenType: ScreenType,
|
||||
val wallpaperId: String,
|
||||
val shuffle: Boolean
|
||||
)
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
data class ScheduleSettings(
|
||||
val enableChanger: Boolean = false,
|
||||
val separateSchedules: Boolean = false,
|
||||
val shuffleEnabled: Boolean = false,
|
||||
val homeEnabled: Boolean = false,
|
||||
val lockEnabled: Boolean = false,
|
||||
val homeAlbumId: String? = null,
|
||||
val lockAlbumId: String? = null,
|
||||
val homeIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
val lockIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
val liveIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
val homeScalingType: ScalingType = ScalingType.FILL,
|
||||
val lockScalingType: ScalingType = ScalingType.FILL,
|
||||
val homeScrollingEnabled: Boolean = false,
|
||||
val homeEffects: WallpaperEffects = WallpaperEffects(),
|
||||
val lockEffects: WallpaperEffects = WallpaperEffects(),
|
||||
val liveAlbumId: String? = null,
|
||||
val liveScalingType: ScalingType = ScalingType.FILL,
|
||||
val liveEffects: WallpaperEffects = WallpaperEffects(),
|
||||
val adaptiveBrightness: Boolean = false
|
||||
) {
|
||||
val effectiveLockIntervalMinutes: Int
|
||||
get() = if (homeEnabled && lockEnabled && separateSchedules) lockIntervalMinutes else homeIntervalMinutes
|
||||
|
||||
fun hasRequiredAlbums(mode: WallpaperMode): Boolean = when (mode) {
|
||||
WallpaperMode.LIVE -> liveAlbumId != null
|
||||
WallpaperMode.STATIC -> (homeEnabled || lockEnabled) &&
|
||||
(!homeEnabled || homeAlbumId != null) && (!lockEnabled || lockAlbumId != null)
|
||||
}
|
||||
|
||||
fun activeScreens(mode: WallpaperMode): Set<ScreenType> {
|
||||
if (mode == WallpaperMode.LIVE) return if (liveAlbumId != null) setOf(ScreenType.LIVE) else emptySet()
|
||||
val home = homeEnabled && homeAlbumId != null
|
||||
val lock = lockEnabled && lockAlbumId != null
|
||||
if (home && lock && homeAlbumId == lockAlbumId && !separateSchedules) return setOf(ScreenType.BOTH)
|
||||
return buildSet {
|
||||
if (home) add(ScreenType.HOME)
|
||||
if (lock) add(ScreenType.LOCK)
|
||||
}
|
||||
}
|
||||
|
||||
fun intervalMinutes(screen: ScreenType): Int = when (screen) {
|
||||
ScreenType.HOME, ScreenType.BOTH -> homeIntervalMinutes
|
||||
ScreenType.LOCK -> effectiveLockIntervalMinutes
|
||||
ScreenType.LIVE -> liveIntervalMinutes
|
||||
}
|
||||
|
||||
fun validate(): ScheduleSettings = copy(
|
||||
homeIntervalMinutes = homeIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
|
||||
lockIntervalMinutes = lockIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
|
||||
liveIntervalMinutes = liveIntervalMinutes.coerceAtLeast(Constants.MIN_LIVE_INTERVAL_MINUTES),
|
||||
homeEffects = homeEffects.validate(),
|
||||
lockEffects = lockEffects.validate(),
|
||||
liveEffects = liveEffects.validate()
|
||||
)
|
||||
|
||||
fun hasSchedulingChanges(other: ScheduleSettings): Boolean {
|
||||
return enableChanger != other.enableChanger ||
|
||||
homeAlbumId != other.homeAlbumId ||
|
||||
lockAlbumId != other.lockAlbumId ||
|
||||
liveAlbumId != other.liveAlbumId ||
|
||||
homeEnabled != other.homeEnabled ||
|
||||
lockEnabled != other.lockEnabled ||
|
||||
homeIntervalMinutes != other.homeIntervalMinutes ||
|
||||
lockIntervalMinutes != other.lockIntervalMinutes ||
|
||||
separateSchedules != other.separateSchedules ||
|
||||
liveIntervalMinutes != other.liveIntervalMinutes
|
||||
}
|
||||
|
||||
/** Display changes reapply the current wallpaper without rescheduling periodic work. */
|
||||
fun hasDisplayChanges(other: ScheduleSettings): Boolean {
|
||||
return homeScalingType != other.homeScalingType ||
|
||||
lockScalingType != other.lockScalingType ||
|
||||
homeScrollingEnabled != other.homeScrollingEnabled ||
|
||||
homeEffects != other.homeEffects ||
|
||||
lockEffects != other.lockEffects ||
|
||||
liveEffects != other.liveEffects ||
|
||||
liveScalingType != other.liveScalingType ||
|
||||
adaptiveBrightness != other.adaptiveBrightness
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkManager cannot run periodic jobs more often than every 15 minutes. Short live-wallpaper
|
||||
* intervals are therefore driven by the visible wallpaper engine and stop when it is hidden.
|
||||
*/
|
||||
fun usesVisibleLiveTimer(intervalMinutes: Int): Boolean =
|
||||
intervalMinutes in Constants.MIN_LIVE_INTERVAL_MINUTES until Constants.MIN_INTERVAL_MINUTES
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import android.net.Uri
|
||||
|
||||
data class Wallpaper(
|
||||
val id: String,
|
||||
val albumId: String,
|
||||
val folderId: String? = null,
|
||||
val uri: String,
|
||||
val fileName: String,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
val displayFileName: String
|
||||
get() = Uri.decode(fileName).let { decoded ->
|
||||
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun empty(id: String = "", albumId: String = "") = Wallpaper(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
uri = "",
|
||||
fileName = "",
|
||||
dateModified = 0L
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
data class WallpaperEffects(
|
||||
val enableBlur: Boolean = false,
|
||||
val blurPercentage: Int = Constants.DEFAULT_BLUR_PERCENTAGE,
|
||||
val enableDarken: Boolean = false,
|
||||
val darkenPercentage: Int = Constants.DEFAULT_DARKEN_PERCENTAGE,
|
||||
val enableVignette: Boolean = false,
|
||||
val vignettePercentage: Int = Constants.DEFAULT_VIGNETTE_PERCENTAGE,
|
||||
val enableGrayscale: Boolean = false,
|
||||
val grayscalePercentage: Int = Constants.DEFAULT_GRAYSCALE_PERCENTAGE,
|
||||
|
||||
// Interactive effects (live wallpaper mode only)
|
||||
val enableDoubleTap: Boolean = false,
|
||||
val enableChangeOnScreenOff: Boolean = false,
|
||||
val enableParallax: Boolean = false,
|
||||
val parallaxIntensity: Int = Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
) {
|
||||
fun validate(): WallpaperEffects = copy(
|
||||
darkenPercentage = darkenPercentage.coerceIn(0, 100),
|
||||
blurPercentage = blurPercentage.coerceIn(0, 100),
|
||||
vignettePercentage = vignettePercentage.coerceIn(0, 100),
|
||||
grayscalePercentage = grayscalePercentage.coerceIn(0, 100),
|
||||
parallaxIntensity = parallaxIntensity.coerceIn(0, 100)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.anthonyla.paperize.domain.repository
|
||||
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface AlbumRepository {
|
||||
fun getAlbumSummaries(): Flow<List<AlbumSummary>>
|
||||
|
||||
fun getAlbumById(albumId: String): Flow<Album?>
|
||||
|
||||
suspend fun getAlbumByName(name: String): Album?
|
||||
|
||||
fun getFolderById(folderId: String): Flow<Folder?>
|
||||
|
||||
suspend fun createAlbum(name: String, coverUri: String? = null): Album
|
||||
|
||||
suspend fun deleteAlbum(albumId: String)
|
||||
|
||||
/** Returns the number of new images. Progress counts rows written within the transaction. */
|
||||
suspend fun addWallpapersToAlbum(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
|
||||
): Int
|
||||
|
||||
/** Returns false for an existing folder URI. Progress counts images written within the transaction. */
|
||||
suspend fun addFolderToAlbum(
|
||||
albumId: String,
|
||||
folder: Folder,
|
||||
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
|
||||
): Boolean
|
||||
|
||||
suspend fun reorderAlbum(albumId: String, folders: List<Folder>, wallpapers: List<Wallpaper>)
|
||||
|
||||
suspend fun removeWallpapersFromAlbum(albumId: String, wallpaperIds: List<String>)
|
||||
|
||||
suspend fun removeFolderFromAlbum(albumId: String, folderId: String)
|
||||
|
||||
suspend fun deleteAllAlbums()
|
||||
|
||||
/** Removes confirmed missing entries and updates covers in the same transaction. */
|
||||
suspend fun pruneMissingEntries(albumId: String): Int
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.anthonyla.paperize.domain.repository
|
||||
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.domain.model.AppSettings
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface SettingsRepository {
|
||||
suspend fun getAppSettings(): AppSettings
|
||||
|
||||
fun getAppSettingsFlow(): Flow<AppSettings>
|
||||
|
||||
suspend fun getWallpaperMode(): WallpaperMode
|
||||
|
||||
fun getWallpaperModeFlow(): Flow<WallpaperMode>
|
||||
|
||||
/** The caller must reset library and schedule data when switching modes. */
|
||||
suspend fun updateWallpaperMode(mode: WallpaperMode)
|
||||
|
||||
suspend fun getScheduleSettings(): ScheduleSettings
|
||||
|
||||
fun getScheduleSettingsFlow(): Flow<ScheduleSettings>
|
||||
|
||||
suspend fun updateScheduleSettings(settings: ScheduleSettings)
|
||||
|
||||
/** Apply an edit to the latest stored settings in one DataStore transaction. */
|
||||
suspend fun updateScheduleSettings(transform: (ScheduleSettings) -> ScheduleSettings): ScheduleSettings
|
||||
|
||||
suspend fun clearAllSettings()
|
||||
|
||||
suspend fun clearScheduleSettings()
|
||||
|
||||
/** BOTH updates the home and lock selections together. */
|
||||
suspend fun updateAlbumId(screen: ScreenType, albumId: String?)
|
||||
|
||||
/** Clears matching selections atomically; returns whether any selection changed. */
|
||||
suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean
|
||||
|
||||
suspend fun clearEmptyAlbumSelection(albumId: String, screen: ScreenType)
|
||||
|
||||
suspend fun updateDarkMode(enabled: Boolean)
|
||||
suspend fun updateDynamicTheming(enabled: Boolean)
|
||||
suspend fun updateAnimate(enabled: Boolean)
|
||||
suspend fun updateFirstLaunch(isFirstLaunch: Boolean)
|
||||
|
||||
suspend fun updateEnableChanger(enabled: Boolean)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.anthonyla.paperize.domain.repository
|
||||
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface WallpaperRepository {
|
||||
suspend fun getWallpaperById(wallpaperId: String): Wallpaper?
|
||||
|
||||
/** Atomic, so concurrent wallpaper changes never receive the same item. */
|
||||
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper?
|
||||
|
||||
suspend fun removeWallpaperFromQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
)
|
||||
|
||||
/** Restore a prepared wallpaper to the front when applying it did not succeed. */
|
||||
suspend fun restoreWallpaperToQueueFront(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
)
|
||||
|
||||
/** Fill an empty wallpaper queue; preserve a queue already filled by another caller. */
|
||||
suspend fun ensureWallpaperQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
shuffle: Boolean = false
|
||||
)
|
||||
|
||||
/** Used when the shuffle setting changes, so every queue rebuilds in the new order. */
|
||||
suspend fun clearAllQueues()
|
||||
|
||||
suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper?
|
||||
|
||||
fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<Wallpaper?>
|
||||
|
||||
suspend fun setCurrentWallpaper(albumId: String, screenType: ScreenType, wallpaperId: String)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.anthonyla.paperize.domain.source
|
||||
|
||||
data class SourceImage(val uri: String, val name: String, val modifiedAt: Long)
|
||||
data class SourceFolder(val name: String, val images: List<SourceImage>)
|
||||
|
||||
interface DocumentSource {
|
||||
suspend fun retainReadPermission(uri: String)
|
||||
suspend fun readImage(uri: String): SourceImage
|
||||
suspend fun readFolder(uri: String, onProgress: (Int) -> Unit = {}): SourceFolder
|
||||
suspend fun isMissing(uri: String, isTree: Boolean = false): Boolean
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.anthonyla.paperize.domain.source
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
interface WallpaperRenderer {
|
||||
/** Decode [wallpaper] with [screen]'s scaling and effects. Returns null if it cannot be read. */
|
||||
suspend fun render(wallpaper: Wallpaper, screen: ScreenType, settings: ScheduleSettings): Bitmap?
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.util.Log
|
||||
import com.anthonyla.paperize.core.EmptyAlbumException
|
||||
import com.anthonyla.paperize.core.NoValidWallpaperException
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.runCatchingCancellable
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.domain.source.WallpaperRenderer
|
||||
import javax.inject.Inject
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Prepares the next wallpaper without marking it as current.
|
||||
*
|
||||
* The queue item is dequeued while it is decoded, but callers must invoke [complete] only after
|
||||
* WallpaperManager confirms the bitmap was applied. If the platform rejects it, [restore] puts
|
||||
* the item back at the front of the queue.
|
||||
*/
|
||||
class ChangeWallpaperUseCase @Inject constructor(
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val renderer: WallpaperRenderer
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String, screenType: ScreenType): PreparedWallpaper {
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
repeat(Constants.MAX_WALLPAPER_LOAD_RETRIES) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
val candidate = dequeueNext(albumId, screenType, settings.shuffleEnabled)
|
||||
try {
|
||||
val bitmap = renderer.render(candidate, screenType, settings)
|
||||
if (bitmap != null) {
|
||||
return PreparedWallpaper(bitmap, albumId, screenType, candidate.id, settings.shuffleEnabled)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
// Cancelling preparation must not consume the selected queue item.
|
||||
withContext(NonCancellable) {
|
||||
try {
|
||||
wallpaperRepository.restoreWallpaperToQueueFront(albumId, screenType, candidate.id)
|
||||
} catch (restoreError: Exception) {
|
||||
Log.e(TAG, "Failed to restore cancelled wallpaper", restoreError)
|
||||
}
|
||||
}
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Unreadable images are skipped for this cycle; refresh owns permanent pruning.
|
||||
}
|
||||
}
|
||||
throw NoValidWallpaperException()
|
||||
}
|
||||
|
||||
/** Dequeue the next item, rebuilding an empty queue once. Throws [EmptyAlbumException] if none remain. */
|
||||
suspend fun dequeueNext(albumId: String, screenType: ScreenType, shuffle: Boolean): Wallpaper =
|
||||
wallpaperRepository.getAndDequeueWallpaper(albumId, screenType) ?: run {
|
||||
wallpaperRepository.ensureWallpaperQueue(albumId, screenType, shuffle)
|
||||
wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
|
||||
?: throw EmptyAlbumException()
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a successfully applied wallpaper and keep the target screen queue in sync.
|
||||
*
|
||||
* [screenType] can differ from the prepared queue when one HOME item was atomically applied to
|
||||
* both screens. The exact item is removed from LOCK rather than blindly dequeuing its head.
|
||||
*/
|
||||
suspend fun complete(
|
||||
prepared: PreparedWallpaper,
|
||||
screenType: ScreenType = prepared.screenType
|
||||
) = completeSpecific(
|
||||
albumId = prepared.albumId,
|
||||
screenType = screenType,
|
||||
wallpaperId = prepared.wallpaperId,
|
||||
shuffle = prepared.shuffle
|
||||
)
|
||||
|
||||
/** Record a user-selected wallpaper and remove that exact item from the next-change queue. */
|
||||
suspend fun completeSpecific(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String,
|
||||
shuffle: Boolean
|
||||
) {
|
||||
runCatchingCancellable { wallpaperRepository.setCurrentWallpaper(albumId, screenType, wallpaperId) }
|
||||
.onFailure {
|
||||
Log.e(TAG, "Applied wallpaper could not be recorded as current", it)
|
||||
return
|
||||
}
|
||||
|
||||
runCatchingCancellable {
|
||||
wallpaperRepository.ensureWallpaperQueue(albumId, screenType, shuffle)
|
||||
// Build first when this is the first synchronized use of a screen queue, then remove
|
||||
// the exact applied item. This prevents the just-applied wallpaper from being
|
||||
// reintroduced at the head of a freshly built queue.
|
||||
wallpaperRepository.removeWallpaperFromQueue(albumId, screenType, wallpaperId)
|
||||
}.onFailure { Log.w(TAG, "Queue sync failed; it will rebuild on the next change", it) }
|
||||
}
|
||||
|
||||
/** Restore a prepared item after WallpaperManager rejected it. */
|
||||
suspend fun restore(prepared: PreparedWallpaper) {
|
||||
runCatchingCancellable {
|
||||
wallpaperRepository.restoreWallpaperToQueueFront(prepared.albumId, prepared.screenType, prepared.wallpaperId)
|
||||
}.onFailure { Log.e(TAG, "Failed to restore rejected wallpaper to its queue", it) }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ChangeWallpaperUseCase"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
class CreateAlbumUseCase @Inject constructor(
|
||||
private val albumRepository: AlbumRepository
|
||||
) {
|
||||
suspend operator fun invoke(name: String, coverUri: String? = null): Album {
|
||||
require(name.isNotBlank()) { "Album name cannot be empty" }
|
||||
require(albumRepository.getAlbumByName(name) == null) { "Album with this name already exists" }
|
||||
return albumRepository.createAlbum(name, coverUri)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
class DeleteAlbumUseCase @Inject constructor(
|
||||
private val albumRepository: AlbumRepository,
|
||||
private val settingsRepository: SettingsRepository
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String) {
|
||||
albumRepository.deleteAlbum(albumId)
|
||||
settingsRepository.clearAlbumSelectionsIfMatches(albumId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.core.util.generateId
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import com.anthonyla.paperize.domain.source.SourceImage
|
||||
import kotlinx.coroutines.flow.first
|
||||
import javax.inject.Inject
|
||||
|
||||
class ImportWallpapersUseCase @Inject constructor(
|
||||
private val documents: DocumentSource,
|
||||
private val albumRepository: AlbumRepository
|
||||
) {
|
||||
suspend fun addImages(albumId: String, uris: List<String>, onSaving: (Int, Int) -> Unit): Boolean {
|
||||
val images = uris.distinct().map { uri ->
|
||||
documents.retainReadPermission(uri)
|
||||
documents.readImage(uri).toWallpaper(albumId)
|
||||
}
|
||||
return albumRepository.addWallpapersToAlbum(albumId, images, onSaving) > 0
|
||||
}
|
||||
|
||||
suspend fun addFolder(
|
||||
albumId: String,
|
||||
uri: String,
|
||||
onScanning: (Int) -> Unit,
|
||||
onSaving: (Int, Int) -> Unit
|
||||
): Boolean {
|
||||
documents.retainReadPermission(uri)
|
||||
// Avoid rescanning an existing folder; insertion still checks duplicates atomically.
|
||||
if (albumRepository.getAlbumById(albumId).first()?.folders.orEmpty().any { it.uri == uri }) return false
|
||||
val source = documents.readFolder(uri, onScanning)
|
||||
val folderId = generateId()
|
||||
val folder = Folder(
|
||||
id = folderId, albumId = albumId, uri = uri, name = source.name,
|
||||
coverUri = null, dateModified = System.currentTimeMillis(),
|
||||
wallpapers = source.images.sortedBy { it.uri }.map { it.toWallpaper(albumId, folderId) }
|
||||
)
|
||||
return albumRepository.addFolderToAlbum(albumId, folder, onSaving)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun SourceImage.toWallpaper(albumId: String, folderId: String? = null) = Wallpaper(
|
||||
id = generateId(), albumId = albumId, folderId = folderId, uri = uri,
|
||||
fileName = name, dateModified = modifiedAt
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.NoValidWallpaperException
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.domain.source.WallpaperRenderer
|
||||
import javax.inject.Inject
|
||||
|
||||
class ReapplyEffectsUseCase @Inject constructor(
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val renderer: WallpaperRenderer
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String, screenType: ScreenType, wallpaperId: String? = null): Bitmap {
|
||||
val wallpaper = if (wallpaperId != null) wallpaperRepository.getWallpaperById(wallpaperId)
|
||||
else wallpaperRepository.getCurrentWallpaper(albumId, screenType)
|
||||
return wallpaper?.let { renderer.render(it, screenType, settingsRepository.getScheduleSettings()) }
|
||||
?: throw NoValidWallpaperException()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import kotlinx.coroutines.flow.first
|
||||
import javax.inject.Inject
|
||||
|
||||
class RefreshFolderUseCase @Inject constructor(
|
||||
private val albumRepository: AlbumRepository,
|
||||
private val documents: DocumentSource
|
||||
) {
|
||||
/** Returns the number of new images. */
|
||||
suspend operator fun invoke(folderId: String): Int {
|
||||
val folder = albumRepository.getFolderById(folderId).first() ?: return 0
|
||||
val source = documents.readFolder(folder.uri)
|
||||
return albumRepository.addWallpapersToAlbum(
|
||||
folder.albumId, source.images.map { it.toWallpaper(folder.albumId, folderId) }
|
||||
)
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.app_shortcut
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver
|
||||
|
||||
class BroadcastActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val intent = Intent("WallpaperBootAndChangeReceiver.intent.action.BROADCAST").setClass(this, WallpaperBootAndChangeReceiver::class.java)
|
||||
sendBroadcast(intent)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data access object for AlbumWithWallpaperAndFolder which is used for application's list of user albums
|
||||
*/
|
||||
@Dao
|
||||
interface AlbumDao {
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM album")
|
||||
fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAlbum(album: Album)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertFolder(folder: Folder)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertFolderList(folders: List<Folder>)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteAlbum(album: Album)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteFolder(folder: Folder)
|
||||
@Delete
|
||||
suspend fun deleteWallpaperList(wallpapers: List<Wallpaper>)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteFolderList(folders: List<Folder>)
|
||||
|
||||
@Query("DELETE FROM wallpaper WHERE initialAlbumName=:initialAlbumName")
|
||||
suspend fun cascadeDeleteWallpaper(initialAlbumName: String)
|
||||
|
||||
@Query("DELETE FROM folder WHERE initialAlbumName=:initialAlbumName")
|
||||
suspend fun cascadeDeleteFolder(initialAlbumName: String)
|
||||
|
||||
@Update
|
||||
suspend fun updateAlbum(album: Album)
|
||||
|
||||
@Update
|
||||
suspend fun updateWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Update
|
||||
suspend fun updateFolder(folder: Folder)
|
||||
|
||||
@Query("DELETE FROM album")
|
||||
suspend fun deleteAllAlbums()
|
||||
|
||||
@Query("DELETE FROM wallpaper")
|
||||
suspend fun deleteAllWallpapers()
|
||||
|
||||
@Query("DELETE FROM folder")
|
||||
suspend fun deleteAllFolders()
|
||||
|
||||
@Transaction
|
||||
suspend fun deleteAllData() {
|
||||
deleteAllWallpapers()
|
||||
deleteAllFolders()
|
||||
deleteAllAlbums()
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
|
||||
/**
|
||||
* Database for storing albums, wallpapers, and folders
|
||||
* Stores [Album], [Wallpaper], and [Folder] inside AlbumWithWallpaperAndFolder
|
||||
*/
|
||||
@Database(
|
||||
entities = [Album::class, Wallpaper::class, Folder::class],
|
||||
version = 5
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class AlbumDatabase: RoomDatabase() {
|
||||
abstract val albumDao: AlbumDao
|
||||
companion object {
|
||||
const val DATABASE_NAME = "paperize_album_db"
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
import com.google.gson.Gson
|
||||
|
||||
/**
|
||||
* Converters for Room database to convert list of strings to json string and vice versa
|
||||
*/
|
||||
class Converters {
|
||||
private val gson = Gson()
|
||||
|
||||
/**
|
||||
* Convert list of strings to json string
|
||||
*/
|
||||
@TypeConverter
|
||||
fun listToJsonString(value: List<String>?): String = gson.toJson(value)
|
||||
|
||||
/**
|
||||
* Convert json string to list of strings
|
||||
*/
|
||||
@TypeConverter
|
||||
fun jsonStringToList(value: String) = gson.fromJson(value, Array<String>::class.java).toList()
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for selected album for application to keep track of which album is currently selected for changing wallpapers from
|
||||
*/
|
||||
@Dao
|
||||
interface SelectedAlbumDao {
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM album")
|
||||
fun getSelectedAlbum(): Flow<List<SelectedAlbum>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAlbum(album: Album)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>)
|
||||
|
||||
@Query("DELETE FROM album WHERE initialAlbumName = :initialAlbumName")
|
||||
suspend fun deleteAlbum(initialAlbumName: String)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Query("DELETE FROM wallpaper WHERE initialAlbumName = :initialAlbumName")
|
||||
suspend fun cascadeDeleteWallpaper(initialAlbumName: String)
|
||||
|
||||
@Query("DELETE FROM album")
|
||||
suspend fun deleteAllAlbums()
|
||||
|
||||
@Query("DELETE FROM wallpaper")
|
||||
suspend fun deleteAllWallpapers()
|
||||
|
||||
@Transaction
|
||||
suspend fun deleteAll() {
|
||||
deleteAllAlbums()
|
||||
deleteAllWallpapers()
|
||||
}
|
||||
|
||||
@Transaction
|
||||
suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum) {
|
||||
upsertAlbum(selectedAlbum.album)
|
||||
upsertWallpaperList(selectedAlbum.wallpapers)
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
|
||||
/**
|
||||
* Database for selected album
|
||||
* Stores [Album] and [Wallpaper] inside SelectedAlbum
|
||||
*/
|
||||
@Database(
|
||||
entities = [Album::class, Wallpaper::class],
|
||||
version = 5
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class SelectedAlbumDatabase: RoomDatabase() {
|
||||
abstract val selectedAlbumDao: SelectedAlbumDao
|
||||
companion object {
|
||||
const val DATABASE_NAME = "paperize_selectedAlbum_db"
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.repository
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.data_source.AlbumDao
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
class AlbumRepositoryImpl(
|
||||
private val dao: AlbumDao
|
||||
): AlbumRepository {
|
||||
override fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>> {
|
||||
return dao.getAlbumsWithWallpaperAndFolder()
|
||||
}
|
||||
|
||||
override suspend fun upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder) {
|
||||
dao.upsertAlbum(albumWithWallpaperAndFolder.album)
|
||||
dao.upsertWallpaperList(albumWithWallpaperAndFolder.wallpapers)
|
||||
dao.upsertFolderList(albumWithWallpaperAndFolder.folders)
|
||||
}
|
||||
|
||||
override suspend fun upsertAlbum(album: Album) {
|
||||
dao.upsertAlbum(album)
|
||||
}
|
||||
|
||||
override suspend fun upsertWallpaper(wallpaper: Wallpaper) {
|
||||
dao.upsertWallpaper(wallpaper)
|
||||
}
|
||||
|
||||
override suspend fun upsertFolder(folder: Folder) {
|
||||
dao.upsertFolder(folder)
|
||||
}
|
||||
|
||||
override suspend fun upsertFolderList(folders: List<Folder>) {
|
||||
dao.upsertFolderList(folders)
|
||||
}
|
||||
|
||||
override suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>) {
|
||||
dao.upsertWallpaperList(wallpapers)
|
||||
}
|
||||
|
||||
override suspend fun deleteAlbum(album: Album) {
|
||||
dao.deleteAlbum(album)
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpaper(wallpaper: Wallpaper) {
|
||||
dao.deleteWallpaper(wallpaper)
|
||||
}
|
||||
|
||||
override suspend fun deleteFolder(folder: Folder) {
|
||||
dao.deleteFolder(folder)
|
||||
}
|
||||
|
||||
override suspend fun updateAlbum(album: Album) {
|
||||
dao.updateAlbum(album)
|
||||
}
|
||||
|
||||
override suspend fun updateFolder(folder: Folder) {
|
||||
dao.updateFolder(folder)
|
||||
}
|
||||
|
||||
override suspend fun updateWallpaper(wallpaper: Wallpaper) {
|
||||
dao.updateWallpaper(wallpaper)
|
||||
}
|
||||
|
||||
override suspend fun cascadeDeleteAlbum(album: Album) {
|
||||
dao.deleteAlbum(album)
|
||||
dao.cascadeDeleteWallpaper(album.initialAlbumName)
|
||||
dao.cascadeDeleteFolder(album.initialAlbumName)
|
||||
}
|
||||
|
||||
override suspend fun cascadeDeleteFolder(initialAlbumName: String) {
|
||||
dao.cascadeDeleteFolder(initialAlbumName)
|
||||
}
|
||||
|
||||
override suspend fun cascadeDeleteWallpaper(initialAlbumName: String) {
|
||||
dao.cascadeDeleteWallpaper(initialAlbumName)
|
||||
}
|
||||
|
||||
override suspend fun deleteFolderList(folders: List<Folder>) {
|
||||
dao.deleteFolderList(folders)
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpaperList(wallpapers: List<Wallpaper>) {
|
||||
dao.deleteWallpaperList(wallpapers)
|
||||
}
|
||||
|
||||
override suspend fun deleteAllData() {
|
||||
dao.deleteAllData()
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.repository
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.data_source.SelectedAlbumDao
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
class SelectedAlbumRepositoryImpl(
|
||||
private val dao: SelectedAlbumDao
|
||||
): SelectedAlbumRepository {
|
||||
override fun getSelectedAlbum(): Flow<List<SelectedAlbum>> {
|
||||
return dao.getSelectedAlbum()
|
||||
}
|
||||
|
||||
override suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum) {
|
||||
dao.upsertSelectedAlbum(selectedAlbum)
|
||||
}
|
||||
|
||||
override suspend fun deleteAlbum(initialAlbumName: String) {
|
||||
dao.deleteAlbum(initialAlbumName)
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpaper(wallpaper: Wallpaper) {
|
||||
dao.deleteWallpaper(wallpaper)
|
||||
}
|
||||
|
||||
override suspend fun cascadeDeleteAlbum(initialAlbumName: String) {
|
||||
dao.deleteAlbum(initialAlbumName)
|
||||
dao.cascadeDeleteWallpaper(initialAlbumName)
|
||||
}
|
||||
|
||||
override suspend fun deleteAll() {
|
||||
dao.deleteAll()
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Album model
|
||||
*
|
||||
* @param initialAlbumName The initial album name -- should not be changed as it is used as the key for database queries
|
||||
* @param displayedAlbumName The displayed album name
|
||||
* @param coverUri The cover uri of the album
|
||||
* @param initialized Whether the album has been initialized
|
||||
* @param homeWallpapersInQueue The list of home wallpapers in the queue
|
||||
* @param lockWallpapersInQueue The list of lock wallpapers in the queue
|
||||
*/
|
||||
@Entity
|
||||
data class Album(
|
||||
@PrimaryKey(autoGenerate = false) val initialAlbumName: String,
|
||||
val displayedAlbumName: String,
|
||||
val coverUri: String?,
|
||||
val initialized: Boolean = false,
|
||||
val homeWallpapersInQueue: List<String> = emptyList(),
|
||||
val lockWallpapersInQueue: List<String> = emptyList(),
|
||||
)
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
|
||||
/**
|
||||
* Complete data class that represents an album with its wallpapers and folders.
|
||||
* @param album The album.
|
||||
* @param wallpapers The wallpapers.
|
||||
* @param folders The folders.
|
||||
*/
|
||||
data class AlbumWithWallpaperAndFolder(
|
||||
@Embedded val album: Album,
|
||||
@Relation(
|
||||
parentColumn = "initialAlbumName",
|
||||
entityColumn = "initialAlbumName",
|
||||
)
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
@Relation(
|
||||
parentColumn = "initialAlbumName",
|
||||
entityColumn = "initialAlbumName",
|
||||
)
|
||||
val folders: List<Folder> = emptyList(),
|
||||
)
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Represents a folder directory containing wallpapers.
|
||||
*
|
||||
* @param initialAlbumName The initial album name.
|
||||
* @param folderName The folder name.
|
||||
* @param coverUri The cover URI.
|
||||
* @param wallpapers The list of wallpaper URI strings in the folder.
|
||||
* @param folderUri The folder directory URI.
|
||||
*/
|
||||
@Entity
|
||||
data class Folder(
|
||||
val initialAlbumName: String,
|
||||
val folderName: String?,
|
||||
val coverUri: String?,
|
||||
val wallpapers: List<String> = emptyList(),
|
||||
val folderUri: String,
|
||||
@PrimaryKey(autoGenerate = false) val key: Int
|
||||
)
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
|
||||
/**
|
||||
* Data class that represents a selected album with its wallpapers.
|
||||
* @param album the selected album.
|
||||
* @param wallpapers the wallpapers of the selected album. Includes the wallpapers from each folders in album.
|
||||
*/
|
||||
data class SelectedAlbum(
|
||||
@Embedded val album: Album,
|
||||
@Relation(
|
||||
parentColumn = "initialAlbumName",
|
||||
entityColumn = "initialAlbumName",
|
||||
)
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
)
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Represents a wallpaper object.
|
||||
*
|
||||
* @param initialAlbumName The name of the album the wallpaper belongs to.
|
||||
* @param wallpaperUri The URI of the wallpaper.
|
||||
*/
|
||||
@Entity
|
||||
data class Wallpaper(
|
||||
val initialAlbumName: String,
|
||||
val wallpaperUri: String,
|
||||
@PrimaryKey(autoGenerate = false) val key: Int
|
||||
)
|
||||
Loaded 100 of 374 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user