Compare commits

..
101 Commits
Author SHA1 Message Date
lucas 7cc0454102 Merge pull request 'Dev lfa' (#4) from dev-LFA into main-LFA
Paperize Android Release CI / Run unit tests and lint (push) Successful in 4m58s
Paperize Android Release CI / Build release APK (push) Successful in 4m54s
Reviewed-on: #4
2026-11-25 18:45:38 +01:00
Lucas Vivo 6bb05ea13b docs(albums): document the album filter changes
Paperize Android Debug CI / Run unit tests and lint (push) Successful in 5m23s
Paperize Android Debug CI / Build debug APK (push) Successful in 4m12s
2026-11-25 18:28:55 +01:00
Lucas Vivo e30b51e5e4 feat(database): add a new database v7 to handle teh naming table 2026-11-25 18:28:35 +01:00
Lucas Vivo 3fc9facf32 feat(albums): add a filter term to album menu to filter the wallpapers in one album 2026-11-25 18:28:09 +01:00
Lucas VivoandCopilot dbd80fe3fa fix(album): finalize database v6 schema and secure passphrase field
Paperize Android Debug CI / Run unit tests and lint (push) Successful in 4m45s
Paperize Android Debug CI / Build debug APK (push) Successful in 4m9s
Paperize Android Release CI / Run unit tests and lint (push) Successful in 4m35s
Paperize Android Release CI / Build release APK (push) Successful in 4m52s
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 16:03:09 +01:00
Lucas Vivo d1ad40b213 docs(albums): rescan albums automatically 2026-11-23 15:50:11 +01:00
Lucas Vivo 2adcf1a318 feat(albums): rescan albums automatically every hour 2026-11-23 15:50:11 +01:00
Lucas Vivo 80c70f82ee chore(gitignore): add jks files 2026-11-23 15:50:11 +01:00
Lucas Vivo faf40edf30 docs(readme): explain new features in readme 2026-11-23 15:50:11 +01:00
Lucas Vivo 29be20ca10 build(build_script): rewrite build script to test on quiethost 2026-11-23 15:50:11 +01:00
Lucas Vivo 8d3701bc6a feat(albums): add menu button to album to rescan folders, rename album and delete album 2026-11-23 15:50:11 +01:00
Lucas Vivo 76cb388199 ci(gitea): split the workflow in dev and main
only compile release apk on main branch
2026-11-23 15:50:11 +01:00
Lucas VivoandCopilot e4b0eab824 docs: explain encrypted album setup and limitations
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 15:50:11 +01:00
Lucas VivoandCopilot c9bdce1484 feat(albums): support encrypted wallpaper albums
Import encrypted images, render them for static and live wallpapers, and provide opt-in uncached previews.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 15:50:11 +01:00
Lucas VivoandCopilot db01ecab9c feat(encryption): store passphrase and decrypt images
Protect the passphrase with Android Keystore and support the wallpaper_changer encrypted image format.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 15:47:41 +01:00
Lucas Vivo 229c54258c ci(github): disable workflows 2026-11-23 15:47:41 +01:00
Lucas Vivo 2d6b905c07 ci(gitea): fix patform-tools
use correct package platform-tools
2026-11-23 15:47:41 +01:00
Lucas Vivo 48562bf01c build(build_script): add build and install script
asd
2026-11-23 15:47:41 +01:00
Lucas Vivo d51e0920d0 ci(gitea): port github test, lint and build to gitea 2026-11-23 15:47:41 +01:00
Anthonyy232 d2fb14dcd0 build: check out text files with LF line endings 2026-11-23 00:16:14 -08:00
Anthonyy232 82e5fbd5e9 build: stop lint failing when a dependency update comes out 2026-11-22 23:47:12 -08:00
Anthonyy232 da506a4df7 docs: cut low-level detail from AGENTS.md 2026-11-22 23:41:02 -08:00
Anthonyy232 6b682980b9 build: fail on warnings and add the compose lint rules
Lint and Kotlin warnings passed CI unless someone read the report. The
Slack Compose rules run inside Android Lint, so they need no new tool.
2026-11-22 23:37:17 -08:00
Anthonyy232 15769d2fe2 docs: recapture the screenshots with the remove buttons 2026-11-22 23:07:53 -08:00
github-actions[bot] dd46dfc9d4 chore: update translations 2026-11-23 02:56:42 +00:00
Anthonyy232 06738a4485 fix: match the live blur strength to static mode
The live shader blurred about three times as much as static mode at the
same setting, with samples so far apart that hard edges showed steps. Live
wallpapers using blur now look about a third as blurred at the same slider
value.
2026-11-22 18:52:34 -08:00
Anthonyy232 d0cad6f45c feat: blur the borders around Fit wallpapers
Fit left black bars around images that do not match the screen. A new
option fills them with a blurred copy of the image, in static and live
mode. In live mode the user's blur now runs on the combined picture, so
it also softens the picture's edges as it already did in static mode.

Fixes #608
2026-11-22 18:49:03 -08:00
Anthonyy232 49ba1aafaf merge: polish text wrapping, folder cards, add buttons and dialogs 2026-11-22 16:48:51 -08:00
Anthonyy232 1a2c6eecd1 fix: line up the album rows when no album is chosen 2026-11-22 16:42:00 -08:00
Anthonyy232 8634a59ee8 fix: draw the import progress as a standard dialog 2026-11-22 16:41:25 -08:00
Anthonyy232 bc6bc2c405 fix: match the library add button to the album one 2026-11-22 16:40:45 -08:00
Anthonyy232 707df3a25d feat: show each folder's cover on its card 2026-11-22 16:39:51 -08:00
Anthonyy232 e9cd2c388f fix: let settings and dialog text wrap instead of cutting it off
Line limits cut descriptions short at large font sizes and in longer
languages, with no way to read the rest.
2026-11-22 16:38:59 -08:00
Anthonyy232 50f6677c95 build: update dependencies
Compose BOM 2026.11.01 brings stable Material 3 1.5.0, so the prerelease
pin goes, and its Compose 1.13 needs compileSdk 37.1 or later.
2026-11-22 16:17:52 -08:00
github-actions[bot] 740175fb10 chore: update translations 2026-11-23 00:00:30 +00:00
Anthonyy232 d94e1be668 feat: remove the current wallpaper from its album
A removed folder image is remembered so rescans do not add it back, and
can be put back from the folder.

Fixes #604
2026-11-22 15:52:06 -08:00
maou-shonen 6270d1c2be fix(i18n): refine zh-Hant rotation description 2026-11-21 23:16:14 +08:00
YaqiongWu 073df232f2 fix(import): skip files trashed under their old display name
HyperOS renames a deleted file to .trashed-… but keeps reporting its old display name, so only the document id shows it.
2026-11-18 08:27:33 -08:00
Anthonyy232 16f5a1682b docs: say that a rescan drops deleted folder images 2026-11-17 18:22:36 -08:00
YaqiongWu e7c6c5b850 fix(import): drop deleted and trashed images on folder refresh
Some galleries delete a photo by renaming it to .trashed-… in place. A rescan imported those as new wallpapers and kept the deleted originals.
2026-11-17 18:18:24 -08:00
Pbg4444 548bc9b32a fix: skip screen-off change if the screen comes back on 2026-11-17 11:41:30 -08:00
Anthonyy232 cb6e7b83be fix: retry the live wallpaper until its images can be read
Waiting for the provider to announce a change did not recover on a Galaxy Tab: nothing was announced, so the home screen stayed black. Retry on a timer instead, and test readability by opening the file.

Refs #646
2026-11-17 08:55:17 -08:00
Anthonyy232 b506ac179f chore: release v4.3.1 2026-11-17 00:41:38 -08:00
Anthonyy232 8eb3d501cd fix: load the live wallpaper once its storage becomes readable
After a reboot the engine can start before the storage volume is
mounted. Every candidate then failed validation, the home screen
stayed black until the next change and the unreadable items were
dropped from the queue, in static mode too.

Refs #646
2026-11-17 00:24:44 -08:00
Anthonyy232 47aa0a6f25 docs: give the language count as a floor
The Crowdin sync adds a language once it is 90% reviewed, which left an exact count stale.
2026-11-16 20:39:06 -08:00
Anthonyy232 0f988dd1a7 refactor: drop unused defaults for the continue-rotation flag 2026-11-16 20:04:08 -08:00
Anthonyy232 39dc628de6 chore: release v4.3.0 2026-11-15 22:06:20 -08:00
Anthonyy232 12c3d67fc2 fix: change on screen off only once the wallpaper is hidden
Some skins keep drawing the wallpaper through their screen-off animation, so the swap was visible. Fixes #644
2026-11-15 22:06:20 -08:00
Anthonyy232 2be0653c37 build: skip the missing plural form lint rule for crowdin exports 2026-11-15 22:06:20 -08:00
Anthonyy232 20f3254016 build: target android 17 (sdk 37) 2026-11-15 19:13:24 -08:00
Anthonyy232 78df576bf8 docs: say how many languages ship 2026-11-15 13:38:25 -08:00
github-actions[bot] 96181409e9 chore: update translations 2026-11-15 13:38:19 -08:00
Anthonyy232 36141d0ac7 fix(i18n): stop offering the app name for translation 2026-11-15 13:38:19 -08:00
Anthonyy232 c198f26a86 ci: auto-merge only the minor-patch group and drop the renovate stub 2026-11-15 13:38:19 -08:00
Anthonyy232 ac6a04b0f4 ci: keep toolchain updates out of the auto-merged group 2026-11-15 13:38:19 -08:00
Anthonyy232 51a67a709d build: move dependency updates from renovate to dependabot
Monthly, grouped, minor and patch merge themselves once the required checks pass. Toolchain updates stay manual because F-Droid compares its rebuild with the release APK. renovate.json stays only to keep the installed app from re-onboarding.
2026-11-15 10:10:41 -08:00
Anthonyy232 007740d626 docs: recapture the screenshots with a fixed status bar 2026-11-15 10:02:17 -08:00
Anthonyy232 98ada25d02 docs: add a security policy 2026-11-15 10:02:17 -08:00
Anthonyy232 4a7f22bbc6 docs: send translators to crowdin 2026-11-15 10:02:17 -08:00
Anthonyy232 99c79daa0c ci: sync translations with crowdin
Only approved translations come back, shipped strings are never dropped, and a new locale waits until it is 90% approved. CI can be dispatched because the pull request it opens with GITHUB_TOKEN starts no workflows.
2026-11-15 10:02:09 -08:00
Anthonyy232 2b9cb6def2 build: baseline the two deliberate lint warnings
Battery optimisation exemption is needed for reliable scheduling outside Play. targetSdk 37 waits for an Android 17 test pass.
2026-11-15 10:02:09 -08:00
Anthonyy232 9fdd5bb3fd refactor: use platform and library apis over hand-rolled code 2026-11-15 10:01:57 -08:00
Anthonyy232 7140c970e1 fix(i18n): put counts inside the plural and format strings
Translators can now place the number and pick the plural form instead of the code gluing words together.
2026-11-15 10:01:57 -08:00
Anthonyy232 f4d6e995b3 refactor(ui): size the wallpaper preview from the window info
Configuration.screenWidthDp is deprecated in Compose; the window container size also includes the system bars the wallpaper sits behind.
2026-11-15 10:01:57 -08:00
Anthonyy232 a5788dac33 docs: rebuild the readme, site and store images from the media branch
The images are now generated from committed emulator captures and demo wallpapers on media, so they can be rebuilt. The fresh captures show a different clock time.
2026-11-15 10:01:57 -08:00
Anthonyy232 3cc8a4230d docs: put the store screenshots on a flat background 2026-11-15 02:30:44 -08:00
Anthonyy232 2a6db2fad7 docs(site): add the copyright line to the footer 2026-11-15 02:30:44 -08:00
Anthonyy232 f8b96084c6 test: check the continued rotation against the real database 2026-11-15 02:30:44 -08:00
Anthonyy232 1b8505d7e4 fix: make continue rotation opt-in and wait for settings to show it
Applying a single wallpaper keeps its 4.2.2 behaviour unless the box is ticked.
2026-11-15 02:30:44 -08:00
Anthonyy232 5902af44c7 docs: match agents.md to the standard and correct the f-droid flow 2026-11-15 02:30:44 -08:00
Anthonyy232 b9c2ab868f docs: note that the release job reuses a prepared draft 2026-11-15 02:30:44 -08:00
Anthonyy232 a34726a506 docs: list traditional chinese and the continue rotation option 2026-11-15 02:30:44 -08:00
Anthonyy232 9a13e3ba09 refactor: trim the rotation helper comment and its duplicate tests 2026-11-15 02:30:44 -08:00
Anthonyy232 de4442cfe5 fix(i18n): drop removed strings and translate the rotation option 2026-11-15 02:30:44 -08:00
Akiro e58830610a feat: continue the rotation from a picked wallpaper (#648)
In ordered mode, setting a single wallpaper only took that item out of the queue, so the next change carried on from the old position. The Set wallpaper dialog now has a "Continue rotation from here" checkbox, on by default and hidden while shuffling, that rebuilds the queue with the wallpapers after the picked one.
2026-11-15 02:30:44 -08:00
魔王少年(maou shonen) a4386df20c feat(i18n): add Traditional Chinese (#629)
Traditional Chinese devices do not match the Simplified Chinese resources and fell back to English.
2026-11-15 02:30:44 -08:00
Anthonyy232 c36ca574d5 ci: keep hand-written notes when the release job reuses a draft
The release action appends generated notes to an existing draft for the tag. Notes are written by hand, so stop generating them.
2026-11-15 02:30:44 -08:00
Anthonyy232 bd679b9d79 ci: update the pinned action digests 2026-11-15 02:30:43 -08:00
Anthonyy232 83e69d2503 build: update gradle to 9.9.1, ksp and kotlinx serialization 2026-11-15 02:30:43 -08:00
Anthonyy232 c20f266ecf docs: recrop store screenshots 2 and 3 to start on a whole row 2026-11-15 02:30:43 -08:00
Anthonyy232 a30504d633 docs: redraw the store feature graphic flat at 1024x500 2026-11-15 02:30:43 -08:00
Anthonyy232 91823ba76b test: track the room schema the migration test reads 2026-11-15 02:30:43 -08:00
Anthonyy232 393cf3f56b chore: stop the renovate cooldown from holding action digests
Digest updates have no release date, so stability-days never passed. Renovate now merges by itself once its own checks pass, as repo auto-merge is off.
2026-11-15 02:30:43 -08:00
Anthonyy232 d42d01ea8c build: drop the unused compose preview dependency 2026-11-15 02:30:43 -08:00
Anthonyy232 bddab1e116 ci: let a started pages deploy finish 2026-11-15 02:30:43 -08:00
Anthonyy232 b76a941e87 docs: rewrite the store listing from what the app does 2026-11-15 02:30:43 -08:00
Anthonyy232 65bc22f1eb fix(site): say which languages ship and drop an untrue policy sentence 2026-11-15 02:30:43 -08:00
Anthonyy232 6703329696 docs: rewrite the readme text for users and drop the dead crowdin link 2026-11-15 02:30:43 -08:00
Anthonyy232 d1de5f1194 docs: trim agents.md to project context and durable rules 2026-11-15 02:30:43 -08:00
Anthonyy232 2888fd3d7f docs: drop the changelog file, release notes are the record 2026-11-15 02:30:43 -08:00
Anthonyy232 7cabc6ff75 feat(site): add the product site and bring the privacy policy back 2026-11-15 02:30:43 -08:00
Anthonyy232 641596f58d ci: cancel superseded runs, run the documented check and use issue forms 2026-11-15 02:30:43 -08:00
Anthonyy232 d75a8af634 docs: add agents.md and keep the readme for users 2026-11-15 02:30:43 -08:00
Anthonyy232 20757e2d1d chore: drop the outdated store video link and the duplicate store icon 2026-11-15 02:30:43 -08:00
Anthonyy232 e521f26903 docs: refresh the store screenshots, banner and format list 2026-11-15 02:30:43 -08:00
Anthonyy232 185994b962 docs: turn the readme into a product page with new screenshots 2026-11-15 02:30:43 -08:00
Anthonyy232 374a078007 feat: group settings into joined rows and put current wallpapers first 2026-11-15 02:30:43 -08:00
Anthonyy232 7fb2843b48 feat: draw the colour palette from the new icon 2026-11-15 02:30:43 -08:00
Anthonyy232 8bae038508 feat: add a launcher icon of three fanned wallpaper sheets 2026-11-15 02:30:43 -08:00
Anthonyy232 cef26f42f8 docs: correct the v4.2.2 permission note
WorkManager still contributes RECEIVE_BOOT_COMPLETED to the merged manifest.
2026-11-14 21:07:56 -08:00
renovate[bot] 063e5dcc28 chore(deps): update dependency com.google.devtools.ksp to v2.3.13 (#649)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-13 23:57:35 +00:00
208 changed files with 13968 additions and 1869 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
* text=auto eol=lf
*.bat text eol=crlf
*.jar binary
+69
View File
@@ -0,0 +1,69 @@
name: Paperize Android Debug CI
on:
push:
branches: ["dev-LFA"]
pull_request:
branches: ["dev-LFA"]
workflow_dispatch:
permissions:
contents: read
jobs:
test-and-lint:
name: Run unit tests and lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Run unit tests and lint
run: ./gradlew testDebugUnitTest lintDebug
build:
name: Build debug APK
if: github.event_name == 'push'
needs: test-and-lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Build debug APK
run: ./gradlew assembleDebug
- name: Upload debug APK
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
with:
name: paperize-debug-apk
path: app/build/outputs/apk/debug/app-debug.apk
if-no-files-found: error
+80
View File
@@ -0,0 +1,80 @@
name: Paperize Android Release CI
on:
push:
branches: ["main-LFA"]
permissions:
contents: read
jobs:
test-and-lint:
name: Run unit tests and lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Run unit tests and lint
run: ./gradlew testDebugUnitTest lintDebug
build:
name: Build release APK
needs: test-and-lint
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: temurin
- name: Set up Android SDK
uses: android-actions/setup-android@v3
with:
packages: platform-tools
- name: Install Android SDK 37
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
- name: Build signed release APK
env:
SIGNING_KEYSTORE_BASE64: ${{ secrets.SIGNING_KEYSTORE_BASE64 }}
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
shell: bash
run: |
set -euo pipefail
: "${SIGNING_KEYSTORE_BASE64:?Missing SIGNING_KEYSTORE_BASE64 secret}"
: "${SIGNING_KEY_ALIAS:?Missing SIGNING_KEY_ALIAS secret}"
: "${SIGNING_STORE_PASSWORD:?Missing SIGNING_STORE_PASSWORD secret}"
: "${SIGNING_KEY_PASSWORD:?Missing SIGNING_KEY_PASSWORD secret}"
export SIGNING_KEYSTORE_PATH="$(mktemp "${RUNNER_TEMP}/paperize-keystore.XXXXXX")"
trap 'rm -f "$SIGNING_KEYSTORE_PATH"' EXIT
printf '%s' "$SIGNING_KEYSTORE_BASE64" | base64 --decode > "$SIGNING_KEYSTORE_PATH"
./gradlew assembleRelease
- name: Upload release APK
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
with:
name: paperize-release-apk
path: app/build/outputs/apk/release/app-release.apk
if-no-files-found: error
-32
View File
@@ -1,32 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: "[Bug] <BUG_NAME>"
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Smartphone (please complete the following information):**
- Device: [e.g. Pixel 32 Pro]
- OS: [e.g. OneUI 21]
- Version [e.g. v2.1.0]
**Additional context**
Add any other context about the problem here.
+35
View File
@@ -0,0 +1,35 @@
name: Bug report
description: Something in Paperize doesn't work as it should
labels: [bug]
body:
- type: textarea
id: what
attributes:
label: What happened
description: What you did, what you expected and what you got. Screenshots help.
validations:
required: true
- type: input
id: version
attributes:
label: Paperize version
placeholder: 4.2.2 from F-Droid
validations:
required: true
- type: input
id: device
attributes:
label: Device and Android version
placeholder: Pixel 9, Android 16
validations:
required: true
- type: dropdown
id: mode
attributes:
label: Wallpaper mode
options:
- Static
- Live
- Not sure
validations:
required: true
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: Feature idea
url: https://github.com/Anthonyy232/Paperize/discussions/categories/ideas
about: Suggest a feature or improvement in Discussions
- name: Question
url: https://github.com/Anthonyy232/Paperize/discussions/categories/q-a
about: Ask how something works
-20
View File
@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[Feature request] <FEATURE_NAME>"
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+39
View File
@@ -0,0 +1,39 @@
version: 2
updates:
- package-ecosystem: gradle
directory: /
schedule:
interval: monthly
cooldown:
default-days: 5
groups:
# F-Droid rebuilds each release and compares it with ours: toolchain updates are merged by hand
toolchain:
patterns:
- gradle-wrapper
- com.android.application*
- com.android.tools.build*
- org.jetbrains.kotlin*
- com.google.devtools.ksp*
# "*" ranks below toolchain's patterns; without patterns these groups would outrank it
minor-patch:
patterns: ["*"]
update-types: [minor, patch]
major:
patterns: ["*"]
update-types: [major]
commit-message:
prefix: chore(deps)
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
cooldown:
default-days: 5
groups:
minor-patch:
update-types: [minor, patch]
major:
update-types: [major]
commit-message:
prefix: chore(deps)
+7
View File
@@ -0,0 +1,7 @@
## What
## Why
## Checked
<!-- e.g. ./gradlew testDebugUnitTest lintDebug, and what you saw on a device or emulator -->
Binary file not shown.

After

Width:  |  Height:  |  Size: 249 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 KiB

@@ -6,10 +6,15 @@ on:
tags: [ 'v*' ]
pull_request:
branches: [ "master" ]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
jobs:
test:
name: Run Unit Tests
@@ -19,20 +24,14 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: Set up JDK 17
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # 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
- name: Run unit tests and lint
run: ./gradlew testDebugUnitTest lintDebug
build:
name: Build Signed APK
@@ -44,15 +43,12 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: Set up JDK 17
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # 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 }}
@@ -86,7 +82,7 @@ jobs:
"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
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: paperize-${{ steps.get_version.outputs.VERSION_NAME }}
path: app/build/outputs/apk/release/paperize-${{ steps.get_version.outputs.VERSION_NAME }}.apk
@@ -101,16 +97,14 @@ jobs:
contents: write
steps:
- name: Download signed APK artifact
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
with:
pattern: paperize-v*
path: ./apk-artifact
merge-multiple: true
- name: Create Draft Release
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3
with:
files: ./apk-artifact/paperize-v*.apk
draft: true
generate_release_notes: true
@@ -12,6 +12,10 @@ permissions:
contents: read
security-events: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
analyze-actions:
name: Analyze GitHub Actions
@@ -21,13 +25,13 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: Initialize CodeQL
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
with:
languages: actions
build-mode: none
- name: Perform CodeQL analysis
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
analyze-java-kotlin:
name: Analyze Java and Kotlin
@@ -37,23 +41,20 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: Set up JDK 17
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6
with:
java-version: "17"
distribution: temurin
cache: gradle
- name: Initialize CodeQL
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # 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
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
+107
View File
@@ -0,0 +1,107 @@
name: Crowdin Sync
on:
push:
branches: [ "master" ]
paths:
- app/src/main/res/values/strings.xml
- crowdin.yml
- .github/workflows/crowdin.yml
schedule:
- cron: "0 8 * * 1"
workflow_dispatch:
inputs:
upload_translations:
description: Send the translations in the repository to Crowdin as approved first
type: boolean
default: false
concurrency:
group: crowdin-sync
permissions:
actions: write
contents: write
pull-requests: write
env:
BRANCH: crowdin-translations
jobs:
synchronize-with-crowdin:
name: Synchronize with Crowdin
runs-on: ubuntu-latest
steps:
- name: Checkout repository source code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: Upload sources and download approved translations
uses: crowdin/github-action@d651c77756acbe11a31d77a6fb79d8a239e1e05a # v3
with:
crowdin_branch_name: main
upload_sources: true
upload_translations: ${{ inputs.upload_translations || false }}
auto_approve_imported: true
download_translations: false
download_bundle: 15
push_translations: false
create_pull_request: false
env:
CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
# Keeps every string the repository already ships, drops strings English no longer has,
# and only adds a new locale once it covers 90% of the English strings.
- name: Merge into the shipped translations
shell: python
run: |
import os, re, shutil, subprocess
from pathlib import Path
res = Path("app/src/main/res")
entry = re.compile(r'<(string|plurals|string-array)\b[^>]*?\bname="([^"]+)"[^>]*>.*?</\1>', re.S)
# Crowdin adds the string's context as a comment attribute.
def entries(text):
return {m.group(2): re.sub(r' comment="[^"]*"', "", m.group(0), count=1) for m in entry.finditer(text)}
def shipped(path):
out = subprocess.run(["git", "show", f"HEAD:{path.as_posix()}"], capture_output=True, text=True)
return out.stdout if out.returncode == 0 else None
subprocess.run(["sudo", "chown", "-R", str(os.getuid()), str(res)], check=True)
source = [k for k, v in entries((res / "values/strings.xml").read_text("utf-8")).items()
if 'translatable="false"' not in v.split(">", 1)[0]]
for path in sorted(res.glob("values-*/strings.xml")):
old_text = shipped(path)
new, old = entries(path.read_text("utf-8")), entries(old_text or "")
merged = [new.get(k) or old[k] for k in source if k in new or k in old]
if old_text is None and len(merged) < 0.9 * len(source):
shutil.rmtree(path.parent)
continue
if merged == [old[k] for k in source if k in old]:
subprocess.run(["git", "checkout", "--", str(path)], check=True)
continue
body = "".join(f" {e}\n" for e in merged)
path.write_text(f'<?xml version="1.0" encoding="utf-8"?>\n<resources>\n{body}</resources>\n', "utf-8")
# Pull requests opened with GITHUB_TOKEN start no workflows, so the checks are dispatched.
- name: Open the translations pull request
env:
GH_TOKEN: ${{ github.token }}
run: |
if [ -z "$(git status --porcelain app/src/main/res)" ]; then
echo "No translation changes"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -C "$BRANCH"
git add app/src/main/res
git commit -m "chore: update translations"
git push --force origin "$BRANCH"
if [ -z "$(gh pr list --head "$BRANCH" --state open --json number --jq '.[].number')" ]; then
gh pr create --base master --head "$BRANCH" --title "chore: update translations" \
--body "Approved translations from [Crowdin](https://crowdin.com/project/paperize)."
fi
gh workflow run android-release.yml --ref "$BRANCH"
@@ -0,0 +1,21 @@
name: Dependabot auto-merge
on: pull_request
permissions:
contents: write
pull-requests: write
jobs:
auto-merge:
if: github.event.pull_request.user.login == 'dependabot[bot]'
runs-on: ubuntu-latest
steps:
- id: meta
uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3
# Waits for the ruleset's required checks
- if: steps.meta.outputs.dependency-group == 'minor-patch' && contains(fromJSON('["version-update:semver-minor", "version-update:semver-patch"]'), steps.meta.outputs.update-type)
run: gh pr merge --auto --squash "$PR_URL"
env:
PR_URL: ${{ github.event.pull_request.html_url }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+40
View File
@@ -0,0 +1,40 @@
name: Pages
on:
push:
branches: [ "master" ]
paths:
- "site/**"
- ".github/workflows/pages.yml"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: pages
cancel-in-progress: false
jobs:
deploy:
name: Deploy site
runs-on: ubuntu-latest
permissions:
contents: read
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Checkout repository source code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: Upload site
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5
with:
path: site
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5
+2 -2
View File
@@ -16,6 +16,6 @@
local.properties
/app/build
/app/release
/app/schemas
.kotlin
/.kotlin/sessions
/.kotlin/sessions
*.jks
+81
View File
@@ -0,0 +1,81 @@
# Working on Paperize
An Android app that changes the home and lock screen wallpaper on a schedule: Kotlin, Jetpack Compose, Material 3, Hilt, Room. Users get it from GitHub releases, F-Droid and IzzyOnDroid.
## Code
- Simple and direct. No speculative abstractions, options or extension points.
- Stay in scope; suggest extras instead of adding them.
- Use what the platform, framework, dependencies and this repo already provide before writing a helper.
- Validate only at real boundaries (user input, storage, network, other processes). No checks, fallbacks or try/catch for cases that can't happen.
- One source of truth for each value or rule.
- Delete dead code you find or create.
- Match the surrounding code.
- Fix root causes, and fix the same pattern everywhere it occurs.
## Comments
- Only where the reason isn't clear from the code: a quirk, a race, a non-obvious decision.
- Short fragments, not sentences. Never restate code, narrate, or label sections.
- Delete comments that no longer match.
## Tests
- Behaviour and the edges that can break. No trivial, duplicate, obvious or low-signal tests.
- A regression test fails without its fix.
- Deterministic: fake time and observable events, no sleeps.
- A failing test is a bug until shown otherwise.
## Paperize
- The UI can only be seen on an emulator or device. Run `./gradlew connectedDebugAndroidTest` there for anything touching rendering, scheduling, storage or imports.
- Dynamic colour swaps the brand palette for the system one, so a design must work with it on and off.
- English is the source language. Translations come through Crowdin: the sync workflow uploads `values/strings.xml` and opens its own pull request with approved translations only, adding a locale once most of it is approved. Add or reword strings in English only, and remove deleted strings from every locale. A locale file fixed by hand must also be sent to Crowdin with the sync workflow's upload option, or a later sync can replace the fix.
- A database schema change needs a migration that keeps user data, never a destructive fallback. Commit the exported schema.
- `metadata/en-US` is the F-Droid and IzzyOnDroid store listing: keep its text and screenshots true to the app.
- F-Droid rebuilds every release from source and compares it with the GitHub APK, so the build must stay reproducible. Its recipe deletes the `foojay` line from `settings.gradle.kts` with `sed`: keep that plugin on one line, and keep `dependenciesInfo` off.
- F-Droid pins the commit of every version: never rewrite a released commit or move a tag. `crowdin-translations` and `media` are live branches, not stale ones.
- `app/lint-baseline.xml` holds only deliberate exceptions; fix new warnings instead of adding them to it.
## Done means
- Diff reviewed against this file.
- `./gradlew testDebugUnitTest lintDebug` passes with zero warnings.
- UI changes seen in the running app, light and dark. Docs and metadata changes need no end-to-end run.
- README updated for anything users will notice; behaviour changes called out.
## Docs
- README is for users: what it does, how to get it, how to use it. No internals, no agent instructions.
- This file is for agents: only what can't be found quickly in the code.
- No meta docs in the repo (notes, audits, plans, reports).
- Generated images are built from the orphan `media` branch; its README has the steps.
## Git
- `type: summary` or `type(scope): summary`: lowercase, imperative, no full stop, about 70 characters at most. Types: `feat` `fix` `refactor` `perf` `test` `docs` `style` `build` `ci` `chore`.
- Body only to say why. `Fixes #123` closes an issue.
- One logical change per commit. Squash fix-ups before merging.
- Branch off `master`. A single commit fast-forwards; several merge with `merge: <summary>`.
- No AI attribution in commits, branches, PRs or releases.
- One maintainer: amending and force-pushing to tidy history is fine. Keep contributors as authors. Delete stale branches.
## Pull requests
- Title in commit format. Body: what changed, why, how it was checked. Short.
## Releases
- Bump commit `chore: release vX.Y.Z`; tag `vX.Y.Z`.
- A pushed `v*` tag is the store submission: F-Droid builds it straight away and compares the result with the release APK. CI attaches the signed APK to the tag's draft release (reusing a draft that already has notes), but a draft's APK isn't public: publish the draft as soon as CI has attached it, or the F-Droid comparison fails. Never rename a tag or asset.
- Title `Paperize X.Y.Z`.
- Notes: banner image first, then `### New`, `### Improved`, `### Fixed` (only those that apply). One line per change, written for users; no internals, dependency lists or test counts. End with the install links (APK, F-Droid, IzzyOnDroid) and the full changelog link.
- Banner: built and hosted on the `media` branch; reference its raw URL.
- The site in `site/` hosts the privacy policy the store listing links to at `#privacy`; keep that anchor.
## Agents
- Pushing, amending and force-pushing are allowed. Ask before publishing a release or submitting to a store.
- Leave changes you didn't make alone. Clean up scratch files, processes and emulators.
- Say what was checked and how, and what wasn't.
- Short replies; one recommendation, not a list of options.
-148
View File
@@ -1,148 +0,0 @@
## v4.2.2
- The live wallpaper loads one image when it starts instead of two, and redraws at once when dark mode changes with adaptive brightness on.
- The Library tab no longer leaves double spacing around the system bars.
- The shuffle and adaptive brightness descriptions hide whenever the setting is on, like the other settings.
- SVG files are no longer imported; they could never be shown as a wallpaper.
- Remove the unused boot and foreground-service permissions.
- Update the build tools and dependencies, and remove dead, duplicated and hand-rolled code.
## 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
+68 -112
View File
@@ -1,149 +1,105 @@
<div align="center">
<img style="display: block" src="https://github.com/user-attachments/assets/e8fb14f5-ec8e-440e-a2ac-8065322b0e28" alt="">
<h1>Paperize</h1>
<p><strong>A dynamic wallpaper changer that keeps your device's aesthetic fresh and exciting</strong></p>
<picture>
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/hero-dark.png">
<img src=".github/readme/hero-light.png" alt="Paperize: a fresh wallpaper, right on time. Three phones show the wallpaper tab, the album library and the effects.">
</picture>
[![GitHub Downloads](https://img.shields.io/github/downloads/Anthonyy232/Paperize/total?style=flat&logo=github&label=Downloads)](https://github.com/Anthonyy232/Paperize/releases)
[![GitHub Release](https://img.shields.io/github/v/release/Anthonyy232/Paperize?style=flat&logo=github)](https://github.com/Anthonyy232/Paperize/releases/latest)
[![License](https://img.shields.io/github/license/Anthonyy232/Paperize?style=flat)](LICENSE)
[![F-Droid](https://img.shields.io/f-droid/v/com.anthonyla.paperize?style=flat&logo=fdroid)](https://f-droid.org/en/packages/com.anthonyla.paperize/)
[![Crowdin](https://badges.crowdin.net/paperize/localized.svg)](https://crowdin.com/project/paperize)
</div>
<p align="center">
<a href="https://github.com/Anthonyy232/Paperize/releases/latest"><b>Download the APK</b></a>
&nbsp;·&nbsp;
<a href="https://f-droid.org/en/packages/com.anthonyla.paperize/"><b>F-Droid</b></a>
&nbsp;·&nbsp;
<a href="https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize"><b>IzzyOnDroid</b></a>
&nbsp;·&nbsp;
<a href="https://anthonyy232.github.io/Paperize/"><b>Website</b></a>
</p>
---
Paperize is an Android app that changes your home and lock screen wallpaper on a schedule, from albums you build out of your own images and folders. It works offline, has no internet permission, and needs Android 12 or newer.
## Features
<picture>
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-albums-dark.png">
<img src=".github/readme/feature-albums-light.png" alt="01. Albums, on rotation. The library with two albums, and an album open showing its wallpapers.">
</picture>
- **Dynamic Wallpaper Changer** — Set your wallpaper to change at specific time intervals
- **Static & Live Wallpapers** — Choose between traditional static wallpapers or smooth live wallpaper transitions
- **Multiple Image Formats** — Supports JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF, and TIFF
- **Folder Support** — Organize wallpapers into folders for auto-updating
- **Dual Screen Support** — Choose the same or separate albums for home and lock screen
- **Wallpaper Effects** — Apply various effects including brightness, blur, scaling, vignette, and more
- **On-Device Storage** — All wallpapers and settings stored locally on your device
An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and every hour while a schedule is running, so new files join the rotation and deleted ones leave it by themselves; **Refresh folder** rescans one straight away. Open an album's options menu to rename or delete it, filter it (encrypted albums), or rescan all its folders. Removing something from an album never touches the file on your device.
---
When creating an album, you can mark it encrypted; this choice is permanent and imports only `.jpg_enc` files made by wallpaper_changer. Set the same passphrase in **Settings → Encrypted albums**. **Filter wallpapers** in the album menu takes a regular expression matched (ignoring case) against each line of the folder's `naming_table.enc` (`name;encrypted file;hash`), as wallpaper_changer does; every image is imported but only matching ones are picked as wallpaper, and images in folders without a naming table never match. It is protected by Android Keystore and remains available for scheduled changes. Encrypted previews are off by default; enabling them decrypts images in memory without caching them to disk. Turning previews off removes them from the app's display. Android may still retain the applied wallpaper, and wallpaper_changer's encryption format does not authenticate its contents.
## Download
Supported formats: JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF and TIFF.
[<img src="https://github.com/Anthonyy232/Paperize/assets/60626873/1c034414-21cd-4a0a-838d-89fe7bd56910" alt="Download from GitHub" height="60">](https://github.com/Anthonyy232/Paperize/releases)
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="60">](https://f-droid.org/en/packages/com.anthonyla.paperize/)
[<img src="https://gitlab.com/IzzyOnDroid/repo/-/raw/master/assets/IzzyOnDroid.png" alt="Get it on IzzyOnDroid" height="60">](https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize)
<picture>
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-schedule-dark.png">
<img src=".github/readme/feature-schedule-light.png" alt="02. Home and lock, your call. The wallpaper tab with the current lock and home wallpapers, an album for each, and the time interval.">
</picture>
---
Turn on **Lock**, **Home** or both and pick an album for each. One interval covers both screens, from 15 minutes to 30 days; **Individual Scheduling** gives each screen its own. Wallpapers go in order unless **Shuffle** is on. Tired of the one on screen? Tap the bin under it in **Current Wallpapers** to take it out of its album and move on to the next. An image removed from a folder stays out when the folder is rescanned, and tapping it under **Removed** in that folder puts it back.
## Localization
<picture>
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-effects-dark.png">
<img src=".github/readme/feature-effects-light.png" alt="03. Effects, to taste. Brightness, blur and vignette, each with a switch for home and lock and a strength slider.">
</picture>
Help translate Paperize into your language! Currently, most translations are provided using machine translation — contributions from native speakers are greatly appreciated.
Brightness, blur, vignette and a gray filter each have a strength slider and separate switches for home and lock. **Adaptive Brightness** adjusts the wallpaper to the system's light or dark mode. Scaling is Fill, Fit, Stretch or None. **Blurred background** fills the space around a Fit wallpaper with a blurred copy of it instead of black, and **Horizontal scrolling** lets a wide Fill wallpaper move between home-screen pages.
**[Contribute on Crowdin →](https://crowdin.com/project/paperize/invite?h=d8d7a7513d2beb0c96ba9b2a5f85473e2084922)**
## How it works
---
1. On first launch, choose **Static Mode** or **Live Wallpaper Mode**.
2. In **Library**, tap **+** to create an album, then add images or a folder to it.
3. In **Wallpaper**, choose the screens and their albums, and set the time interval.
4. Leave the rest to Paperize. **Wallpaper changing** pauses and resumes the schedule without clearing your albums.
## Tech Stack
To skip ahead, use **Change wallpaper now** in the app, the Quick Settings tile, or the shortcut you get by long-pressing the app icon. In static mode you can also open any image in an album and set it as the wallpaper yourself. Tick **Continue rotation from here** to have the rotation carry on from that image; it is off by default and hidden while **Shuffle** is on.
| Category | Technology |
|----------|------------|
| **Language** | [Kotlin](https://kotlinlang.org/) |
| **UI Framework** | [Jetpack Compose](https://developer.android.com/develop/ui/compose) |
| **Design System** | [Material 3](https://m3.material.io/) |
| **Dependency Injection** | [Dagger Hilt](https://dagger.dev/hilt/) |
| **Database** | [Room](https://developer.android.com/training/data-storage/room) |
| **Image Loading** | [Coil](https://coil-kt.github.io/coil/) |
## Static and live modes
<details>
<summary><b>View all dependencies</b></summary>
**Static mode** sets ordinary wallpapers through the system, which is simple and light on the battery.
- [Zoomable](https://github.com/usuiat/Zoomable) — Zoomable and pannable views
**Live wallpaper mode** runs Paperize as a live wallpaper showing one album on both screens, and adds:
</details>
- a crossfade between wallpapers
- **Double-Tap to Change**
- **Change on Screen Off**
- **Parallax Effect**, which moves the wallpaper as you swipe between home-screen pages (your launcher has to support it)
- intervals down to 1 minute; intervals under 15 minutes only run while the wallpaper is visible
---
Switching modes in Settings resets your albums, wallpapers and settings.
## Architecture
## Settings
- `AlbumRepository` owns library mutations. Imports, 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.
- **Wallpaper Mode**: switch between static and live.
- **Dark Mode**, **Dynamic Theming** (Material You colours from your system) and **Animation**.
- **Battery Optimization**: Android may delay scheduled changes for apps it optimizes. Exempting Paperize keeps them on time.
- **Reset all data**: clears every album and setting.
## Building from Source
## Privacy
### Prerequisites
Albums and settings stay on your device, and Paperize has no internet permission. Read the [privacy policy](https://anthonyy232.github.io/Paperize/#privacy).
| 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 |
## Translations
### Build Steps
Paperize ships in more than 35 languages. To add or improve a language, translate it on [Crowdin](https://crowdin.com/project/paperize). Translations are reviewed there before they reach the app, and a new language is added once 90% of it has been reviewed.
1. **Clone the repository**
```bash
git clone https://github.com/Anthonyy232/Paperize.git
cd Paperize
```
## Building from source
2. **Open in Android Studio**
- Launch Android Studio
- Select `File > Open` and navigate to the cloned repository
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
---
### Verification
Set `ANDROID_HOME` to your Android SDK directory, or configure `sdk.dir` in
`local.properties`. Use the checked-in Gradle wrapper:
You need Java 17 and the Android SDK (`ANDROID_HOME`, or `sdk.dir` in `local.properties`). Paperize compiles against SDK 37 and runs on Android 12 (SDK 31) and newer.
```bash
./gradlew testDebugUnitTest lintDebug assembleDebug
./gradlew connectedDebugAndroidTest
git clone https://github.com/Anthonyy232/Paperize.git
cd Paperize
./gradlew assembleDebug
```
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.
The APK lands in `app/build/outputs/apk/debug`. Or open the folder in Android Studio and press Run.
For the development setup with an emulator on `lucas@quiethost`, `./build_and_install.sh` builds locally, installs the debug app and test APK remotely, copies test images, and runs the tests. The Android tests can cancel wallpaper schedules in the installed app.
## Contributing
Contributions are welcome! Feel free to:
Contributions are welcome. Report bugs in [issues](https://github.com/Anthonyy232/Paperize/issues), suggest features in [Discussions](https://github.com/Anthonyy232/Paperize/discussions), and read [AGENTS.md](AGENTS.md) before opening a pull request.
- Report bugs by opening an issue
- Suggest features or improvements
- Submit pull requests
---
## Support
If you find Paperize useful, consider supporting development through [GitHub Sponsors](https://github.com/sponsors/Anthonyy232) (one-time or monthly). Thank you!
---
If Paperize is useful to you, you can support it through [GitHub Sponsors](https://github.com/sponsors/Anthonyy232).
## License
This project is licensed under the **GNU General Public License v3.0** — see the [LICENSE](LICENSE) file for details.
Copyright (c) 2023-2026 Anthony La.
Paperize is free software, licensed under the [GNU General Public License v3.0](LICENSE) only, and comes with no warranty.
+3
View File
@@ -0,0 +1,3 @@
# Security
Please report vulnerabilities privately through the repository's [Report a vulnerability](https://github.com/Anthonyy232/Paperize/security/advisories/new) form on GitHub, not in a public issue.
+19 -5
View File
@@ -14,7 +14,9 @@ ksp {
android {
namespace = "com.anthonyla.paperize"
compileSdk = 37
compileSdk {
version = release(37) { minorApiLevel = 2 }
}
signingConfigs {
create("release") {
@@ -36,9 +38,9 @@ android {
defaultConfig {
applicationId = "com.anthonyla.paperize"
minSdk = 31
targetSdk = 36
versionCode = 59
versionName = "4.2.2"
targetSdk = 37
versionCode = 61
versionName = "4.3.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
@@ -73,6 +75,17 @@ android {
generateLocaleConfig = true
}
lint {
baseline = file("lint-baseline.xml")
// Crowdin exports no "many" form for Romance languages; Android falls back to "other".
disable += "MissingQuantity"
// App screens, not a library: a modifier no caller passes is dead weight.
disable += "ComposeModifierMissing"
// Dependabot handles updates; these fail the build whenever anything upstream releases.
disable += listOf("AndroidGradlePluginVersion", "GradleDependency", "NewerVersionAvailable")
warningsAsErrors = true
}
dependenciesInfo {
includeInApk = false
includeInBundle = false
@@ -82,6 +95,7 @@ android {
kotlin {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_17)
allWarningsAsErrors = true
}
}
@@ -93,7 +107,6 @@ dependencies {
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)
@@ -111,6 +124,7 @@ dependencies {
implementation(libs.androidx.hilt.work)
implementation(libs.androidx.foundation)
implementation(libs.androidx.profileinstaller)
lintChecks(libs.compose.lint.checks)
testImplementation(libs.junit)
testImplementation(libs.mockk)
testImplementation(libs.kotlinx.coroutines.test)
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 9.5.1" type="baseline" client="gradle" dependencies="false" name="AGP (9.5.1)" variant="all" version="9.5.1">
<issue
id="BatteryLife"
message="Use of `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` violates the Play Store Content Policy regarding acceptable use cases, as described in https://developer.android.com/training/monitoring-device-state/doze-standby.html"
errorLine1=" val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/com/anthonyla/paperize/core/util/BatteryOptimizationUtil.kt"
line="20"
column="42"/>
</issue>
</issues>
@@ -0,0 +1,444 @@
{
"formatVersion": 1,
"database": {
"version": 4,
"identityHash": "d071c2eda238d0ca9c8f55b5bf591395",
"entities": [
{
"tableName": "albums",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "createdAt",
"columnName": "createdAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "modifiedAt",
"columnName": "modifiedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
}
},
{
"tableName": "wallpapers",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderId",
"columnName": "folderId",
"affinity": "TEXT"
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fileName",
"columnName": "fileName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sourceType",
"columnName": "sourceType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mediaType",
"columnName": "mediaType",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpapers_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_wallpapers_folderId",
"unique": false,
"columnNames": [
"folderId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
},
{
"name": "index_wallpapers_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "folders",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"folderId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_folders_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_queue",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "queuePosition",
"columnName": "queuePosition",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpaper_queue_albumId_screenType",
"unique": false,
"columnNames": [
"albumId",
"screenType"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
},
{
"name": "index_wallpaper_queue_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
},
{
"name": "index_wallpaper_queue_queuePosition",
"unique": false,
"columnNames": [
"queuePosition"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_current",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "appliedAt",
"columnName": "appliedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"albumId",
"screenType"
]
},
"indices": [
{
"name": "index_wallpaper_current_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'd071c2eda238d0ca9c8f55b5bf591395')"
]
}
}
@@ -0,0 +1,512 @@
{
"formatVersion": 1,
"database": {
"version": 5,
"identityHash": "2457e5712f12294d683a5788349b5f84",
"entities": [
{
"tableName": "albums",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "createdAt",
"columnName": "createdAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "modifiedAt",
"columnName": "modifiedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
}
},
{
"tableName": "wallpapers",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderId",
"columnName": "folderId",
"affinity": "TEXT"
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fileName",
"columnName": "fileName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sourceType",
"columnName": "sourceType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mediaType",
"columnName": "mediaType",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpapers_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_wallpapers_folderId",
"unique": false,
"columnNames": [
"folderId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
},
{
"name": "index_wallpapers_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "folders",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"folderId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_folders_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_queue",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "queuePosition",
"columnName": "queuePosition",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpaper_queue_albumId_screenType",
"unique": false,
"columnNames": [
"albumId",
"screenType"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
},
{
"name": "index_wallpaper_queue_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
},
{
"name": "index_wallpaper_queue_queuePosition",
"unique": false,
"columnNames": [
"queuePosition"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_current",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "appliedAt",
"columnName": "appliedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"albumId",
"screenType"
]
},
"indices": [
{
"name": "index_wallpaper_current_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "excluded_wallpapers",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "folderId",
"columnName": "folderId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fileName",
"columnName": "fileName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"folderId",
"uri"
]
},
"foreignKeys": [
{
"table": "folders",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"folderId"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2457e5712f12294d683a5788349b5f84')"
]
}
}
@@ -0,0 +1,519 @@
{
"formatVersion": 1,
"database": {
"version": 6,
"identityHash": "126e2fefe2b0a0804b9ce27d880edf8f",
"entities": [
{
"tableName": "albums",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, `isEncrypted` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "createdAt",
"columnName": "createdAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "modifiedAt",
"columnName": "modifiedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isEncrypted",
"columnName": "isEncrypted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
}
},
{
"tableName": "wallpapers",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderId",
"columnName": "folderId",
"affinity": "TEXT"
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fileName",
"columnName": "fileName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sourceType",
"columnName": "sourceType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mediaType",
"columnName": "mediaType",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpapers_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_wallpapers_folderId",
"unique": false,
"columnNames": [
"folderId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
},
{
"name": "index_wallpapers_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "folders",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"folderId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_folders_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_queue",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "queuePosition",
"columnName": "queuePosition",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpaper_queue_albumId_screenType",
"unique": false,
"columnNames": [
"albumId",
"screenType"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
},
{
"name": "index_wallpaper_queue_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
},
{
"name": "index_wallpaper_queue_queuePosition",
"unique": false,
"columnNames": [
"queuePosition"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_current",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "appliedAt",
"columnName": "appliedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"albumId",
"screenType"
]
},
"indices": [
{
"name": "index_wallpaper_current_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "excluded_wallpapers",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "folderId",
"columnName": "folderId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fileName",
"columnName": "fileName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"folderId",
"uri"
]
},
"foreignKeys": [
{
"table": "folders",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"folderId"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '126e2fefe2b0a0804b9ce27d880edf8f')"
]
}
}
@@ -0,0 +1,524 @@
{
"formatVersion": 1,
"database": {
"version": 7,
"identityHash": "dd85d0b5892ec87e1bc8906b1f42a004",
"entities": [
{
"tableName": "albums",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, `isEncrypted` INTEGER NOT NULL DEFAULT 0, `filter` TEXT, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "createdAt",
"columnName": "createdAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "modifiedAt",
"columnName": "modifiedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isEncrypted",
"columnName": "isEncrypted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "filter",
"columnName": "filter",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
}
},
{
"tableName": "wallpapers",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folderId",
"columnName": "folderId",
"affinity": "TEXT"
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fileName",
"columnName": "fileName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sourceType",
"columnName": "sourceType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "mediaType",
"columnName": "mediaType",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpapers_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_wallpapers_folderId",
"unique": false,
"columnNames": [
"folderId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
},
{
"name": "index_wallpapers_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "folders",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"folderId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "coverUri",
"columnName": "coverUri",
"affinity": "TEXT"
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_albumId",
"unique": false,
"columnNames": [
"albumId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
},
{
"name": "index_folders_uri",
"unique": false,
"columnNames": [
"uri"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_queue",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "queuePosition",
"columnName": "queuePosition",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_wallpaper_queue_albumId_screenType",
"unique": false,
"columnNames": [
"albumId",
"screenType"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
},
{
"name": "index_wallpaper_queue_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
},
{
"name": "index_wallpaper_queue_queuePosition",
"unique": false,
"columnNames": [
"queuePosition"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "wallpaper_current",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "albumId",
"columnName": "albumId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "screenType",
"columnName": "screenType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wallpaperId",
"columnName": "wallpaperId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "appliedAt",
"columnName": "appliedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"albumId",
"screenType"
]
},
"indices": [
{
"name": "index_wallpaper_current_wallpaperId",
"unique": false,
"columnNames": [
"wallpaperId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
}
],
"foreignKeys": [
{
"table": "albums",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"albumId"
],
"referencedColumns": [
"id"
]
},
{
"table": "wallpapers",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"wallpaperId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "excluded_wallpapers",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "folderId",
"columnName": "folderId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "uri",
"columnName": "uri",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "fileName",
"columnName": "fileName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "dateModified",
"columnName": "dateModified",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayOrder",
"columnName": "displayOrder",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "addedAt",
"columnName": "addedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"folderId",
"uri"
]
},
"foreignKeys": [
{
"table": "folders",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"folderId"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'dd85d0b5892ec87e1bc8906b1f42a004')"
]
}
}
@@ -72,7 +72,7 @@ class DocumentAccessInstrumentedTest {
}
provider.answer = { cursor }
try {
treeUri.scanFolderImages(context)
treeUri.scanFolderImages(context, false)
fail("Expected incomplete scan failure")
} catch (_: java.io.IOException) { }
assertTrue(cursor.isClosed)
@@ -91,13 +91,52 @@ class DocumentAccessInstrumentedTest {
}
}
}
val found = treeUri.scanFolderImages(context)
val found = treeUri.scanFolderImages(context, false)
assertEquals(1, found.size)
assertEquals("photo.PNG", found.single().name)
assertEquals(42L, found.single().modifiedAt)
assertEquals(2, provider.queries)
}
@Test fun scansOnlyFilesForTheAlbumModeIncludingNestedDirectories() = runBlocking {
provider.answer = { uri ->
when (DocumentsContract.getDocumentId(uri)) {
"root" -> directoryCursor().apply {
addRow(arrayOf<Any>("child", "Child", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
addRow(arrayOf<Any>("plain", "photo.JPG", "image/jpeg", 1L))
addRow(arrayOf<Any>("encrypted", "photo.JPG_ENC", "application/octet-stream", 2L))
addRow(arrayOf<Any>("other", "photo.png_enc", "application/octet-stream", 3L))
}
else -> directoryCursor().apply {
addRow(arrayOf<Any>("nested", "nested.jpg_enc", "application/octet-stream", 4L))
}
}
}
assertEquals(setOf("photo.JPG"), treeUri.scanFolderImages(context, false).map { it.name }.toSet())
assertEquals(setOf("photo.JPG_ENC", "nested.jpg_enc"), treeUri.scanFolderImages(context, true).map { it.name }.toSet())
}
@Test fun scanSkipsTrashedFilesButKeepsImagesInHiddenFolders() = runBlocking {
provider.answer = { uri ->
when (DocumentsContract.getDocumentId(uri)) {
"root" -> directoryCursor().apply {
addRow(arrayOf<Any>("trashed", ".trashed54970.jpg", "image/jpeg", 1L))
addRow(arrayOf<Any>("trash", ".Trash-123.png", "image/png", 2L))
addRow(arrayOf<Any>("primary:Pictures/.trashed-1797497267-old.jpg", "old.jpg", "image/jpeg", 5L))
addRow(arrayOf<Any>("primary:.trashed-1797497267-top.jpg", "top.jpg", "image/jpeg", 6L))
addRow(arrayOf<Any>("primary:Pictures/.walls", ".walls", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
addRow(arrayOf<Any>("plain", "photo.jpg", "image/jpeg", 3L))
}
"primary:Pictures/.walls" -> directoryCursor().apply {
addRow(arrayOf<Any>("primary:Pictures/.walls/wall.png", "wall.png", "image/png", 4L))
}
else -> directoryCursor()
}
}
val found = treeUri.scanFolderImages(context, false)
assertEquals(setOf("photo.jpg", "wall.png"), found.map { it.name }.toSet())
}
@Test fun failureInChildFolderDoesNotReturnPartialImport() = runBlocking {
provider.answer = { uri ->
if (DocumentsContract.getDocumentId(uri) == "root") directoryCursor().apply {
@@ -106,7 +145,7 @@ class DocumentAccessInstrumentedTest {
} else null
}
try {
treeUri.scanFolderImages(context)
treeUri.scanFolderImages(context, false)
fail("Expected child folder failure")
} catch (_: java.io.IOException) { }
}
@@ -120,7 +159,7 @@ class DocumentAccessInstrumentedTest {
check(cancelled.await(5, TimeUnit.SECONDS)) { "Provider query was not cancelled" }
signal?.throwIfCanceled()
}
val scan = launch(Dispatchers.IO) { treeUri.scanFolderImages(context) }
val scan = launch(Dispatchers.IO) { treeUri.scanFolderImages(context, false) }
assertTrue(started.await(5, TimeUnit.SECONDS))
scan.cancel()
scan.join()
@@ -149,6 +149,38 @@ class WallpaperUtilInstrumentedTest {
}
}
@Test
fun blurredFitBackgroundFillsTheBarsFromTheImage() {
val source = mutableBitmap(80, 40, Color.RED)
val result = finalizeToCanvas(source, 40, 80, ScalingType.FIT, blurFitBackground = true)
try {
assertEquals(Color.RED, result.getPixel(20, 0))
assertEquals(Color.RED, result.getPixel(20, 40))
} finally {
result.recycle()
}
}
@Test
fun blurredBackdropAveragesFineDetailInsteadOfSamplingIt() {
val source = Bitmap.createBitmap(512, 256, Bitmap.Config.ARGB_8888)
val checker = IntArray(512 * 256) { i -> if ((i % 512 + i / 512) % 2 == 0) Color.WHITE else Color.BLACK }
source.setPixels(checker, 0, 512, 0, 0, 512, 256)
val backdrop = createBlurredBackdrop(source)
try {
assertEquals(64, backdrop.width)
assertEquals(32, backdrop.height)
for (y in 0 until backdrop.height) {
for (x in 0 until backdrop.width) {
assertTrue("Pixel $x,$y", Color.red(backdrop.getPixel(x, y)) in 100..155)
}
}
} finally {
source.recycle()
backdrop.recycle()
}
}
@Test
fun disabledStaticEffectsLeaveBitmapUntouched() {
val source = mutableBitmap(32, 32, Color.rgb(240, 80, 20))
@@ -16,7 +16,7 @@ class LibraryMigrationInstrumentedTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
@Test fun everyLegacyVersionPreservesLibraryAndQueue() = runBlocking {
for (version in 1..3) {
for (version in 1..4) {
val name = "migration-test-$version"
context.deleteDatabase(name)
try {
@@ -26,6 +26,7 @@ class LibraryMigrationInstrumentedTest {
try {
assertEquals("My album", db.albumDao().getAlbumById("album")?.name)
assertEquals("content://image", db.albumDao().getAlbumById("album")?.coverUri)
assertFalse(db.albumDao().getAlbumById("album")!!.isEncrypted)
val image = db.wallpaperDao().getWallpaperById("image")!!
assertEquals("folder", image.folderId)
assertEquals("photo.jpg", image.fileName)
@@ -34,6 +35,7 @@ class LibraryMigrationInstrumentedTest {
assertEquals("content://image", db.folderDao().getFolderById("folder")?.coverUri)
assertEquals(listOf("image"), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
assertEquals(if (version >= 3) "image" else null, db.wallpaperCurrentDao().getCurrentWallpaperFlow("album", ScreenType.HOME).first()?.id)
assertTrue(db.excludedWallpaperDao().getUris("folder").isEmpty())
db.openHelper.readableDatabase.query("PRAGMA foreign_key_check").use { assertEquals(0, it.count) }
db.albumDao().deleteAlbumById("album")
assertNull(db.wallpaperDao().getWallpaperById("image"))
@@ -43,6 +45,61 @@ class LibraryMigrationInstrumentedTest {
}
}
@Test fun bothVersionFiveSchemasMigrateToTheCombinedSchema() = runBlocking {
for (hasEncryptionColumn in listOf(false, true)) {
val name = "migration-test-v5-encrypted-$hasEncryptionColumn"
context.deleteDatabase(name)
try {
createVersionFiveDatabase(name, hasEncryptionColumn)
val db = Room.databaseBuilder(context, PaperizeDatabase::class.java, name)
.addMigrations(*LIBRARY_MIGRATIONS).build()
try {
assertEquals(hasEncryptionColumn, db.albumDao().getAlbumById("album")!!.isEncrypted)
assertEquals(
if (hasEncryptionColumn) emptyList<String>() else listOf("content://excluded"),
db.excludedWallpaperDao().getUris("folder")
)
db.openHelper.readableDatabase.query("PRAGMA foreign_key_check").use { assertEquals(0, it.count) }
} finally { db.close() }
} finally { context.deleteDatabase(name) }
}
}
private fun createVersionFiveDatabase(name: String, hasEncryptionColumn: Boolean) {
val schema = InstrumentationRegistry.getInstrumentation().context.assets
.open("com.anthonyla.paperize.data.database.PaperizeDatabase/4.json")
.bufferedReader().use { JSONObject(it.readText()).getJSONObject("database").getJSONArray("entities") }
val path = context.getDatabasePath(name)
path.parentFile!!.mkdirs()
SQLiteDatabase.openOrCreateDatabase(path, null).use { db ->
db.setForeignKeyConstraintsEnabled(true)
for (index in 0 until schema.length()) {
val entity = schema.getJSONObject(index)
val table = entity.getString("tableName")
if (table == "excluded_wallpapers") continue
db.execSQL(entity.getString("createSql").replace("\${TABLE_NAME}", table))
val indices = entity.optJSONArray("indices")
if (indices != null) for (i in 0 until indices.length()) {
db.execSQL(indices.getJSONObject(i).getString("createSql").replace("\${TABLE_NAME}", table))
}
}
if (hasEncryptionColumn) {
db.execSQL("ALTER TABLE `albums` ADD COLUMN `isEncrypted` INTEGER NOT NULL DEFAULT 0")
} else {
db.execSQL("CREATE TABLE IF NOT EXISTS `excluded_wallpapers` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE)")
}
db.execSQL(
"INSERT INTO albums (id, name, coverUri, createdAt, modifiedAt${if (hasEncryptionColumn) ", isEncrypted" else ""}) " +
"VALUES ('album', 'My album', 'content://image', 1, 2${if (hasEncryptionColumn) ", 1" else ""})"
)
db.execSQL("INSERT INTO folders (id, albumId, name, uri, coverUri, dateModified, displayOrder, addedAt) VALUES ('folder', 'album', 'Photos', 'content://tree', 'content://image', 3, 0, 4)")
if (!hasEncryptionColumn) {
db.execSQL("INSERT INTO excluded_wallpapers VALUES ('folder', 'content://excluded', 'excluded', 'excluded.jpg', 5, 6, 7)")
}
db.version = 5
}
}
private fun createLegacyDatabase(name: String, version: Int) {
val schema = InstrumentationRegistry.getInstrumentation().context.assets
.open("com.anthonyla.paperize.data.database.PaperizeDatabase/4.json")
@@ -57,9 +114,10 @@ class LibraryMigrationInstrumentedTest {
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`)")
if (table == "wallpapers") create = when (version) {
1 -> create.replace("`mediaType` TEXT NOT NULL, ", "")
2, 3 -> create.replace("PRIMARY KEY(`id`)", "`cropOffsetX` REAL, `cropOffsetY` REAL, `cropScale` REAL, PRIMARY KEY(`id`)")
else -> create
}
db.execSQL(create)
val indices = entity.optJSONArray("indices")
@@ -11,7 +11,10 @@ import com.anthonyla.paperize.data.database.PaperizeDatabase
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.mapper.toEntity
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.source.WallpaperRenderer
import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase
import kotlinx.coroutines.async
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
@@ -26,11 +29,32 @@ import org.junit.runner.RunWith
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)
private val documents = com.anthonyla.paperize.data.source.AndroidDocumentSource(context)
private val wallpapers = WallpaperRepositoryImpl(db, documents, com.anthonyla.paperize.data.source.EncryptedImageStore(context))
private val albums = AlbumRepositoryImpl(documents, db)
@After fun close() = db.close()
@Test fun renamingPreservesAlbumContentsAndRejectsOtherNamesIgnoringCase() = runBlocking {
val album = albums.createAlbum("Original", isEncrypted = true)
albums.addWallpapersToAlbum(album.id, listOf(testWallpaper("image", album.id)))
albums.createAlbum("Other")
assertFalse(albums.renameAlbum(album.id, "other"))
assertTrue(albums.renameAlbum(album.id, "ORIGINAL"))
assertTrue(albums.renameAlbum(album.id, "Renamed"))
val saved = albums.getAlbumById(album.id).first()!!
assertEquals("Renamed", saved.name)
assertTrue(saved.isEncrypted)
assertEquals(listOf("image"), saved.wallpapers.map { it.id })
}
@Test fun encryptedAlbumModeSurvivesPersistence() = runBlocking {
val album = albums.createAlbum("Encrypted", isEncrypted = true)
assertTrue(album.isEncrypted)
assertTrue(albums.getAlbumById(album.id).first()!!.isEncrypted)
assertFalse(albums.createAlbum("Ordinary").isEncrypted)
}
@Test fun cancellingAChunkedFolderImportRollsBackAllRows() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val folder = testFolder("folder", "album").copy(
@@ -105,6 +129,23 @@ class AlbumRepositoryInstrumentedTest {
assertEquals(0, albums.addWallpapersToAlbum("album", listOf(image.copy(id = "stale", folderId = "folder"))))
}
@Test fun continuingFromAPickedWallpaperFollowsAlbumOrderAndWraps() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
db.wallpaperDao().insertWallpapers((1..5).map {
testWallpaper("$it", "album").copy(uri = "content://$it", displayOrder = it).toEntity()
})
val change = ChangeWallpaperUseCase(wallpapers, SettingsRepositoryImpl(context), object : WallpaperRenderer {
override suspend fun render(wallpaper: Wallpaper, screen: ScreenType, settings: ScheduleSettings) = null
})
suspend fun next() = change.dequeueNext("album", ScreenType.HOME, shuffle = false).id
change.completeSpecific("album", ScreenType.HOME, "3", shuffle = false, startSequenceHere = true)
assertEquals(listOf("4", "5", "1"), List(3) { next() })
change.completeSpecific("album", ScreenType.HOME, "5", shuffle = false, startSequenceHere = true)
assertEquals("1", next())
}
@Test fun concurrentQueueCreationKeepsBothScreensInSyncAndDoesNotRefillConsumedItems() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
albums.addWallpapersToAlbum("album", (1..8).map {
@@ -120,4 +161,71 @@ class AlbumRepositoryInstrumentedTest {
wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, true)
assertEquals(expected.drop(1), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
}
@Test fun syncFolderWallpapersRemovesOnlyThatFoldersMissingFilesAndAddsNewOnes() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(
wallpapers = (1..5).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
))
albums.addWallpapersToAlbum("album", listOf(testWallpaper("direct", "album").copy(uri = "content://photo-3")))
val scanned = listOf(1, 2, 4, 5, 6).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
val added = albums.syncFolderWallpapers("album", "folder", scanned)
assertEquals(1, added)
assertEquals(
listOf(1, 2, 4, 5, 6).map { "content://photo-$it" }.toSet(),
db.wallpaperDao().getUrisInCollection("album", "folder").toSet()
)
assertEquals(listOf("content://photo-3"), db.wallpaperDao().getUrisInCollection("album", null))
}
@Test fun syncFolderWallpapersKeepsRowsWhenScanIsEmpty() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(
wallpapers = listOf(testWallpaper("image-1", "album").copy(folderId = "folder", uri = "content://photo-1"))
))
assertEquals(0, albums.syncFolderWallpapers("album", "folder", emptyList()))
assertEquals(1, db.wallpaperDao().getUrisInCollection("album", "folder").size)
}
@Test fun removedFolderImageStaysOutOfRescansUntilRestoredInPlace() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val images = (1..3).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(wallpapers = images))
val removed = albums.removeWallpaper("image-2")!!
assertEquals(0, albums.syncFolderWallpapers("album", "folder", images))
val folder = albums.getFolderById("folder").first()!!
assertEquals(setOf("image-1", "image-3"), folder.wallpapers.map { it.id }.toSet())
assertEquals(listOf(removed), folder.removedWallpapers)
albums.restoreWallpaper(removed)
assertEquals(listOf("image-1", "image-2", "image-3"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
assertTrue(albums.getFolderById("folder").first()!!.removedWallpapers.isEmpty())
}
@Test fun rescanForgetsRemovedImagesWhoseFilesAreGone() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val images = (1..2).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(wallpapers = images))
albums.removeWallpaper("image-1")
albums.syncFolderWallpapers("album", "folder", images.drop(1))
assertTrue(albums.getFolderById("folder").first()!!.removedWallpapers.isEmpty())
// The file coming back later is a new image, not a removed one.
assertEquals(1, albums.syncFolderWallpapers("album", "folder", images))
}
@Test fun undoingADirectImageImportedAgainAddsNoDuplicate() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val image = testWallpaper("image", "album").copy(uri = "content://photo")
albums.addWallpapersToAlbum("album", listOf(image))
val removed = albums.removeWallpaper("image")!!
albums.addWallpapersToAlbum("album", listOf(image.copy(id = "again")))
albums.restoreWallpaper(removed)
assertEquals(listOf("again"), db.wallpaperDao().getWallpaperIdsByAlbum("album"))
}
}
@@ -14,6 +14,19 @@ import org.junit.Assert.*
import org.junit.Test
class SettingsRepositoryInstrumentedTest {
@Test fun encryptedPreviewSettingPersistsAndCanBeDisabled() = runBlocking {
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
val original = preferences.getAppSettings().encryptedPreviews
try {
preferences.updateEncryptedPreviews(true)
assertTrue(preferences.getAppSettings().encryptedPreviews)
preferences.updateEncryptedPreviews(false)
assertFalse(preferences.getAppSettings().encryptedPreviews)
} finally {
preferences.updateEncryptedPreviews(original)
}
}
@Test fun concurrentScheduleEditsReadTheLatestValueWithoutLosingSelections() = runBlocking {
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
val previousSettings = preferences.getScheduleSettings()
@@ -62,7 +75,7 @@ class SettingsRepositoryInstrumentedTest {
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 = lockEffects, liveEffects = liveEffects,
homeScrollingEnabled = true, blurFitBackground = true, homeEffects = effects, lockEffects = lockEffects, liveEffects = liveEffects,
adaptiveBrightness = true
)
preferences.updateScheduleSettings(full)
@@ -0,0 +1,89 @@
package com.anthonyla.paperize.data.source
import android.content.ContentProvider
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.ContextWrapper
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
@RunWith(AndroidJUnit4::class)
class EncryptedImageStoreInstrumentedTest {
private val app = ApplicationProvider.getApplicationContext<Context>()
private val directory = File(app.cacheDir, "encrypted-image-store-test").apply { mkdirs() }
private val encryptedFile = File(directory, "image")
private val provider = ImageProvider(encryptedFile)
private val context = object : ContextWrapper(app) {
override fun getNoBackupFilesDir(): File = directory
override fun getContentResolver(): ContentResolver = ContentResolver.wrap(provider)
}
private val uri = Uri.parse("content://test/image")
private val encrypted = (
"53616c7465645f5f00010203040506075fccfb3397721c83694890dfe23e4516" +
"7b69d90d234d801114bb019d584a6f47"
).chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@After fun cleanup() {
directory.deleteRecursively()
}
@Test fun persistsEncryptedPassphraseAndDecryptsProviderStream() {
encryptedFile.writeBytes(encrypted)
val store = EncryptedImageStore(context)
assertEquals(0, store.revision.value)
assertFalse(store.hasPassphrase())
assertThrows(MissingPassphraseException::class.java) { store.decrypt(uri) }
store.setPassphrase("päss漢字")
assertEquals(1, store.revision.value)
val stored = File(directory, "encrypted_image_passphrase").readBytes()
assertFalse(stored.toString(Charsets.UTF_8).contains("päss漢字"))
val reopened = EncryptedImageStore(context)
assertTrue(reopened.hasPassphrase())
assertArrayEquals(
"Paperize test image\u0000".toByteArray() + byteArrayOf(0xff.toByte()),
reopened.decrypt(uri)
)
reopened.setPassphrase("wrong")
assertEquals(1, reopened.revision.value)
assertThrows(IncorrectPassphraseException::class.java) { reopened.decrypt(uri) }
reopened.clearPassphrase()
assertEquals(2, reopened.revision.value)
assertFalse(store.hasPassphrase())
assertThrows(MissingPassphraseException::class.java) { reopened.decrypt(uri) }
}
@Test fun rejectsTamperedStoredPassphrase() {
val store = EncryptedImageStore(context)
store.setPassphrase("secret")
val file = File(directory, "encrypted_image_passphrase")
file.writeBytes(file.readBytes().apply { this[lastIndex] = (last().toInt() xor 1).toByte() })
assertThrows(PassphraseStorageException::class.java) { store.decrypt(uri) }
}
private class ImageProvider(private val file: File) : ContentProvider() {
override fun onCreate() = true
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor =
ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<out String>?): Int = 0
}
}
@@ -0,0 +1,145 @@
package com.anthonyla.paperize.data.source
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.util.getDeviceScreenSize
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.service.livewallpaper.renderer.EncryptedImageLoader
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.UUID
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class EncryptedRenderingInstrumentedTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val directory = File(instrumentation.targetContext.cacheDir, "encrypted-render-${UUID.randomUUID()}")
private val context = object : ContextWrapper(instrumentation.targetContext) {
override fun getNoBackupFilesDir(): File = directory
}
private val encryptedFile = File(directory, "image.jpg_enc")
private val uri = Uri.fromFile(encryptedFile)
private val store = EncryptedImageStore(context)
private val renderer = AndroidWallpaperRenderer(context, store)
private val loader = EncryptedImageLoader(store, uri)
private val wallpaper = Wallpaper(
id = "image", albumId = "album", uri = uri.toString(),
fileName = "image.jpg_enc", dateModified = 0
)
private val passphrase = "päss漢字"
private lateinit var wrongPassphrase: String
@Before fun setup() {
check(directory.mkdirs())
val image = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)
val jpeg = try {
image.eraseColor(Color.rgb(220, 30, 40))
ByteArrayOutputStream().use { output ->
check(image.compress(Bitmap.CompressFormat.JPEG, 100, output))
output.toByteArray()
}
} finally {
image.recycle()
}
val encrypted = encryptTestJpeg(jpeg, passphrase)
encryptedFile.writeBytes(encrypted)
// CBC has no authentication; choose a wrong key that actually fails padding.
wrongPassphrase = (0..100).asSequence().map { "wrong-$it" }.first { candidate ->
try {
decryptEncryptedImage(encrypted, candidate).fill(0)
false
} catch (_: IncorrectPassphraseException) {
true
}
}
store.setPassphrase(passphrase)
}
@After fun cleanup() {
directory.deleteRecursively()
}
@Test fun rendersDecryptedJpegInStaticAndLivePaths() {
val rendered = runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
assertNotNull(rendered)
checkNotNull(rendered)
try {
val screen = getDeviceScreenSize(context)
assertEquals(screen.width, rendered.width)
assertEquals(screen.height, rendered.height)
assertRed(rendered)
} finally {
rendered.recycle()
}
val loaded = loader.load(16, 16)
assertNotNull(loaded)
checkNotNull(loaded)
try {
assertEquals(16, loaded.width)
assertEquals(16, loaded.height)
assertRed(loaded)
} finally {
loaded.recycle()
}
}
@Test fun wrongOrMissingPassphraseFailsBothPaths() {
store.setPassphrase(wrongPassphrase)
assertThrows(IncorrectPassphraseException::class.java) {
runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
}
assertNull(loader.load(16, 16))
store.clearPassphrase()
assertThrows(MissingPassphraseException::class.java) {
runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
}
assertNull(loader.load(16, 16))
}
private fun assertRed(bitmap: Bitmap) {
val pixel = bitmap.getPixel(bitmap.width / 2, bitmap.height / 2)
assertTrue(Color.red(pixel) > 180)
assertTrue(Color.green(pixel) < 70)
assertTrue(Color.blue(pixel) < 80)
}
}
internal fun encryptTestJpeg(jpeg: ByteArray, passphrase: String): ByteArray {
val salt = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7)
val spec = PBEKeySpec(passphrase.toCharArray(), salt, 10_000, 384)
val material = try {
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
return try {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(material, 0, 32, "AES"), IvParameterSpec(material, 32, 16))
"Salted__".toByteArray(Charsets.US_ASCII) + salt + cipher.doFinal(jpeg)
} finally {
material.fill(0)
}
}
@@ -28,6 +28,7 @@ import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
import com.anthonyla.paperize.presentation.screens.album_view.components.AlbumViewTopBar
import kotlinx.coroutines.CompletableDeferred
import androidx.compose.ui.semantics.SemanticsActions
import com.anthonyla.paperize.core.WallpaperMode
@@ -56,7 +57,7 @@ class AlbumUiInstrumentedTest {
onToggleChanger = {}, onSelectAlbum = { _, _ -> },
onUpdateScheduleSettings = { latest = it },
onUpdateScheduleSettingsDebounced = { latest = it },
onChangeWallpaperNow = {}, homeWallpaperUri = null, lockWallpaperUri = null
onChangeWallpaperNow = {}, homeWallpaper = null, lockWallpaper = null, onRemoveWallpaper = {}
)
}
}
@@ -92,8 +93,9 @@ class AlbumUiInstrumentedTest {
var attempts = 0
compose.setContent {
PaperizeTheme(false, false) {
LibraryScreen(emptyList(), {}, { name ->
LibraryScreen(emptyList(), {}, { name, encrypted ->
assertEquals("Mountains", name)
assertTrue(encrypted)
attempts++
if (attempts == 1) pending.await() else null
})
@@ -101,6 +103,7 @@ class AlbumUiInstrumentedTest {
}
compose.onNodeWithContentDescription(context.getString(R.string.add_album)).performClick()
compose.onNodeWithText(context.getString(R.string.album_name)).performTextInput("Mountains")
compose.onNodeWithText(context.getString(R.string.encrypted_album)).performClick()
compose.onNodeWithText(context.getString(R.string.save)).performClick().assertIsNotEnabled()
compose.runOnIdle { pending.complete(R.string.album_create_failed) }
compose.onNodeWithText(context.getString(R.string.album_create_failed)).assertIsDisplayed()
@@ -110,6 +113,33 @@ class AlbumUiInstrumentedTest {
compose.runOnIdle { assertEquals(2, attempts) }
}
@Test fun albumOptionsExposeActionsAndDisableRescanWithoutFolders() {
val hasFolders = mutableStateOf(false)
var action = ""
compose.setContent {
PaperizeTheme(false, false) {
AlbumViewTopBar(
title = "Album", isSelectionMode = false, selectedCount = 0, allSelected = false,
onBackClick = {}, onSortClick = {}, onDeleteAlbum = { action = "delete" },
onRenameAlbum = { action = "rename" }, onFilterAlbum = null, onRefreshFolders = { action = "refresh" },
albumActionsEnabled = true, hasFolders = hasFolders.value,
onSelectAll = {}, onDeleteSelected = {}, onClearSelection = {}
)
}
}
fun openMenu() = compose.onNodeWithContentDescription(context.getString(R.string.album_menu)).performClick()
openMenu()
compose.onNodeWithText(context.getString(R.string.refresh_album_folders)).assertIsNotEnabled()
compose.onNodeWithText(context.getString(R.string.rename_album)).performClick()
compose.runOnIdle { assertEquals("rename", action); hasFolders.value = true }
openMenu()
compose.onNodeWithText(context.getString(R.string.refresh_album_folders)).performClick()
compose.runOnIdle { assertEquals("refresh", action) }
openMenu()
compose.onNodeWithText(context.getString(R.string.delete_album)).performClick()
compose.runOnIdle { assertEquals("delete", action) }
}
@Test fun sortSheetExposesCurrentSelectionAndAppliesNewChoice() {
var chosen: SortOption? = null
var dismissed = false
@@ -0,0 +1,94 @@
package com.anthonyla.paperize.presentation
import android.content.ContextWrapper
import android.graphics.Bitmap
import android.net.Uri
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import coil3.request.CachePolicy
import coil3.request.ImageRequest
import com.anthonyla.paperize.data.source.EncryptedImageStore
import com.anthonyla.paperize.data.source.encryptTestJpeg
import com.anthonyla.paperize.presentation.common.components.encryptedPreviewImageRequest
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.UUID
import java.util.concurrent.atomic.AtomicReference
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class EncryptedPreviewInstrumentedTest {
@get:Rule val compose = createComposeRule()
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val directory = File(instrumentation.targetContext.cacheDir, "encrypted-preview-${UUID.randomUUID()}")
private val context = object : ContextWrapper(instrumentation.targetContext) {
override fun getNoBackupFilesDir(): File = directory
}
private val image = File(directory, "image.jpg_enc")
private val store = EncryptedImageStore(context)
@Before fun setup() {
check(directory.mkdirs())
val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)
val jpeg = try {
ByteArrayOutputStream().use { output ->
check(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output))
output.toByteArray()
}
} finally {
bitmap.recycle()
}
image.writeBytes(encryptTestJpeg(jpeg, "test"))
store.setPassphrase("test")
}
@After fun cleanup() {
directory.deleteRecursively()
}
@Test fun disablingPreviewsDropsTheDecryptedRequestAndNeverCachesIt() {
val enabled = mutableStateOf(true)
val request = AtomicReference<ImageRequest?>()
compose.setContent {
CompositionLocalProvider(LocalContext provides context) {
val value = encryptedPreviewImageRequest(
Uri.fromFile(image).toString(), 32, 32, false, enabled.value, store
)
SideEffect { request.set(value) }
}
}
compose.waitUntil(20_000) { request.get() != null }
val decrypted = checkNotNull(request.get())
assertTrue(decrypted.data is Bitmap)
assertEquals(CachePolicy.DISABLED, decrypted.memoryCachePolicy)
assertEquals(CachePolicy.DISABLED, decrypted.diskCachePolicy)
compose.runOnIdle { enabled.value = false }
compose.waitUntil(20_000) { request.get() == null }
compose.runOnIdle { enabled.value = true }
compose.waitUntil(20_000) { request.get() != null }
}
@Test fun missingDocumentMetadataStillLoadsTheOriginalUri() {
val uri = Uri.parse("content://missing.provider/image")
val request = AtomicReference<ImageRequest?>()
compose.setContent {
CompositionLocalProvider(LocalContext provides context) {
val value = encryptedPreviewImageRequest(uri.toString(), 32, 32, false, false, store)
SideEffect { request.set(value) }
}
}
compose.waitUntil(20_000) { request.get() != null }
assertEquals(uri, checkNotNull(request.get()).data)
}
}
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.service.livewallpaper.renderer
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.opengl.EGL14
import android.opengl.EGLConfig
@@ -171,6 +172,72 @@ class LiveWallpaperShaderInstrumentedTest {
}
}
@Test
fun blurredFitBackgroundFillsTheBarsTheRightWayUpWithAndWithoutBlur() {
val app = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
val uploads = java.util.concurrent.LinkedBlockingQueue<() -> Unit>()
val renderer = PaperizeWallpaperRenderer(app, object : PaperizeWallpaperRenderer.Callbacks {
override fun queueEventOnGlThread(event: () -> Unit): Boolean = uploads.offer(event)
override fun requestRender() = Unit
})
val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
val gl = egl.eglGetCurrentContext().gl as javax.microedition.khronos.opengles.GL10
val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
.chooseConfig(egl, egl.eglGetCurrentDisplay())
val file = java.io.File.createTempFile("fit-backdrop", ".png", app.cacheDir)
try {
// Wide image, red over blue, so Fit leaves bars above and below it.
val bitmap = Bitmap.createBitmap(SIZE * 2, SIZE, Bitmap.Config.ARGB_8888).apply {
eraseColor(Color.BLUE)
Canvas(this).drawRect(0f, 0f, SIZE * 2f, SIZE / 2f, android.graphics.Paint().apply { color = Color.RED })
}
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
bitmap.recycle()
renderer.onSurfaceCreated(gl, config)
renderer.onSurfaceChanged(gl, SIZE, SIZE)
renderer.updateScalingType(com.anthonyla.paperize.core.ScalingType.FIT)
renderer.queueWallpaper(
ContentUriImageLoader(
app.contentResolver,
android.net.Uri.fromFile(file),
com.anthonyla.paperize.core.ScalingType.FIT
),
skipCrossfade = true
)
checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
renderer.onDrawFrame(gl)
assertEquals(Color.BLACK, readPixel(SIZE / 2, SIZE - 2))
renderer.updateBlurFitBackground(true)
renderer.onDrawFrame(gl)
assertTopRedBottomBlue()
renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(enableBlur = true, blurPercentage = 10))
renderer.onDrawFrame(gl)
assertTopRedBottomBlue()
// A vignette over the whole screen leaves no seam where the picture meets the backdrop.
renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(enableVignette = true, vignettePercentage = 100))
renderer.onDrawFrame(gl)
val inside = Color.red(readPixel(SIZE / 2, SIZE * 3 / 4 - 1))
val outside = Color.red(readPixel(SIZE / 2, SIZE * 3 / 4 + 1))
assertTrue("inside=$inside outside=$outside", kotlin.math.abs(inside - outside) <= 20)
GLUtil.checkGLError("blurred fit background")
} finally {
renderer.cancelLoading()
file.delete()
}
}
// glReadPixels counts rows from the bottom of the surface.
private fun assertTopRedBottomBlue() {
val top = readPixel(SIZE / 2, SIZE - 2)
val bottom = readPixel(SIZE / 2, 1)
assertTrue("Top bar ${Integer.toHexString(top)}", Color.red(top) > 200 && Color.blue(top) < 50)
assertTrue("Bottom bar ${Integer.toHexString(bottom)}", Color.blue(bottom) > 200 && Color.red(bottom) < 50)
}
@Test
fun liveColorEffectsChangeRenderedPixels() {
val sourceColor = Color.rgb(200, 100, 40)
@@ -228,6 +295,48 @@ class LiveWallpaperShaderInstrumentedTest {
}
}
@Test
fun liveBlurSpreadsAnEdgeAsFarAsStaticBlur() {
val app = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
val uploads = java.util.concurrent.LinkedBlockingQueue<() -> Unit>()
val renderer = PaperizeWallpaperRenderer(app, object : PaperizeWallpaperRenderer.Callbacks {
override fun queueEventOnGlThread(event: () -> Unit): Boolean = uploads.offer(event)
override fun requestRender() = Unit
})
val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
val gl = egl.eglGetCurrentContext().gl as javax.microedition.khronos.opengles.GL10
val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
.chooseConfig(egl, egl.eglGetCurrentDisplay())
val file = java.io.File.createTempFile("blur-edge", ".png", app.cacheDir)
val static = com.anthonyla.paperize.core.util.processBitmap(
boundaryBitmap(horizontalBoundary = true), enableBlur = true, blurPercent = 100
)
try {
val edge = boundaryBitmap(horizontalBoundary = true)
file.outputStream().use { edge.compress(Bitmap.CompressFormat.PNG, 100, it) }
edge.recycle()
renderer.onSurfaceCreated(gl, config)
renderer.onSurfaceChanged(gl, SIZE, SIZE)
renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(enableBlur = true, blurPercentage = 100))
renderer.queueWallpaper(
ContentUriImageLoader(app.contentResolver, android.net.Uri.fromFile(file)),
skipCrossfade = true
)
checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
renderer.onDrawFrame(gl)
for (x in listOf(20, 24, 28, 36, 40, 44)) {
val live = Color.red(readPixel(x, SIZE / 2))
val expected = Color.red(static.getPixel(x, SIZE / 2))
assertTrue("x=$x live=$live static=$expected", kotlin.math.abs(live - expected) <= 16)
}
} finally {
renderer.cancelLoading()
static.recycle()
file.delete()
}
}
private fun drawEffects(
program: Int,
texture: Int,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 108 108">
<rect width="108" height="108" fill="#ffd9e2"/>
<path d="M68.25 36.59L77.37 42.74A5.5 5.5 0 0 1 78.85 50.38L65.01 70.9L64.68 70.08L68.2 36.56A5.5 5.5 0 0 1 68.25 36.59Z" fill="#e03a72"/>
<path d="M49.61 32.64L60.55 33.79A5.5 5.5 0 0 1 65.44 39.83L62.76 65.34L49.55 32.63A5.5 5.5 0 0 1 49.61 32.64Z" fill="#c2255c"/>
<path d="M31.29 37.9L41.49 33.78A5.5 5.5 0 0 1 48.65 36.82L61.01 67.42A5.5 5.5 0 0 1 57.97 74.58L47.77 78.7A5.5 5.5 0 0 1 40.61 75.66L28.25 45.06A5.5 5.5 0 0 1 31.29 37.9Z" fill="#000000"/>
</svg>

After

Width:  |  Height:  |  Size: 584 B

@@ -2,7 +2,7 @@ package com.anthonyla.paperize.core.constants
object Constants {
const val DATABASE_NAME = "paperize_database"
const val DATABASE_VERSION = 4
const val DATABASE_VERSION = 7
const val PREFERENCES_NAME = "paperize_preferences"
@@ -25,7 +25,6 @@ object Constants {
const val DEFAULT_GRAYSCALE_PERCENTAGE = 0
const val MAX_EFFECT_PERCENTAGE = 100
const val SLIDER_EFFECT_STEPS = 99
const val DIALOG_MESSAGE_MAX_LINES = 10
const val MIN_EFFECT_PERCENTAGE = 0
const val MIN_LIVE_INTERVAL_MINUTES = 1
@@ -44,6 +43,8 @@ object Constants {
const val PREVIEW_THUMBNAIL_HEIGHT = 1200
const val MAX_BLUR_RADIUS = 25.0f
const val BACKDROP_MAX_SIZE = 64
const val BACKDROP_BLUR_PERCENT = 25
const val BRIGHTNESS_SAMPLE_SIZE = 10
// ITU-R BT.709
@@ -11,7 +11,7 @@ object BatteryOptimizationUtil {
private const val TAG = "BatteryOptimizationUtil"
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val powerManager = context.getSystemService(PowerManager::class.java)
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
}
@@ -2,23 +2,14 @@ package com.anthonyla.paperize.core.util
import android.content.ContentResolver
import android.net.Uri
import android.provider.OpenableColumns
import java.util.UUID
fun Uri.isValid(contentResolver: ContentResolver): Boolean {
if (scheme != "content") return false
fun Uri.isReadable(contentResolver: ContentResolver): Boolean {
if (scheme != ContentResolver.SCHEME_CONTENT) return false
return try {
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
cursor.moveToFirst()
} ?: false
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
} catch (_: Exception) {
// Fallback to opening the stream if the provider doesn't support the specific query
try {
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
} catch (_: Exception) {
false
}
false
}
}
@@ -11,4 +11,10 @@ object QueueBuilder {
val newWallpaperIds = allWallpaperIds.filter { it !in existingSet }
return existingValid + newWallpaperIds.shuffled()
}
/** Ids before [pickedId] are left out: the ordered rebuild of an empty queue starts at the first item. */
fun idsAfter(orderedIds: List<String>, pickedId: String): List<String> {
val index = orderedIds.indexOf(pickedId)
return if (index < 0) orderedIds else orderedIds.subList(index + 1, orderedIds.size).toList()
}
}
@@ -1,7 +1,6 @@
package com.anthonyla.paperize.core.util
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
import androidx.core.graphics.createBitmap
import android.graphics.Canvas
@@ -41,7 +40,7 @@ private const val BUILT_IN_DISPLAY_CATEGORY =
"android.hardware.display.category.BUILT_IN_DISPLAYS"
fun getDeviceScreenSize(context: Context): Size {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val windowManager = context.getSystemService(WindowManager::class.java)
val metrics: WindowMetrics = windowManager.currentWindowMetrics
val currentWindow = metrics.bounds.width() to metrics.bounds.height()
@@ -117,11 +116,13 @@ fun retrieveBitmap(
width: Int,
height: Int,
scaling: ScalingType = ScalingType.FIT,
preserveSourceOverflow: Boolean = false
preserveSourceOverflow: Boolean = false,
blurFitBackground: Boolean = false,
imageSource: ImageDecoder.Source? = null
): Bitmap? {
// ImageDecoder applies EXIF orientation and reports dimensions after it.
val bitmap = try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
val source = imageSource ?: ImageDecoder.createSource(context.contentResolver, wallpaperUri)
ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
val (targetW, targetH) = calculateDecodeSize(
info.size.width, info.size.height, width, height, scaling
@@ -153,7 +154,7 @@ fun retrieveBitmap(
if (preserveSourceOverflow && scaling == ScalingType.FILL) {
scaleToFillPreservingOverflow(it, width, height)
} else {
finalizeToCanvas(it, width, height, scaling)
finalizeToCanvas(it, width, height, scaling, blurFitBackground)
}
}
}
@@ -183,28 +184,61 @@ private fun scaleToFillPreservingOverflow(
}
/** Render the decoded bitmap onto the requested canvas; consumes [source]. */
internal fun finalizeToCanvas(source: Bitmap, canvasW: Int, canvasH: Int, scaling: ScalingType): Bitmap {
internal fun finalizeToCanvas(
source: Bitmap,
canvasW: Int,
canvasH: Int,
scaling: ScalingType,
blurFitBackground: Boolean = false
): 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
fun centered(width: Float, height: Float) =
RectF((canvasW - width) / 2f, (canvasH - height) / 2f, (canvasW + width) / 2f, (canvasH + height) / 2f)
fun scaled(bitmap: Bitmap, mode: ScalingType): RectF {
if (mode == ScalingType.STRETCH) return centered(canvasW.toFloat(), canvasH.toFloat())
val widthRatio = canvasW.toFloat() / bitmap.width
val heightRatio = canvasH.toFloat() / bitmap.height
val scale = when (mode) {
ScalingType.FILL -> maxOf(widthRatio, heightRatio)
ScalingType.FIT -> minOf(widthRatio, heightRatio)
ScalingType.NONE, ScalingType.STRETCH -> 1f
}
return centered(bitmap.width * scale, bitmap.height * scale)
}
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)
val paint = Paint(Paint.FILTER_BITMAP_FLAG)
Canvas(result).apply {
drawColor(Color.BLACK)
drawBitmap(source, null, RectF(left, top, left + width, top + height), Paint(Paint.FILTER_BITMAP_FLAG))
if (scaling == ScalingType.FIT && blurFitBackground) {
val backdrop = createBlurredBackdrop(source)
drawBitmap(backdrop, null, scaled(backdrop, ScalingType.FILL), paint)
backdrop.recycle()
} else {
drawColor(Color.BLACK)
}
drawBitmap(source, null, scaled(source, scaling), paint)
}
source.recycle()
return result
}
/**
* A blurred copy of [source] at most [Constants.BACKDROP_MAX_SIZE] pixels across, meant to be
* stretched over the screen. Halving step by step averages every pixel; a single large downscale
* samples only a few and turns detailed images into noise.
*/
fun createBlurredBackdrop(source: Bitmap): Bitmap {
var small = source
while (maxOf(small.width, small.height) > Constants.BACKDROP_MAX_SIZE) {
val half = small.scale(maxOf(1, small.width / 2), maxOf(1, small.height / 2))
if (small !== source) small.recycle()
small = half
}
if (small === source) small = source.copy(Bitmap.Config.ARGB_8888, false)
val blurred = processBitmap(small, enableBlur = true, blurPercent = Constants.BACKDROP_BLUR_PERCENT)
if (blurred !== small) small.recycle()
return blurred
}
private fun drawVignette(canvas: Canvas, width: Int, height: Int, percent: Int) {
val centerX = width / 2f
val centerY = height / 2f
@@ -245,9 +279,7 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
}
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)
return BrightnessCalculator.getAdaptiveMultiplier(context.resources.configuration.isNightModeActive, brightness)
}
fun adaptiveBrightnessAdjustment(context: Context, source: Bitmap): Bitmap {
@@ -4,7 +4,7 @@ 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 ->
val LIBRARY_MIGRATIONS: Array<Migration> = (1..3).map<Int, Migration> { version ->
object : Migration(version, 4) {
override fun migrate(db: SupportSQLiteDatabase) {
// Rebuilding the parent table would cascade-delete these rows; preserve them first.
@@ -39,4 +39,24 @@ val LIBRARY_MIGRATIONS: Array<Migration> = (1..3).map { version ->
}
}
}
}.toTypedArray()
}.toTypedArray() + object : Migration(5, 6) {
override fun migrate(db: SupportSQLiteDatabase) {
val hasEncryptionColumn = db.query("PRAGMA table_info(`albums`)").use { cursor ->
val nameColumn = cursor.getColumnIndexOrThrow("name")
var found = false
while (cursor.moveToNext()) {
if (cursor.getString(nameColumn) == "isEncrypted") {
found = true
break
}
}
found
}
if (!hasEncryptionColumn) {
db.execSQL("ALTER TABLE `albums` ADD COLUMN `isEncrypted` INTEGER NOT NULL DEFAULT 0")
}
db.execSQL(
"CREATE TABLE IF NOT EXISTS `excluded_wallpapers` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE)"
)
}
}
@@ -1,13 +1,16 @@
package com.anthonyla.paperize.data.database
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.RoomDatabase
import com.anthonyla.paperize.data.database.dao.AlbumDao
import com.anthonyla.paperize.data.database.dao.ExcludedWallpaperDao
import com.anthonyla.paperize.data.database.dao.FolderDao
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
import com.anthonyla.paperize.data.database.dao.WallpaperDao
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.ExcludedWallpaperEntity
import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
@@ -20,10 +23,12 @@ import com.anthonyla.paperize.core.constants.Constants
WallpaperEntity::class,
FolderEntity::class,
WallpaperQueueEntity::class,
WallpaperCurrentEntity::class
WallpaperCurrentEntity::class,
ExcludedWallpaperEntity::class
],
version = Constants.DATABASE_VERSION,
exportSchema = true
exportSchema = true,
autoMigrations = [AutoMigration(from = 4, to = 5), AutoMigration(from = 6, to = 7)]
)
abstract class PaperizeDatabase : RoomDatabase() {
abstract fun albumDao(): AlbumDao
@@ -31,4 +36,5 @@ abstract class PaperizeDatabase : RoomDatabase() {
abstract fun folderDao(): FolderDao
abstract fun wallpaperQueueDao(): WallpaperQueueDao
abstract fun wallpaperCurrentDao(): WallpaperCurrentDao
abstract fun excludedWallpaperDao(): ExcludedWallpaperDao
}
@@ -39,6 +39,12 @@ interface AlbumDao {
@Query("DELETE FROM albums WHERE id = :albumId")
suspend fun deleteAlbumById(albumId: String)
@Query("UPDATE albums SET name = :name, modifiedAt = :modifiedAt WHERE id = :albumId")
suspend fun renameAlbum(albumId: String, name: String, modifiedAt: Long): Int
@Query("UPDATE albums SET filter = :filter, modifiedAt = :modifiedAt WHERE id = :albumId")
suspend fun setFilter(albumId: String, filter: String?, modifiedAt: Long): Int
@Query("UPDATE albums SET coverUri = :coverUri, modifiedAt = :modifiedAt WHERE id = :albumId")
suspend fun updateAlbumCover(albumId: String, coverUri: String?, modifiedAt: Long)
@@ -0,0 +1,19 @@
package com.anthonyla.paperize.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.anthonyla.paperize.data.database.entities.ExcludedWallpaperEntity
@Dao
interface ExcludedWallpaperDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(entity: ExcludedWallpaperEntity)
@Query("SELECT uri FROM excluded_wallpapers WHERE folderId = :folderId")
suspend fun getUris(folderId: String): List<String>
@Query("DELETE FROM excluded_wallpapers WHERE folderId = :folderId AND uri IN (:uris)")
suspend fun deleteUris(folderId: String, uris: List<String>)
}
@@ -14,6 +14,9 @@ interface WallpaperDao {
@Query("SELECT uri FROM wallpapers WHERE albumId = :albumId AND folderId IS :folderId")
suspend fun getUrisInCollection(albumId: String, folderId: String?): List<String>
@Query("DELETE FROM wallpapers WHERE albumId = :albumId AND folderId = :folderId AND uri IN (:uris)")
suspend fun deleteFolderWallpapersByUris(albumId: String, folderId: String, uris: List<String>): Int
@Query("SELECT COALESCE(MAX(displayOrder), -1) FROM wallpapers WHERE albumId = :albumId")
suspend fun getMaxOrder(albumId: String): Int
@@ -32,6 +35,9 @@ interface WallpaperDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertWallpapers(wallpapers: List<WallpaperEntity>)
@Query("SELECT * FROM wallpapers WHERE folderId = :folderId")
suspend fun getFolderWallpapers(folderId: String): List<WallpaperEntity>
@Query("SELECT id FROM wallpapers WHERE albumId = :albumId")
suspend fun getWallpaperIdsByAlbum(albumId: String): List<String>
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.data.database.entities
import androidx.room.Entity
import androidx.room.ColumnInfo
import androidx.room.PrimaryKey
@Entity(tableName = "albums")
@@ -10,5 +11,7 @@ data class AlbumEntity(
val name: String,
val coverUri: String?,
val createdAt: Long = System.currentTimeMillis(),
val modifiedAt: Long = System.currentTimeMillis()
val modifiedAt: Long = System.currentTimeMillis(),
@ColumnInfo(defaultValue = "0") val isEncrypted: Boolean = false,
val filter: String? = null
)
@@ -0,0 +1,27 @@
package com.anthonyla.paperize.data.database.entities
import androidx.room.Entity
import androidx.room.ForeignKey
/** A folder image the user removed, so folder rescans skip it. Keeps the row to restore it as it was. */
@Entity(
tableName = "excluded_wallpapers",
primaryKeys = ["folderId", "uri"],
foreignKeys = [
ForeignKey(
entity = FolderEntity::class,
parentColumns = ["id"],
childColumns = ["folderId"],
onDelete = ForeignKey.CASCADE
)
]
)
data class ExcludedWallpaperEntity(
val folderId: String,
val uri: String,
val id: String,
val fileName: String,
val dateModified: Long,
val displayOrder: Int,
val addedAt: Long
)
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.data.database.relations
import androidx.room.Embedded
import androidx.room.Relation
import com.anthonyla.paperize.data.database.entities.ExcludedWallpaperEntity
import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
@@ -14,5 +15,12 @@ data class FolderWithWallpapers(
entityColumn = "folderId",
entity = WallpaperEntity::class
)
val wallpapers: List<WallpaperEntity> = emptyList()
val wallpapers: List<WallpaperEntity> = emptyList(),
@Relation(
parentColumn = "id",
entityColumn = "folderId",
entity = ExcludedWallpaperEntity::class
)
val excluded: List<ExcludedWallpaperEntity> = emptyList()
)
@@ -18,7 +18,9 @@ fun AlbumEntity.toDomainModel(
wallpapers = wallpapers,
folders = folders,
createdAt = createdAt,
modifiedAt = modifiedAt
modifiedAt = modifiedAt,
isEncrypted = isEncrypted,
filter = filter
)
fun Album.toEntity(): AlbumEntity = AlbumEntity(
@@ -26,7 +28,9 @@ fun Album.toEntity(): AlbumEntity = AlbumEntity(
name = name,
coverUri = coverUri,
createdAt = createdAt,
modifiedAt = modifiedAt
modifiedAt = modifiedAt,
isEncrypted = isEncrypted,
filter = filter
)
fun AlbumWithDetails.toDomainModel(): Album {
@@ -6,7 +6,8 @@ import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
fun FolderEntity.toDomainModel(
wallpapers: List<Wallpaper> = emptyList()
wallpapers: List<Wallpaper> = emptyList(),
removedWallpapers: List<Wallpaper> = emptyList()
): Folder = Folder(
id = id,
albumId = albumId,
@@ -16,6 +17,7 @@ fun FolderEntity.toDomainModel(
dateModified = dateModified,
displayOrder = displayOrder,
wallpapers = wallpapers,
removedWallpapers = removedWallpapers,
addedAt = addedAt
)
@@ -31,5 +33,6 @@ fun Folder.toEntity(): FolderEntity = FolderEntity(
)
fun FolderWithWallpapers.toDomainModel(): Folder = folder.toDomainModel(
wallpapers = wallpapers.map { it.toDomainModel() }
wallpapers = wallpapers.map { it.toDomainModel() },
removedWallpapers = excluded.map { it.toDomainModel(folder.albumId) }
)
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.data.mapper
import com.anthonyla.paperize.data.database.entities.ExcludedWallpaperEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
import com.anthonyla.paperize.domain.model.Wallpaper
@@ -25,3 +26,24 @@ fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
sourceType = if (folderId == null) "DIRECT" else "FOLDER",
addedAt = addedAt
)
fun ExcludedWallpaperEntity.toDomainModel(albumId: String): Wallpaper = Wallpaper(
id = id,
albumId = albumId,
folderId = folderId,
uri = uri,
fileName = fileName,
dateModified = dateModified,
displayOrder = displayOrder,
addedAt = addedAt
)
fun Wallpaper.toExcludedEntity(folderId: String): ExcludedWallpaperEntity = ExcludedWallpaperEntity(
folderId = folderId,
uri = uri,
id = id,
fileName = fileName,
dateModified = dateModified,
displayOrder = displayOrder,
addedAt = addedAt
)
@@ -5,6 +5,7 @@ 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.data.mapper.toExcludedEntity
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.domain.model.Folder
@@ -14,6 +15,7 @@ import com.anthonyla.paperize.domain.source.DocumentSource
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
@Singleton
@@ -24,6 +26,7 @@ class AlbumRepositoryImpl @Inject constructor(
private val albumDao = database.albumDao()
private val wallpaperDao = database.wallpaperDao()
private val folderDao = database.folderDao()
private val excludedDao = database.excludedWallpaperDao()
companion object {
private const val WALLPAPER_BATCH_SIZE = 500
@@ -35,12 +38,15 @@ class AlbumRepositoryImpl @Inject constructor(
override fun getAlbumById(albumId: String): Flow<Album?> =
albumDao.getAlbumWithDetails(albumId).map { it?.toDomainModel() }
override suspend fun getAlbumEncryption(albumId: String): Boolean? =
albumDao.getAlbumById(albumId)?.isEncrypted
override fun getFolderById(folderId: String): Flow<Folder?> =
folderDao.getFolderWithWallpapers(folderId).map { it?.toDomainModel() }
override suspend fun createAlbum(name: String, coverUri: String?): Album {
override suspend fun createAlbum(name: String, coverUri: String?, isEncrypted: Boolean): Album {
val now = System.currentTimeMillis()
val album = Album(id = generateId(), name = name, coverUri = coverUri, createdAt = now, modifiedAt = now)
val album = Album(id = generateId(), name = name, coverUri = coverUri, createdAt = now, modifiedAt = now, isEncrypted = isEncrypted)
albumDao.insertAlbum(album.toEntity())
return album
}
@@ -49,6 +55,19 @@ class AlbumRepositoryImpl @Inject constructor(
albumDao.deleteAlbumById(albumId)
}
override suspend fun renameAlbum(albumId: String, name: String): Boolean = database.withTransaction {
if (albumDao.getAlbumSummaries().first().any { it.id != albumId && it.name.equals(name, ignoreCase = true) }) {
return@withTransaction false
}
check(albumDao.renameAlbum(albumId, name, System.currentTimeMillis()) == 1)
true
}
override suspend fun setAlbumFilter(albumId: String, filter: String?) = database.withTransaction {
check(albumDao.setFilter(albumId, filter?.takeIf { it.isNotBlank() }, System.currentTimeMillis()) == 1)
database.wallpaperQueueDao().clearAllQueues(albumId)
}
override suspend fun addWallpapersToAlbum(
albumId: String,
wallpapers: List<Wallpaper>,
@@ -73,6 +92,34 @@ class AlbumRepositoryImpl @Inject constructor(
true
}
override suspend fun syncFolderWallpapers(
albumId: String,
folderId: String,
wallpapers: List<Wallpaper>,
onProgress: (Int, Int) -> Unit
): Int = database.withTransaction {
checkNotNull(albumDao.getAlbumById(albumId))
val scanned = wallpapers.mapTo(HashSet()) { it.uri }
// An empty scan can be an unavailable provider, so it removes nothing.
val stale = if (scanned.isEmpty()) emptyList()
else wallpaperDao.getUrisInCollection(albumId, folderId).filterNot { it in scanned }
val excluded = excludedDao.getUris(folderId).toHashSet()
if (scanned.isNotEmpty()) excluded.filterNot { it in scanned }.chunked(WALLPAPER_BATCH_SIZE).forEach {
excludedDao.deleteUris(folderId, it)
}
var removed = 0
stale.chunked(WALLPAPER_BATCH_SIZE).forEach {
removed += wallpaperDao.deleteFolderWallpapersByUris(albumId, folderId, it)
}
val added = insertNewWallpapers(albumId, wallpapers.filterNot { it.uri in excluded }, onProgress)
if (removed > 0) {
folderDao.updateFolderCover(folderId, wallpaperDao.getFolderCoverUri(folderId))
updateAlbumCoverIfNeeded(albumId)
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
}
added
}
private suspend fun insertNewWallpapers(
albumId: String,
wallpapers: List<Wallpaper>,
@@ -130,6 +177,26 @@ class AlbumRepositoryImpl @Inject constructor(
}
}
override suspend fun removeWallpaper(wallpaperId: String): Wallpaper? = database.withTransaction {
val wallpaper = wallpaperDao.getWallpaperById(wallpaperId)?.toDomainModel() ?: return@withTransaction null
wallpaper.folderId?.let { excludedDao.insert(wallpaper.toExcludedEntity(it)) }
removeWallpapersFromAlbum(wallpaper.albumId, listOf(wallpaperId))
wallpaper
}
override suspend fun restoreWallpaper(wallpaper: Wallpaper) = database.withTransaction {
val albumId = wallpaper.albumId
val folderId = wallpaper.folderId
if (folderId != null) excludedDao.deleteUris(folderId, listOf(wallpaper.uri))
// The same image can be imported again before an undo.
if (wallpaper.uri in wallpaperDao.getUrisInCollection(albumId, folderId)) return@withTransaction
wallpaperDao.insertWallpapers(listOf(wallpaper.toEntity()))
database.wallpaperQueueDao().clearAllQueues(albumId)
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
folderDao.refreshFolderCovers(albumId)
updateAlbumCoverIfNeeded(albumId)
}
override suspend fun removeFolderFromAlbum(albumId: String, folderId: String) {
database.withTransaction {
folderDao.deleteAlbumFolder(albumId, folderId)
@@ -31,6 +31,7 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
private val DARK_MODE = booleanPreferencesKey("dark_mode")
private val DYNAMIC_THEMING = booleanPreferencesKey("dynamic_theming")
private val ANIMATE = booleanPreferencesKey("animate")
private val ENCRYPTED_PREVIEWS = booleanPreferencesKey("encrypted_previews")
private val FIRST_LAUNCH = booleanPreferencesKey("first_launch")
private val WALLPAPER_MODE = stringPreferencesKey("wallpaper_mode")
private val ENABLE_CHANGER = booleanPreferencesKey("enable_changer")
@@ -48,6 +49,7 @@ private val HOME_SCALING_TYPE = stringPreferencesKey("home_scaling_type")
private val LOCK_SCALING_TYPE = stringPreferencesKey("lock_scaling_type")
private val LIVE_SCALING_TYPE = stringPreferencesKey("live_scaling_type")
private val HOME_SCROLLING_ENABLED = booleanPreferencesKey("home_scrolling_enabled")
private val BLUR_FIT_BACKGROUND = booleanPreferencesKey("blur_fit_background")
private val ADAPTIVE_BRIGHTNESS = booleanPreferencesKey("adaptive_brightness")
/** Effect keys are "<screen>_<field>", e.g. "home_enable_blur" or "live_parallax_intensity". */
@@ -84,7 +86,8 @@ class SettingsRepositoryImpl @Inject constructor(
darkMode = prefs[DARK_MODE],
dynamicTheming = prefs[DYNAMIC_THEMING] ?: defaults.dynamicTheming,
animate = prefs[ANIMATE] ?: defaults.animate,
firstLaunch = prefs[FIRST_LAUNCH] ?: defaults.firstLaunch
firstLaunch = prefs[FIRST_LAUNCH] ?: defaults.firstLaunch,
encryptedPreviews = prefs[ENCRYPTED_PREVIEWS] ?: defaults.encryptedPreviews
)
}
@@ -123,6 +126,7 @@ class SettingsRepositoryImpl @Inject constructor(
prefs[LOCK_SCALING_TYPE] = settings.lockScalingType.name
prefs[LIVE_SCALING_TYPE] = settings.liveScalingType.name
prefs[HOME_SCROLLING_ENABLED] = settings.homeScrollingEnabled
prefs[BLUR_FIT_BACKGROUND] = settings.blurFitBackground
prefs.writeEffects(HOME_EFFECTS, settings.homeEffects)
prefs.writeEffects(LOCK_EFFECTS, settings.lockEffects)
prefs.writeEffects(LIVE_EFFECTS, settings.liveEffects)
@@ -173,6 +177,10 @@ class SettingsRepositoryImpl @Inject constructor(
dataStore.edit { it[ANIMATE] = enabled }
}
override suspend fun updateEncryptedPreviews(enabled: Boolean) {
dataStore.edit { it[ENCRYPTED_PREVIEWS] = enabled }
}
override suspend fun completeFirstLaunch() {
dataStore.edit { it[FIRST_LAUNCH] = false }
}
@@ -199,6 +207,7 @@ class SettingsRepositoryImpl @Inject constructor(
lockScalingType = ScalingType.fromString(prefs[LOCK_SCALING_TYPE]),
liveScalingType = ScalingType.fromString(prefs[LIVE_SCALING_TYPE]),
homeScrollingEnabled = prefs[HOME_SCROLLING_ENABLED] ?: defaults.homeScrollingEnabled,
blurFitBackground = prefs[BLUR_FIT_BACKGROUND] ?: defaults.blurFitBackground,
homeEffects = prefs.readEffects(HOME_EFFECTS),
lockEffects = prefs.readEffects(LOCK_EFFECTS),
liveEffects = prefs.readEffects(LIVE_EFFECTS),
@@ -7,7 +7,11 @@ 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.data.source.EncryptedImageStore
import com.anthonyla.paperize.domain.repository.WallpaperRepository
import com.anthonyla.paperize.domain.source.DocumentSource
import com.anthonyla.paperize.domain.source.albumFilterRegex
import com.anthonyla.paperize.domain.source.matchingNamingTableFiles
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
@@ -16,7 +20,9 @@ import kotlinx.coroutines.flow.map
@Singleton
class WallpaperRepositoryImpl @Inject constructor(
private val database: PaperizeDatabase
private val database: PaperizeDatabase,
private val documents: DocumentSource,
private val encryptedImages: EncryptedImageStore
) : WallpaperRepository {
private val wallpaperDao = database.wallpaperDao()
@@ -50,6 +56,8 @@ class WallpaperRepositoryImpl @Inject constructor(
screenType: ScreenType,
shuffle: Boolean
) {
if (wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType) != null) return
val allowed = allowedWallpaperIds(albumId)
database.withTransaction {
// Recheck inside the transaction: another caller may already have filled it.
if (wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType) != null) return@withTransaction
@@ -60,11 +68,11 @@ class WallpaperRepositoryImpl @Inject constructor(
} else null
val otherQueue = otherScreen?.let { wallpaperQueueDao.getQueueItems(albumId, it) }.orEmpty()
val ids = if (shuffle) {
val available = wallpaperDao.getWallpaperIdsByAlbum(albumId)
val available = wallpaperDao.getWallpaperIdsByAlbum(albumId).allowed(allowed)
if (otherQueue.isEmpty()) available.shuffled()
else QueueBuilder.mergeWithExistingQueue(otherQueue.map { it.wallpaperId }, available)
} else {
wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId)
wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId).allowed(allowed)
}
wallpaperQueueDao.rebuildQueue(albumId, screenType, ids)
if (otherScreen != null && otherQueue.isEmpty()) {
@@ -73,6 +81,36 @@ class WallpaperRepositoryImpl @Inject constructor(
}
}
override suspend fun startSequenceAfter(
albumId: String,
screenType: ScreenType,
wallpaperId: String
) {
val allowed = allowedWallpaperIds(albumId)
database.withTransaction {
val ordered = wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId)
wallpaperQueueDao.rebuildQueue(
albumId, screenType, QueueBuilder.idsAfter(ordered, wallpaperId).allowed(allowed)
)
}
}
private fun List<String>.allowed(allowed: Set<String>?) = if (allowed == null) this else filter { it in allowed }
/** Ids passing the album filter, or null without one. Images outside a folder with a naming table never pass. */
private suspend fun allowedWallpaperIds(albumId: String): Set<String>? {
val filter = database.albumDao().getAlbumById(albumId)?.filter?.let(::albumFilterRegex) ?: return null
val allowed = HashSet<String>()
database.folderDao().getFoldersByAlbum(albumId).forEach { folder ->
val table = documents.readNamingTable(folder.uri) ?: return@forEach
val files = matchingNamingTableFiles(encryptedImages.decrypt(table).decodeToString(), filter)
wallpaperDao.getFolderWallpapers(folder.id)
.filter { it.fileName.substringAfterLast('/') in files }
.mapTo(allowed) { it.id }
}
return allowed
}
override suspend fun clearAllQueues() {
wallpaperQueueDao.deleteAllQueueItems()
}
@@ -10,11 +10,12 @@ import android.provider.DocumentsContract
import android.provider.OpenableColumns
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.runCatchingCancellable
import com.anthonyla.paperize.domain.source.DocumentSource
import com.anthonyla.paperize.domain.source.NAMING_TABLE_FILE
import com.anthonyla.paperize.domain.source.SourceFolder
import com.anthonyla.paperize.domain.source.SourceImage
import com.anthonyla.paperize.domain.source.isSupportedSourceName
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
@@ -37,14 +38,27 @@ class AndroidDocumentSource @Inject constructor(
SourceImage(uri, document?.name ?: uri.substringAfterLast('/'), document?.lastModified() ?: 0L)
}
override suspend fun readFolder(uri: String, onProgress: (Int) -> Unit): SourceFolder = withContext(Dispatchers.IO) {
override suspend fun readFolder(uri: String, isEncrypted: Boolean, onProgress: (Int) -> Unit): SourceFolder = withContext(Dispatchers.IO) {
val tree = uri.toUri()
SourceFolder(
DocumentFile.fromTreeUri(context, tree)?.name ?: uri.substringAfterLast('/'),
tree.scanFolderImages(context, onProgress)
tree.scanFolderImages(context, isEncrypted, onProgress)
)
}
override suspend fun readNamingTable(folderUri: String): ByteArray? = withContext(Dispatchers.IO) {
val tree = folderUri.toUri()
val children = DocumentsContract.buildChildDocumentsUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))
val projection = arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val documentId = context.contentResolver.query(children, projection, null, null, null)?.use { cursor ->
cursor.requireComplete()
generateSequence { if (cursor.moveToNext()) cursor else null }
.firstOrNull { it.getString(1) == NAMING_TABLE_FILE }?.getString(0)
} ?: return@withContext null
val table = DocumentsContract.buildDocumentUriUsingTree(tree, documentId)
context.contentResolver.openInputStream(table)?.use { it.readBytes() }
}
override suspend fun isMissing(uri: String, isTree: Boolean): Boolean = withContext(Dispatchers.IO) {
val source = uri.toUri()
val document = if (isTree) {
@@ -80,7 +94,7 @@ private fun Cursor.requireComplete() {
* Rejects incomplete provider results and cancels in-flight queries with the caller.
* [onProgress] reports every [PROGRESS_REPORT_INTERVAL] discoveries and on completion.
*/
internal suspend fun Uri.scanFolderImages(context: Context, onProgress: (found: Int) -> Unit = {}): List<SourceImage> {
internal suspend fun Uri.scanFolderImages(context: Context, isEncrypted: Boolean, onProgress: (found: Int) -> Unit = {}): List<SourceImage> {
val rootDocumentId = DocumentsContract.getTreeDocumentId(this)
val projection = arrayOf(
@@ -122,12 +136,15 @@ internal suspend fun Uri.scanFolderImages(context: Context, onProgress: (found:
currentCoroutineContext().ensureActive()
val documentId = cursor.getString(idColumn) ?: continue
if (!visitedDocuments.add(documentId)) continue
val name = cursor.getString(nameColumn) ?: continue
// Galleries rename deleted files in place: .trashed-…, .Trash-…
// HyperOS keeps reporting the old display name, so the id is checked too.
val fileName = documentId.substringAfterLast('/').substringAfterLast(':')
if (listOf(name, fileName).any { it.startsWith(".trash", ignoreCase = true) }) continue
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
pendingDirs.addLast(documentId)
} else {
val name = cursor.getString(nameColumn) ?: continue
val extension = name.substringAfterLast('.', "").lowercase()
if (extension in Constants.SUPPORTED_IMAGE_EXTENSIONS) {
if (isSupportedSourceName(name, isEncrypted)) {
results.add(
SourceImage(
uri = DocumentsContract.buildDocumentUriUsingTree(this, documentId).toString(),
@@ -2,6 +2,8 @@ package com.anthonyla.paperize.data.source
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.util.Log
import androidx.core.net.toUri
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
@@ -14,11 +16,13 @@ import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.source.WallpaperRenderer
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import java.nio.ByteBuffer
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
class AndroidWallpaperRenderer @Inject constructor(
@param:ApplicationContext private val context: Context
@param:ApplicationContext private val context: Context,
private val encryptedImages: EncryptedImageStore
) : WallpaperRenderer {
override suspend fun render(wallpaper: Wallpaper, screen: ScreenType, settings: ScheduleSettings): Bitmap? {
currentCoroutineContext().ensureActive()
@@ -33,8 +37,22 @@ class AndroidWallpaperRenderer @Inject constructor(
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
val decrypted = if (wallpaper.fileName.endsWith(".jpg_enc", ignoreCase = true)) {
try {
encryptedImages.decrypt(wallpaper.uri.toUri())
} catch (e: Exception) {
Log.e("AndroidWallpaperRenderer", "Could not decrypt wallpaper", e)
throw e
}
} else null
var bitmap = try {
retrieveBitmap(context, wallpaper.uri.toUri(), size.width, size.height, scaling,
usesLauncherManagedScrolling(screen, scaling, settings.homeScrollingEnabled),
settings.blurFitBackground,
decrypted?.let { ImageDecoder.createSource(ByteBuffer.wrap(it)) })
} finally {
decrypted?.fill(0)
} ?: return null
try {
val processed = processBitmap(
source = bitmap,
@@ -0,0 +1,157 @@
package com.anthonyla.paperize.data.source
import android.content.Context
import android.net.Uri
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.AtomicFile
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
import java.io.IOException
import java.security.KeyStore
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
import javax.inject.Inject
import javax.inject.Singleton
class MissingPassphraseException : IllegalStateException("No encryption passphrase is configured")
class PassphraseStorageException(cause: Throwable) : IllegalStateException("Cannot access the stored passphrase", cause)
class InvalidEncryptedFileException : IOException("Invalid or truncated encrypted file")
class IncorrectPassphraseException : IOException("Incorrect passphrase or damaged encrypted file")
@Singleton
class EncryptedImageStore @Inject constructor(
@param:ApplicationContext private val context: Context
) {
private val passphraseFile = AtomicFile(File(context.noBackupFilesDir, "encrypted_image_passphrase"))
private val mutableRevision = MutableStateFlow(0)
val revision: StateFlow<Int> = mutableRevision.asStateFlow()
@Synchronized
fun setPassphrase(passphrase: String) {
try {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key(create = true))
val plaintext = passphrase.toByteArray(Charsets.UTF_8)
val encrypted = try {
cipher.doFinal(plaintext)
} finally {
plaintext.fill(0)
}
val output = passphraseFile.startWrite()
try {
output.write(cipher.iv)
output.write(encrypted)
passphraseFile.finishWrite(output)
mutableRevision.value += 1
} catch (e: Exception) {
passphraseFile.failWrite(output)
throw e
}
} catch (e: Exception) {
throw PassphraseStorageException(e)
}
}
@Synchronized
fun clearPassphrase() {
passphraseFile.delete()
check(!passphraseFile.baseFile.exists()) { "Cannot clear the stored passphrase" }
mutableRevision.value += 1
}
@Synchronized
fun hasPassphrase(): Boolean = passphraseFile.baseFile.exists()
fun decrypt(uri: Uri): ByteArray {
val passphrase = synchronized(this) { readPassphrase() }
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
?: throw IOException("Cannot open encrypted file")
return decryptEncryptedImage(bytes, passphrase)
}
fun decrypt(bytes: ByteArray): ByteArray = decryptEncryptedImage(bytes, synchronized(this) { readPassphrase() })
private fun readPassphrase(): String {
if (!hasPassphrase()) throw MissingPassphraseException()
try {
val stored = passphraseFile.readFully()
require(stored.size >= IV_SIZE + TAG_SIZE)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(create = false), GCMParameterSpec(128, stored, 0, IV_SIZE))
val plaintext = cipher.doFinal(stored, IV_SIZE, stored.size - IV_SIZE)
return try {
plaintext.toString(Charsets.UTF_8)
} finally {
plaintext.fill(0)
}
} catch (e: Exception) {
throw PassphraseStorageException(e)
}
}
private fun key(create: Boolean): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val existing = keyStore.getKey(KEY_ALIAS, null) as? SecretKey
if (existing != null) return existing
check(create) { "Keystore key is missing" }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").run {
init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
)
generateKey()
}
}
private companion object {
const val KEY_ALIAS = "paperize_encrypted_image_passphrase"
const val IV_SIZE = 12
const val TAG_SIZE = 16
}
}
internal fun decryptEncryptedImage(encrypted: ByteArray, passphrase: String): ByteArray {
val headerSize = 16
if (encrypted.size < headerSize + 16 ||
(encrypted.size - headerSize) % 16 != 0 ||
!encrypted.copyOfRange(0, 8).contentEquals("Salted__".toByteArray(Charsets.US_ASCII))
) throw InvalidEncryptedFileException()
val spec = PBEKeySpec(passphrase.toCharArray(), encrypted.copyOfRange(8, headerSize), 10_000, 384)
val material = try {
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
try {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(
Cipher.DECRYPT_MODE,
SecretKeySpec(material, 0, 32, "AES"),
IvParameterSpec(material, 32, 16)
)
return try {
cipher.doFinal(encrypted, headerSize, encrypted.size - headerSize)
} catch (_: BadPaddingException) {
throw IncorrectPassphraseException()
}
} finally {
material.fill(0)
}
}
@@ -7,5 +7,8 @@ data class Album(
val wallpapers: List<Wallpaper> = emptyList(),
val folders: List<Folder> = emptyList(),
val createdAt: Long = System.currentTimeMillis(),
val modifiedAt: Long = System.currentTimeMillis()
val modifiedAt: Long = System.currentTimeMillis(),
val isEncrypted: Boolean = false,
/** Regex over naming-table lines; only matching images are picked as wallpaper. */
val filter: String? = null
)
@@ -4,5 +4,6 @@ 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
val firstLaunch: Boolean = true,
val encryptedPreviews: Boolean = false
)
@@ -11,6 +11,7 @@ data class Folder(
val dateModified: Long,
val displayOrder: Int = 0,
val wallpapers: List<Wallpaper> = emptyList(),
val removedWallpapers: List<Wallpaper> = emptyList(),
val addedAt: Long = System.currentTimeMillis()
) {
val displayName: String
@@ -19,6 +19,7 @@ data class ScheduleSettings(
val homeScalingType: ScalingType = ScalingType.FILL,
val lockScalingType: ScalingType = ScalingType.FILL,
val homeScrollingEnabled: Boolean = false,
val blurFitBackground: Boolean = false,
val homeEffects: WallpaperEffects = WallpaperEffects(),
val lockEffects: WallpaperEffects = WallpaperEffects(),
val liveAlbumId: String? = null,
@@ -87,6 +88,7 @@ data class ScheduleSettings(
return homeScalingType != other.homeScalingType ||
lockScalingType != other.lockScalingType ||
homeScrollingEnabled != other.homeScrollingEnabled ||
blurFitBackground != other.blurFitBackground ||
homeEffects != other.homeEffects ||
lockEffects != other.lockEffects ||
liveEffects != other.liveEffects ||
@@ -11,9 +11,17 @@ interface AlbumRepository {
fun getAlbumById(albumId: String): Flow<Album?>
suspend fun getAlbumEncryption(albumId: String): Boolean?
fun getFolderById(folderId: String): Flow<Folder?>
suspend fun createAlbum(name: String, coverUri: String? = null): Album
suspend fun createAlbum(name: String, coverUri: String? = null, isEncrypted: Boolean = false): Album
/** Returns false if another album has this name, ignoring case. */
suspend fun renameAlbum(albumId: String, name: String): Boolean
/** A null or blank [filter] removes it. Rebuilds the album queues. */
suspend fun setAlbumFilter(albumId: String, filter: String?)
suspend fun deleteAlbum(albumId: String)
@@ -31,8 +39,22 @@ interface AlbumRepository {
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
): Boolean
/** Makes a folder match a complete scan of it. Returns the number of new images. */
suspend fun syncFolderWallpapers(
albumId: String,
folderId: String,
wallpapers: List<Wallpaper>,
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
): Int
suspend fun removeWallpapersFromAlbum(albumId: String, wallpaperIds: List<String>)
/** Removes one wallpaper; a folder image is also kept out of later rescans. Returns it for [restoreWallpaper]. */
suspend fun removeWallpaper(wallpaperId: String): Wallpaper?
/** Puts a removed wallpaper back where it was. */
suspend fun restoreWallpaper(wallpaper: Wallpaper)
suspend fun removeFolderFromAlbum(albumId: String, folderId: String)
suspend fun deleteAllAlbums()
@@ -42,6 +42,7 @@ interface SettingsRepository {
suspend fun updateDarkMode(enabled: Boolean)
suspend fun updateDynamicTheming(enabled: Boolean)
suspend fun updateAnimate(enabled: Boolean)
suspend fun updateEncryptedPreviews(enabled: Boolean)
suspend fun completeFirstLaunch()
suspend fun updateEnableChanger(enabled: Boolean)
@@ -30,6 +30,13 @@ interface WallpaperRepository {
shuffle: Boolean = false
)
/** Requeue only the album-ordered wallpapers after [wallpaperId]. */
suspend fun startSequenceAfter(
albumId: String,
screenType: ScreenType,
wallpaperId: String
)
/** Used when the shuffle setting changes, so every queue rebuilds in the new order. */
suspend fun clearAllQueues()
@@ -1,11 +1,19 @@
package com.anthonyla.paperize.domain.source
import com.anthonyla.paperize.core.constants.Constants
data class SourceImage(val uri: String, val name: String, val modifiedAt: Long)
data class SourceFolder(val name: String, val images: List<SourceImage>)
fun isSupportedSourceName(name: String, isEncrypted: Boolean): Boolean =
if (isEncrypted) name.endsWith(".jpg_enc", ignoreCase = true)
else name.substringAfterLast('.', "").lowercase() in Constants.SUPPORTED_IMAGE_EXTENSIONS
interface DocumentSource {
suspend fun retainReadPermission(uri: String)
suspend fun readImage(uri: String): SourceImage
suspend fun readFolder(uri: String, onProgress: (Int) -> Unit = {}): SourceFolder
suspend fun readFolder(uri: String, isEncrypted: Boolean, onProgress: (Int) -> Unit = {}): SourceFolder
/** The [NAMING_TABLE_FILE] in the root of a folder, or null if it has none. */
suspend fun readNamingTable(folderUri: String): ByteArray?
suspend fun isMissing(uri: String, isTree: Boolean = false): Boolean
}
@@ -0,0 +1,12 @@
package com.anthonyla.paperize.domain.source
const val NAMING_TABLE_FILE = "naming_table.enc"
fun albumFilterRegex(pattern: String) = Regex(pattern, RegexOption.IGNORE_CASE)
/** File names of the entries whose `name;encrypted_file;hash` line contains a [filter] match, like wallpaper_changer. */
fun matchingNamingTableFiles(table: String, filter: Regex): Set<String> =
table.lineSequence()
.filter { it.count { c -> c == ';' } >= 2 && filter.containsMatchIn(it) }
.map { it.split(';', limit = 3)[1].substringAfterLast('/') }
.toSet()
@@ -32,13 +32,10 @@ class ChangeWallpaperUseCase @Inject constructor(
) {
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)
return dequeueReadable(albumId, screenType, settings.shuffleEnabled) { candidate ->
try {
val bitmap = renderer.render(candidate, screenType, settings)
if (bitmap != null) {
return PreparedWallpaper(bitmap, albumId, screenType, candidate.id, settings.shuffleEnabled)
renderer.render(candidate, screenType, settings)?.let { bitmap ->
PreparedWallpaper(bitmap, albumId, screenType, candidate.id, settings.shuffleEnabled)
}
} catch (e: CancellationException) {
// Cancelling preparation must not consume the selected queue item.
@@ -51,10 +48,33 @@ class ChangeWallpaperUseCase @Inject constructor(
}
throw e
} catch (_: Exception) {
// Unreadable images are skipped for this cycle; refresh owns permanent pruning.
null
}
} ?: throw NoValidWallpaperException()
}
/**
* Dequeue until [open] reads an item. Unreadable items are skipped for this cycle; refresh
* owns permanent pruning. When none is readable the source itself is likely unavailable
* (storage still mounting, a revoked permission), so the queue is left as it was.
*/
suspend fun <T : Any> dequeueReadable(
albumId: String,
screenType: ScreenType,
shuffle: Boolean,
open: suspend (Wallpaper) -> T?
): T? {
val unreadable = mutableListOf<Wallpaper>()
repeat(Constants.MAX_WALLPAPER_LOAD_RETRIES) {
currentCoroutineContext().ensureActive()
val candidate = dequeueNext(albumId, screenType, shuffle)
open(candidate)?.let { return it }
unreadable += candidate
}
throw NoValidWallpaperException()
unreadable.asReversed().forEach {
wallpaperRepository.restoreWallpaperToQueueFront(albumId, screenType, it.id)
}
return null
}
/** Dequeue the next item, rebuilding an empty queue once. Throws [EmptyAlbumException] if none remain. */
@@ -81,12 +101,16 @@ class ChangeWallpaperUseCase @Inject constructor(
shuffle = prepared.shuffle
)
/** Record a user-selected wallpaper and remove that exact item from the next-change queue. */
/**
* Record a user-selected wallpaper and remove that exact item from the next-change queue,
* or with [startSequenceHere] and shuffle off, restart the queue after it.
*/
suspend fun completeSpecific(
albumId: String,
screenType: ScreenType,
wallpaperId: String,
shuffle: Boolean
shuffle: Boolean,
startSequenceHere: Boolean = false
) {
runCatchingCancellable { wallpaperRepository.setCurrentWallpaper(albumId, screenType, wallpaperId) }
.onFailure {
@@ -94,6 +118,12 @@ class ChangeWallpaperUseCase @Inject constructor(
return
}
if (startSequenceHere && !shuffle) {
runCatchingCancellable { wallpaperRepository.startSequenceAfter(albumId, screenType, wallpaperId) }
.onFailure { Log.w(TAG, "Could not continue the sequence from the picked wallpaper", it) }
return
}
runCatchingCancellable {
wallpaperRepository.ensureWallpaperQueue(albumId, screenType, shuffle)
// Build first when this is the first synchronized use of a screen queue, then remove
@@ -8,9 +8,9 @@ class CreateAlbumUseCase @Inject constructor(
private val albumRepository: AlbumRepository
) {
/** Returns false, creating nothing, when an album already has this name ignoring case. */
suspend operator fun invoke(name: String): Boolean {
suspend operator fun invoke(name: String, isEncrypted: Boolean = false): Boolean {
if (albumRepository.getAlbumSummaries().first().any { it.name.equals(name, ignoreCase = true) }) return false
albumRepository.createAlbum(name)
albumRepository.createAlbum(name, isEncrypted = isEncrypted)
return true
}
}
@@ -6,6 +6,7 @@ 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 com.anthonyla.paperize.domain.source.isSupportedSourceName
import kotlinx.coroutines.flow.first
import javax.inject.Inject
@@ -14,9 +15,11 @@ class ImportWallpapersUseCase @Inject constructor(
private val albumRepository: AlbumRepository
) {
suspend fun addImages(albumId: String, uris: List<String>, onSaving: (Int, Int) -> Unit): Boolean {
val images = uris.distinct().map { uri ->
val isEncrypted = checkNotNull(albumRepository.getAlbumEncryption(albumId))
val images = uris.distinct().mapNotNull { uri ->
documents.retainReadPermission(uri)
documents.readImage(uri).toWallpaper(albumId)
val image = documents.readImage(uri)
if (!isEncrypted || isSupportedSourceName(image.name, true)) image.toWallpaper(albumId) else null
}
return albumRepository.addWallpapersToAlbum(albumId, images, onSaving) > 0
}
@@ -29,8 +32,9 @@ class ImportWallpapersUseCase @Inject constructor(
): 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 album = checkNotNull(albumRepository.getAlbumById(albumId).first())
if (album.folders.any { it.uri == uri }) return false
val source = documents.readFolder(uri, album.isEncrypted, onScanning)
val folderId = generateId()
val folder = Folder(
id = folderId, albumId = albumId, uri = uri, name = source.name,
@@ -12,9 +12,10 @@ class RefreshFolderUseCase @Inject constructor(
/** 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) }
val isEncrypted = albumRepository.getAlbumEncryption(folder.albumId) ?: return 0
val source = documents.readFolder(folder.uri, isEncrypted)
return albumRepository.syncFolderWallpapers(
folder.albumId, folderId, source.images.map { it.toWallpaper(folder.albumId, folderId) }
)
}
}
@@ -21,7 +21,6 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.res.stringResource
import com.anthonyla.paperize.R
@@ -49,7 +48,7 @@ fun AddAlbumAnimatedFab(
}
}
Icon(
painter = rememberVectorPainter(imageVector),
imageVector = imageVector,
contentDescription = if (fabMenuExpanded) {
stringResource(R.string.content_desc_collapse)
} else {
@@ -13,11 +13,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import coil3.compose.AsyncImagePainter
import coil3.compose.rememberAsyncImagePainter
import coil3.request.ImageRequest
import coil3.size.Size
import com.anthonyla.paperize.domain.model.AlbumSummary
/** The album's cover image, or a placeholder icon until one loads. */
@@ -30,10 +27,7 @@ fun AlbumCover(
placeholderModifier: Modifier = Modifier
) {
val cover = rememberAsyncImagePainter(
ImageRequest.Builder(LocalContext.current)
.data(album.coverUri)
.size(Size(thumbnailSize, thumbnailSize))
.build(),
encryptedAwareImageRequest(album.coverUri, thumbnailSize, thumbnailSize),
contentScale = ContentScale.Crop
)
val coverState by cover.state.collectAsState()
@@ -1,23 +1,27 @@
package com.anthonyla.paperize.presentation.common.components
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import com.anthonyla.paperize.R
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
@Composable
fun AddAlbumDialog(
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
onConfirm: (String, Boolean) -> Unit,
errorMessage: String?,
isSaving: Boolean
) {
var albumName by rememberSaveable { mutableStateOf("") }
var isEncrypted by rememberSaveable { mutableStateOf(false) }
AlertDialog(
onDismissRequest = { if (!isSaving) onDismiss() },
@@ -38,11 +42,24 @@ fun AddAlbumDialog(
} else null,
modifier = Modifier.fillMaxWidth()
)
Row(
modifier = Modifier.fillMaxWidth().toggleable(
value = isEncrypted,
enabled = !isSaving,
role = Role.Checkbox,
onValueChange = { isEncrypted = it }
),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(checked = isEncrypted, onCheckedChange = null, enabled = !isSaving)
Text(stringResource(R.string.encrypted_album))
}
Text(stringResource(R.string.encrypted_album_hint), style = MaterialTheme.typography.bodySmall)
}
},
confirmButton = {
TextButton(
onClick = { onConfirm(albumName.trim()) },
onClick = { onConfirm(albumName.trim(), isEncrypted) },
enabled = !isSaving && albumName.isNotBlank()
) {
Text(stringResource(R.string.save))
@@ -0,0 +1,138 @@
package com.anthonyla.paperize.presentation.common.components
import android.graphics.ImageDecoder
import android.provider.OpenableColumns
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.core.net.toUri
import androidx.compose.ui.platform.LocalContext
import coil3.request.CachePolicy
import coil3.request.ImageRequest
import coil3.request.crossfade
import coil3.size.Size
import com.anthonyla.paperize.data.source.EncryptedImageStore
import com.anthonyla.paperize.domain.repository.SettingsRepository
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import java.nio.ByteBuffer
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@EntryPoint
@InstallIn(SingletonComponent::class)
interface EncryptedPreviewEntryPoint {
fun encryptedImages(): EncryptedImageStore
fun settings(): SettingsRepository
}
private data class PreviewImage(val data: Any, val encrypted: Boolean)
@Composable
fun encryptedAwareImageRequest(
uri: String?,
width: Int? = null,
height: Int? = null,
animate: Boolean = false
): ImageRequest? {
val context = LocalContext.current
val dependencies = remember(context) {
EntryPointAccessors.fromApplication(context.applicationContext, EncryptedPreviewEntryPoint::class.java)
}
val settings = remember(dependencies) { dependencies.settings().getAppSettingsFlow() }
val appSettings by settings.collectAsState(initial = null)
val enabled = appSettings?.encryptedPreviews == true
val store = remember(dependencies) { dependencies.encryptedImages() }
return encryptedPreviewImageRequest(uri, width, height, animate, enabled, store)
}
@Composable
internal fun encryptedPreviewImageRequest(
uri: String?,
width: Int?,
height: Int?,
animate: Boolean,
enabled: Boolean,
store: EncryptedImageStore
): ImageRequest? {
val context = LocalContext.current
val revision by store.revision.collectAsState()
return key(uri, enabled, revision, width, height) {
val image by produceState<PreviewImage?>(initialValue = null) {
if (uri != null) {
value = withContext(Dispatchers.IO) {
try {
val parsed = uri.toUri()
val name = if (parsed.scheme == "file") parsed.lastPathSegment else {
try {
context.contentResolver.query(
parsed, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null
)?.use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0) else null
}
} catch (e: Exception) {
Log.w("EncryptedPreview", "Could not read image name; loading the original URI", e)
null
}
}
if (name == null) {
Log.w("EncryptedPreview", "Image name unavailable; loading the original URI")
}
val isEncrypted = (name ?: parsed.lastPathSegment)?.endsWith(".jpg_enc", ignoreCase = true) == true
if (!isEncrypted) {
PreviewImage(parsed, false)
} else if (!enabled) {
null
} else {
val bytes = store.decrypt(parsed)
try {
val bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) {
decoder, info, _ ->
val maxWidth = width ?: 2048
val maxHeight = height ?: 2048
val scale = minOf(1f, maxWidth.toFloat() / info.size.width, maxHeight.toFloat() / info.size.height)
decoder.setTargetSize(
(info.size.width * scale).toInt().coerceAtLeast(1),
(info.size.height * scale).toInt().coerceAtLeast(1)
)
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
}
PreviewImage(bitmap, true)
} finally {
bytes.fill(0)
}
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w("EncryptedPreview", "Could not load image preview", e)
null
}
}
}
}
remember(context, image, width, height, animate) {
image?.let {
ImageRequest.Builder(context)
.data(it.data)
.crossfade(animate && !it.encrypted)
.apply {
if (width != null && height != null) size(Size(width, height))
if (it.encrypted) {
memoryCachePolicy(CachePolicy.DISABLED)
diskCachePolicy(CachePolicy.DISABLED)
}
}
.build()
}
}
}
}
@@ -31,7 +31,6 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.presentation.common.navigation.util.NavConstants
@@ -41,9 +40,9 @@ import kotlinx.coroutines.delay
@Composable
fun OnboardingLayout(
title: String,
modifier: Modifier = Modifier,
iconContent: @Composable () -> Unit,
content: @Composable () -> Unit,
modifier: Modifier = Modifier,
actions: @Composable () -> Unit
) {
var visible by remember { mutableStateOf(false) }
@@ -91,7 +90,6 @@ fun OnboardingLayout(
text = title,
style = MaterialTheme.typography.headlineLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
}
@@ -130,7 +128,6 @@ fun OnboardingButton(
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
@@ -2,7 +2,6 @@ package com.anthonyla.paperize.presentation.common.components
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
@@ -25,7 +24,6 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SelectableGridCard(
isSelected: Boolean,
@@ -1,36 +1,60 @@
package com.anthonyla.paperize.presentation.common.components
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
/** Related [SettingsRow]s drawn as one rounded block, split by hairline gaps instead of nested cards. */
@Composable
fun SettingsCard(
fun SettingsGroup(
modifier: Modifier = Modifier,
title: String? = null,
content: @Composable ColumnScope.() -> Unit
) {
Column(modifier = modifier.fillMaxWidth()) {
if (title != null) {
Text(
text = title,
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = AppSpacing.large, end = AppSpacing.large, bottom = AppSpacing.small)
)
}
Column(
modifier = Modifier.clip(MaterialTheme.shapes.large),
verticalArrangement = Arrangement.spacedBy(AppSpacing.hairline),
content = content
)
}
}
@Composable
fun SettingsRow(
modifier: Modifier = Modifier,
contentModifier: Modifier = Modifier,
onClick: (() -> Unit)? = null,
verticalArrangement: Arrangement.Vertical = Arrangement.Top,
content: @Composable ColumnScope.() -> Unit
) {
val shape = MaterialTheme.shapes.medium
val colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow)
val body: @Composable ColumnScope.() -> Unit = {
val color = MaterialTheme.colorScheme.surfaceContainer
val body: @Composable () -> Unit = {
Column(
modifier = contentModifier.padding(AppSpacing.large),
modifier = contentModifier.padding(horizontal = AppSpacing.large, vertical = AppSpacing.medium),
verticalArrangement = verticalArrangement,
content = content
)
}
if (onClick == null) {
Card(modifier = modifier.fillMaxWidth(), shape = shape, colors = colors, content = body)
Surface(modifier = modifier.fillMaxWidth(), color = color, content = body)
} else {
Card(onClick = onClick, modifier = modifier.fillMaxWidth(), shape = shape, colors = colors, content = body)
Surface(onClick = onClick, modifier = modifier.fillMaxWidth(), color = color, content = body)
}
}
@@ -41,17 +65,18 @@ fun SettingSwitchItem(
onCheckedChange: (Boolean) -> Unit,
description: String? = null
) {
SettingsCard(modifier = Modifier.padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)) {
SettingSwitchRow(title, description, checked, onCheckedChange)
SettingsRow(modifier = Modifier.toggleable(value = checked, role = Role.Switch, onValueChange = onCheckedChange)) {
SettingSwitchRow(title, description, checked, onCheckedChange = null)
}
}
/** A null [onCheckedChange] leaves toggling to a parent that handles the whole row. */
@Composable
fun SettingSwitchRow(
title: String,
description: String?,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit
onCheckedChange: ((Boolean) -> Unit)?
) {
Row(
modifier = Modifier
@@ -60,33 +85,31 @@ fun SettingSwitchRow(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
SettingText(
title = title,
description = description,
modifier = Modifier
.weight(1f)
.padding(end = AppSpacing.large),
verticalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall)
) {
Text(
text = title,
fontWeight = FontWeight.SemiBold,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
if (description != null) {
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
}
}
Switch(
checked = checked,
onCheckedChange = onCheckedChange
.padding(end = AppSpacing.large)
)
Switch(checked = checked, onCheckedChange = onCheckedChange)
}
}
@Composable
fun SettingText(title: String, description: String?, modifier: Modifier = Modifier) {
Column(modifier = modifier) {
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface
)
if (description != null) {
Text(
text = description,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
@@ -4,15 +4,11 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.core.net.toUri
import coil3.compose.AsyncImage
import coil3.request.ImageRequest
import coil3.size.Size
import com.anthonyla.paperize.core.constants.Constants
@Composable
@@ -36,10 +32,9 @@ fun WallpaperItem(
}
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(wallpaperUri.toUri())
.size(Size(Constants.GRID_THUMBNAIL_WIDTH, Constants.GRID_THUMBNAIL_HEIGHT))
.build(),
model = encryptedAwareImageRequest(
wallpaperUri, Constants.GRID_THUMBNAIL_WIDTH, Constants.GRID_THUMBNAIL_HEIGHT
),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
@@ -2,75 +2,76 @@ package com.anthonyla.paperize.presentation.common.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFFB8336A)
// Drawn from the launcher icon: its rose sheet is the light primary, its pink ground the primary
// container, and its black sheet the ink behind the text and dark surfaces.
val md_theme_light_primary = Color(0xFFC2255C)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFFFD9E4)
val md_theme_light_onPrimaryContainer = Color(0xFF8C1F4C)
val md_theme_light_secondary = Color(0xFF8B5563)
val md_theme_light_primaryContainer = Color(0xFFFFD9E2)
val md_theme_light_onPrimaryContainer = Color(0xFF7A0F38)
val md_theme_light_secondary = Color(0xFF73565D)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFFFDAE1)
val md_theme_light_onSecondaryContainer = Color(0xFF6A3D49)
val md_theme_light_tertiary = Color(0xFFA35F35)
val md_theme_light_secondaryContainer = Color(0xFFFBDBE1)
val md_theme_light_onSecondaryContainer = Color(0xFF2B151B)
val md_theme_light_tertiary = Color(0xFFA83A34)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFDCC2)
val md_theme_light_onTertiaryContainer = Color(0xFF7A4520)
val md_theme_light_tertiaryContainer = Color(0xFFFFDAD5)
val md_theme_light_onTertiaryContainer = Color(0xFF73120F)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF93000A)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF211A1C)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF211A1C)
val md_theme_light_surfaceVariant = Color(0xFFF4DDE2)
val md_theme_light_onSurfaceVariant = Color(0xFF524245)
val md_theme_light_outline = Color(0xFF857275)
val md_theme_light_inverseOnSurface = Color(0xFFFEEDF0)
val md_theme_light_inverseSurface = Color(0xFF372E2F)
val md_theme_light_inversePrimary = Color(0xFFFFB0C8)
val md_theme_light_surfaceTint = Color(0xFFB8336A)
val md_theme_light_outlineVariant = Color(0xFFD7C1C4)
val md_theme_light_background = Color(0xFFFFF8F9)
val md_theme_light_onBackground = Color(0xFF1C0F13)
val md_theme_light_surface = Color(0xFFFFF8F9)
val md_theme_light_onSurface = Color(0xFF1C0F13)
val md_theme_light_surfaceVariant = Color(0xFFF5DDE2)
val md_theme_light_onSurfaceVariant = Color(0xFF524347)
val md_theme_light_outline = Color(0xFF857378)
val md_theme_light_inverseOnSurface = Color(0xFFFFECEF)
val md_theme_light_inverseSurface = Color(0xFF2B1D21)
val md_theme_light_inversePrimary = Color(0xFFFFB1C5)
val md_theme_light_surfaceTint = Color(0xFFC2255C)
val md_theme_light_outlineVariant = Color(0xFFD9C1C6)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFFFB3CA)
val md_theme_dark_onPrimary = Color(0xFF650033)
val md_theme_dark_primaryContainer = Color(0xFF8F1F4F)
val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E4)
val md_theme_dark_secondary = Color(0xFFE7BFC8)
val md_theme_dark_onSecondary = Color(0xFF4A2A32)
val md_theme_dark_secondaryContainer = Color(0xFF714551)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFDAE1)
val md_theme_dark_tertiary = Color(0xFFF5C098)
val md_theme_dark_onTertiary = Color(0xFF522A0C)
val md_theme_dark_tertiaryContainer = Color(0xFF7F4825)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDCC2)
val md_theme_dark_primary = Color(0xFFFFB1C5)
val md_theme_dark_onPrimary = Color(0xFF5E1130)
val md_theme_dark_primaryContainer = Color(0xFF7D1F43)
val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E2)
val md_theme_dark_secondary = Color(0xFFE4BDC5)
val md_theme_dark_onSecondary = Color(0xFF43292F)
val md_theme_dark_secondaryContainer = Color(0xFF5C3F46)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFD9E0)
val md_theme_dark_tertiary = Color(0xFFFFB4A9)
val md_theme_dark_onTertiary = Color(0xFF5F150F)
val md_theme_dark_tertiaryContainer = Color(0xFF7E2B23)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDAD5)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1A1114)
val md_theme_dark_onBackground = Color(0xFFF0E0E2)
val md_theme_dark_surface = Color(0xFF1A1114)
val md_theme_dark_onSurface = Color(0xFFF0E0E2)
val md_theme_dark_surfaceVariant = Color(0xFF534244)
val md_theme_dark_onSurfaceVariant = Color(0xFFD7C1C4)
val md_theme_dark_outline = Color(0xFFA08C8F)
val md_theme_dark_inverseOnSurface = Color(0xFF1A1114)
val md_theme_dark_inverseSurface = Color(0xFFF0E0E2)
val md_theme_dark_inversePrimary = Color(0xFFB8336A)
val md_theme_dark_surfaceTint = Color(0xFFFFB3CA)
val md_theme_dark_outlineVariant = Color(0xFF534244)
val md_theme_dark_background = Color(0xFF171012)
val md_theme_dark_onBackground = Color(0xFFF1DEE2)
val md_theme_dark_surface = Color(0xFF171012)
val md_theme_dark_onSurface = Color(0xFFF1DEE2)
val md_theme_dark_surfaceVariant = Color(0xFF524347)
val md_theme_dark_onSurfaceVariant = Color(0xFFD9C1C6)
val md_theme_dark_outline = Color(0xFFA18B90)
val md_theme_dark_inverseOnSurface = Color(0xFF2B1D21)
val md_theme_dark_inverseSurface = Color(0xFFF1DEE2)
val md_theme_dark_inversePrimary = Color(0xFFC2255C)
val md_theme_dark_surfaceTint = Color(0xFFFFB1C5)
val md_theme_dark_outlineVariant = Color(0xFF524347)
val md_theme_dark_scrim = Color(0xFF000000)
val md_theme_light_surfaceContainer = Color(0xFFF7F2F3)
val md_theme_light_surfaceContainerHigh = Color(0xFFF1ECEE)
val md_theme_light_surfaceContainerHighest = Color(0xFFEBE6E8)
val md_theme_light_surfaceContainerLow = Color(0xFFFDF8F9)
val md_theme_light_surfaceContainer = Color(0xFFF9EBEE)
val md_theme_light_surfaceContainerHigh = Color(0xFFF3E5E8)
val md_theme_light_surfaceContainerHighest = Color(0xFFEDDFE2)
val md_theme_light_surfaceContainerLow = Color(0xFFFEF1F3)
val md_theme_light_surfaceContainerLowest = Color(0xFFFFFFFF)
val md_theme_dark_surfaceContainer = Color(0xFF241D1F)
val md_theme_dark_surfaceContainerHigh = Color(0xFF2F272A)
val md_theme_dark_surfaceContainerHighest = Color(0xFF3A3235)
val md_theme_dark_surfaceContainerLow = Color(0xFF211A1C)
val md_theme_dark_surfaceContainerLowest = Color(0xFF0F0D0E)
val md_theme_dark_surfaceContainer = Color(0xFF241B1E)
val md_theme_dark_surfaceContainerHigh = Color(0xFF2E2528)
val md_theme_dark_surfaceContainerHighest = Color(0xFF393033)
val md_theme_dark_surfaceContainerLow = Color(0xFF1F171A)
val md_theme_dark_surfaceContainerLowest = Color(0xFF110B0D)
@@ -3,6 +3,7 @@ package com.anthonyla.paperize.presentation.common.theme
import androidx.compose.ui.unit.dp
object AppSpacing {
val hairline = 2.dp
val extraSmall = 6.dp
val small = 12.dp
val medium = 16.dp
@@ -5,8 +5,14 @@ import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
@@ -17,6 +23,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
@@ -38,6 +45,7 @@ import com.anthonyla.paperize.presentation.screens.album_view.components.AlbumVi
import com.anthonyla.paperize.presentation.screens.album_view.components.FolderItem
import com.anthonyla.paperize.presentation.screens.album_view.components.ImportProgressDialog
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch
@Composable
fun AlbumViewScreen(
@@ -57,8 +65,18 @@ fun AlbumViewScreen(
val importProgress by viewModel.importProgress.collectAsStateWithLifecycle()
val message by viewModel.message.collectAsStateWithLifecycle()
val isDeleting by viewModel.isDeleting.collectAsStateWithLifecycle()
val isRefreshing by viewModel.isRefreshing.collectAsStateWithLifecycle()
val albumDeleted by viewModel.albumDeleted.collectAsStateWithLifecycle()
var showDeleteAlbumDialog by rememberSaveable { mutableStateOf(false) }
var showRenameDialog by rememberSaveable { mutableStateOf(false) }
var renameText by rememberSaveable { mutableStateOf("") }
var renameError by rememberSaveable { mutableStateOf<Int?>(null) }
var isRenaming by remember { mutableStateOf(false) }
var showFilterDialog by rememberSaveable { mutableStateOf(false) }
var filterText by rememberSaveable { mutableStateOf("") }
var filterError by rememberSaveable { mutableStateOf<Int?>(null) }
var isFiltering by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
SnackbarMessageEffect(message, snackbarHostState, viewModel::dismissMessage)
LaunchedEffect(viewModel) {
@@ -104,24 +122,42 @@ fun AlbumViewScreen(
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
topBar = {
AlbumViewTopBar(
title = album?.name ?: "",
isSelectionMode = isSelectionMode,
selectedCount = selectedCount,
allSelected = allSelected,
onBackClick = onBackClick,
onSortClick = { showSortSheet = true },
onDeleteAlbum = { showDeleteAlbumDialog = true },
onSelectAll = { if (allSelected) viewModel.clearSelection() else viewModel.selectAll() },
onDeleteSelected = { if (!isDeleting) showDeleteSelectedDialog = true },
onClearSelection = { viewModel.clearSelection() }
)
Column {
AlbumViewTopBar(
title = album?.name ?: "",
isSelectionMode = isSelectionMode,
selectedCount = selectedCount,
allSelected = allSelected,
onBackClick = onBackClick,
onSortClick = { showSortSheet = true },
onDeleteAlbum = { showDeleteAlbumDialog = true },
onRenameAlbum = {
renameText = album?.name.orEmpty()
renameError = null
showRenameDialog = true
},
onFilterAlbum = if (album?.isEncrypted == true) {
{
filterText = album?.filter.orEmpty()
filterError = null
showFilterDialog = true
}
} else null,
onRefreshFolders = viewModel::refreshFolders,
albumActionsEnabled = album != null && !isDeleting && !isRefreshing && importProgress is ImportProgress.Idle,
hasFolders = folders.isNotEmpty(),
onSelectAll = { if (allSelected) viewModel.clearSelection() else viewModel.selectAll() },
onDeleteSelected = { if (!isDeleting && !isRefreshing) showDeleteSelectedDialog = true },
onClearSelection = { viewModel.clearSelection() }
)
if (isRefreshing) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
},
floatingActionButton = {
if (!isSelectionMode && totalItemsCount > 0) {
if (!isSelectionMode && !isRefreshing && totalItemsCount > 0) {
AddAlbumAnimatedFab(
isLoading = importProgress !is ImportProgress.Idle,
onImageClick = { imagePickerLauncher.launch(arrayOf("image/*")) },
onImageClick = { imagePickerLauncher.launch(arrayOf(if (album?.isEncrypted == true) "*/*" else "image/*")) },
onFolderClick = { folderPickerLauncher.launch(null) }
)
}
@@ -133,10 +169,10 @@ fun AlbumViewScreen(
hint = stringResource(R.string.album_empty_hint),
modifier = modifier.padding(paddingValues)
) {
FilledTonalButton(onClick = { imagePickerLauncher.launch(arrayOf("image/*")) }) {
FilledTonalButton(enabled = !isRefreshing, onClick = { imagePickerLauncher.launch(arrayOf(if (album?.isEncrypted == true) "*/*" else "image/*")) }) {
Text(stringResource(R.string.add_wallpapers))
}
TextButton(onClick = { folderPickerLauncher.launch(null) }) {
TextButton(enabled = !isRefreshing, onClick = { folderPickerLauncher.launch(null) }) {
Text(stringResource(R.string.add_folder))
}
}
@@ -200,6 +236,90 @@ fun AlbumViewScreen(
ImportProgressDialog(progress = importProgress, onCancel = viewModel::cancelImport)
if (showRenameDialog) {
AlertDialog(
onDismissRequest = { if (!isRenaming) showRenameDialog = false },
title = { Text(stringResource(R.string.rename_album)) },
text = {
OutlinedTextField(
value = renameText,
onValueChange = { renameText = it; renameError = null },
label = { Text(stringResource(R.string.album_name)) },
singleLine = true,
enabled = !isRenaming,
isError = renameError != null,
supportingText = renameError?.let { error ->
{ Text(stringResource(error), color = MaterialTheme.colorScheme.error) }
}
)
},
confirmButton = {
TextButton(
enabled = !isRenaming && renameText.isNotBlank(),
onClick = {
isRenaming = true
scope.launch {
try {
renameError = viewModel.renameAlbum(renameText.trim())
if (renameError == null) showRenameDialog = false
} finally {
isRenaming = false
}
}
}
) { Text(stringResource(R.string.save)) }
},
dismissButton = {
TextButton(onClick = { showRenameDialog = false }, enabled = !isRenaming) {
Text(stringResource(R.string.cancel))
}
}
)
}
if (showFilterDialog) {
AlertDialog(
onDismissRequest = { if (!isFiltering) showFilterDialog = false },
title = { Text(stringResource(R.string.filter_album)) },
text = {
OutlinedTextField(
value = filterText,
onValueChange = { filterText = it; filterError = null },
label = { Text(stringResource(R.string.filter_pattern)) },
supportingText = {
val error = filterError
if (error != null) Text(stringResource(error), color = MaterialTheme.colorScheme.error)
else Text(stringResource(R.string.filter_pattern_hint))
},
singleLine = true,
enabled = !isFiltering,
isError = filterError != null
)
},
confirmButton = {
TextButton(
enabled = !isFiltering,
onClick = {
isFiltering = true
scope.launch {
try {
filterError = viewModel.setFilter(filterText.trim())
if (filterError == null) showFilterDialog = false
} finally {
isFiltering = false
}
}
}
) { Text(stringResource(R.string.save)) }
},
dismissButton = {
TextButton(onClick = { showFilterDialog = false }, enabled = !isFiltering) {
Text(stringResource(R.string.cancel))
}
}
)
}
if (showDeleteSelectedDialog) {
ConfirmDialog(
title = stringResource(R.string.remove_selected_title, selectedCount),
@@ -9,8 +9,10 @@ import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.runCatchingCancellable
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.source.albumFilterRegex
import com.anthonyla.paperize.domain.usecase.DeleteAlbumUseCase
import com.anthonyla.paperize.domain.usecase.ImportWallpapersUseCase
import com.anthonyla.paperize.domain.usecase.RefreshFolderUseCase
import com.anthonyla.paperize.presentation.common.launchBusy
import com.anthonyla.paperize.presentation.common.navigation.AlbumRoute
import com.anthonyla.paperize.presentation.common.stateWhileSubscribed
@@ -20,6 +22,8 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
@HiltViewModel
@@ -27,7 +31,8 @@ class AlbumViewViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val albumRepository: AlbumRepository,
private val importWallpapersUseCase: ImportWallpapersUseCase,
private val deleteAlbumUseCase: DeleteAlbumUseCase
private val deleteAlbumUseCase: DeleteAlbumUseCase,
private val refreshFolderUseCase: RefreshFolderUseCase
) : ViewModel() {
companion object {
@@ -54,6 +59,8 @@ class AlbumViewViewModel @Inject constructor(
val isDeleting = _isDeleting.asStateFlow()
private val _albumDeleted = MutableStateFlow(false)
val albumDeleted = _albumDeleted.asStateFlow()
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing = _isRefreshing.asStateFlow()
private var importJob: Job? = null
fun dismissMessage() { _message.value = null }
@@ -78,7 +85,7 @@ class AlbumViewViewModel @Inject constructor(
}
private fun import(initialProgress: ImportProgress, block: suspend () -> Boolean) {
if (importJob?.isCompleted == false || _isDeleting.value) return
if (importJob?.isCompleted == false || _isDeleting.value || _isRefreshing.value) return
_message.value = null
_importProgress.value = initialProgress
importJob = viewModelScope.launch {
@@ -100,7 +107,7 @@ class AlbumViewViewModel @Inject constructor(
fun cancelImport() { importJob?.cancel() }
fun deleteAlbum() {
if (_isDeleting.value || importJob?.isCompleted == false) return
if (_isDeleting.value || _isRefreshing.value || importJob?.isCompleted == false) return
_message.value = null
launchBusy(_isDeleting) {
runCatchingCancellable { deleteAlbumUseCase(albumId) }
@@ -112,13 +119,61 @@ class AlbumViewViewModel @Inject constructor(
}
}
suspend fun renameAlbum(name: String): Int? =
runCatchingCancellable { albumRepository.renameAlbum(albumId, name) }
.fold(
onSuccess = { renamed -> if (renamed) null else R.string.album_name_exists_error },
onFailure = { e ->
Log.e(TAG, "Error renaming album", e)
R.string.rename_album_failed
}
)
suspend fun setFilter(filter: String): Int? {
if (runCatching { albumFilterRegex(filter) }.isFailure) return R.string.filter_invalid
return runCatchingCancellable { albumRepository.setAlbumFilter(albumId, filter) }
.fold(
onSuccess = { null },
onFailure = { e ->
Log.e(TAG, "Error setting album filter", e)
R.string.filter_album_failed
}
)
}
fun refreshFolders() {
if (_isRefreshing.value || _isDeleting.value || importJob?.isCompleted == false) return
_message.value = null
launchBusy(_isRefreshing) {
val result = runCatchingCancellable {
val folders = checkNotNull(albumRepository.getAlbumById(albumId).first()).folders
var failed = false
folders.forEach { folder ->
runCatchingCancellable { refreshFolderUseCase(folder.id) }
.onFailure { e ->
Log.e(TAG, "Error refreshing folder '${folder.name}'", e)
failed = true
}
}
failed
}
_message.value = result.fold(
onSuccess = { failed -> if (failed) R.string.album_refresh_failed else R.string.album_refreshed },
onFailure = { e ->
Log.e(TAG, "Error loading album folders", e)
R.string.album_refresh_failed
}
)
}
}
fun toggleWallpaperSelection(wallpaperId: String) = toggle(_selectedWallpapers, wallpaperId)
fun toggleFolderSelection(folderId: String) = toggle(_selectedFolders, folderId)
private fun toggle(selection: MutableStateFlow<Set<String>>, id: String) {
if (_isDeleting.value) return
selection.value = if (id in selection.value) selection.value - id else selection.value + id
selection.update { if (id in it) it - id else it + id }
}
fun selectAll() {
@@ -134,7 +189,7 @@ class AlbumViewViewModel @Inject constructor(
}
fun deleteSelected() {
if (_isDeleting.value || importJob?.isCompleted == false) return
if (_isDeleting.value || _isRefreshing.value || importJob?.isCompleted == false) return
_message.value = null
val wallpaperIds = _selectedWallpapers.value.toList()
val folderIds = _selectedFolders.value.toList()
@@ -1,17 +1,25 @@
package com.anthonyla.paperize.presentation.screens.album_view.components
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import com.anthonyla.paperize.R
@@ -27,6 +35,11 @@ fun AlbumViewTopBar(
onBackClick: () -> Unit,
onSortClick: () -> Unit,
onDeleteAlbum: () -> Unit,
onRenameAlbum: () -> Unit,
onFilterAlbum: (() -> Unit)?,
onRefreshFolders: () -> Unit,
albumActionsEnabled: Boolean,
hasFolders: Boolean,
onSelectAll: () -> Unit,
onDeleteSelected: () -> Unit,
onClearSelection: () -> Unit
@@ -64,6 +77,7 @@ fun AlbumViewTopBar(
}
)
} else {
var menuExpanded by remember { mutableStateOf(false) }
BackTopAppBar(title = title, onBack = onBackClick) {
IconButton(onClick = onSortClick) {
Icon(
@@ -71,11 +85,32 @@ fun AlbumViewTopBar(
contentDescription = stringResource(R.string.sort)
)
}
IconButton(onClick = onDeleteAlbum) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = stringResource(R.string.delete_album)
)
Box {
IconButton(onClick = { menuExpanded = true }, enabled = albumActionsEnabled) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(R.string.album_menu)
)
}
DropdownMenu(expanded = menuExpanded, onDismissRequest = { menuExpanded = false }) {
DropdownMenuItem(
text = { Text(stringResource(R.string.rename_album)) },
onClick = { menuExpanded = false; onRenameAlbum() }
)
if (onFilterAlbum != null) DropdownMenuItem(
text = { Text(stringResource(R.string.filter_album)) },
onClick = { menuExpanded = false; onFilterAlbum() }
)
DropdownMenuItem(
text = { Text(stringResource(R.string.refresh_album_folders)) },
enabled = hasFolders,
onClick = { menuExpanded = false; onRefreshFolders() }
)
DropdownMenuItem(
text = { Text(stringResource(R.string.delete_album)) },
onClick = { menuExpanded = false; onDeleteAlbum() }
)
}
}
}
}
@@ -1,17 +1,29 @@
package com.anthonyla.paperize.presentation.screens.album_view.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import coil3.compose.AsyncImage
import coil3.request.ImageRequest
import coil3.size.Size
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.presentation.common.components.SelectableGridCard
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
@@ -32,27 +44,56 @@ fun FolderItem(
onLongClick = onLongClick,
modifier = modifier
) {
Icon(
imageVector = Icons.Default.Folder,
contentDescription = null,
modifier = Modifier
.fillMaxSize(0.5f)
.align(Alignment.Center),
tint = if (isSelected) {
MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)
} else {
MaterialTheme.colorScheme.primary
}
)
Text(
text = folder.displayName,
style = MaterialTheme.typography.labelSmall,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
val coverUri = folder.coverUri
if (coverUri == null) {
Icon(
imageVector = Icons.Default.Folder,
contentDescription = null,
modifier = Modifier
.fillMaxSize(0.5f)
.align(Alignment.Center),
tint = if (isSelected) {
MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)
} else {
MaterialTheme.colorScheme.primary
}
)
} else {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(coverUri.toUri())
.size(Size(Constants.GRID_THUMBNAIL_WIDTH, Constants.GRID_THUMBNAIL_HEIGHT))
.build(),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
alpha = if (isSelected) 0.7f else 1f
)
}
Surface(
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(AppSpacing.small)
)
.fillMaxWidth()
) {
Row(
modifier = Modifier.padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall),
horizontalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Folder,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(16.dp)
)
Text(
text = folder.displayName,
style = MaterialTheme.typography.labelLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
}
}
@@ -1,96 +1,69 @@
package com.anthonyla.paperize.presentation.screens.album_view.components
import androidx.annotation.StringRes
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.anthonyla.paperize.R
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
import com.anthonyla.paperize.presentation.screens.album_view.ImportProgress
@Composable
fun ImportProgressDialog(progress: ImportProgress, onCancel: () -> Unit) {
val active = progress as? ImportProgress.Active ?: return
Dialog(
AlertDialog(
onDismissRequest = {},
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
) {
Surface(
shape = MaterialTheme.shapes.extraLarge,
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
when (active) {
is ImportProgress.Scanning -> {
Title(R.string.import_adding_folder)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
CircularProgressIndicator(modifier = Modifier.size(24.dp))
Text(
text = stringResource(R.string.import_scanning, active.found),
style = MaterialTheme.typography.bodyMedium
)
}
}
is ImportProgress.Saving -> {
Title(R.string.import_adding_wallpapers)
Text(
text = stringResource(R.string.import_saving, active.saved, active.total),
style = MaterialTheme.typography.bodyMedium
)
val fraction by animateFloatAsState(
targetValue = if (active.total > 0) active.saved.toFloat() / active.total else 0f,
label = "importProgress"
)
LinearProgressIndicator(
progress = { fraction },
modifier = Modifier
.fillMaxWidth()
.height(6.dp)
)
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false),
title = {
Text(
stringResource(
when (active) {
is ImportProgress.Scanning -> R.string.import_adding_folder
is ImportProgress.Saving -> R.string.import_adding_wallpapers
}
)
)
},
text = {
when (active) {
is ImportProgress.Scanning -> Row(
horizontalArrangement = Arrangement.spacedBy(AppSpacing.medium),
verticalAlignment = Alignment.CenterVertically
) {
CircularProgressIndicator(modifier = Modifier.size(24.dp))
Text(pluralStringResource(R.plurals.import_scanning, active.found, active.found))
}
TextButton(onClick = onCancel, modifier = Modifier.align(Alignment.End)) {
Text(stringResource(R.string.cancel))
is ImportProgress.Saving -> Column(verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)) {
Text(stringResource(R.string.import_saving, active.saved, active.total))
val fraction by animateFloatAsState(
targetValue = if (active.total > 0) active.saved.toFloat() / active.total else 0f,
label = "importProgress"
)
LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth())
}
}
},
confirmButton = {
TextButton(onClick = onCancel) {
Text(stringResource(R.string.cancel))
}
}
}
}
@Composable
private fun Title(@StringRes text: Int) {
Text(
text = stringResource(text),
style = MaterialTheme.typography.titleMedium
)
}
@@ -1,9 +1,11 @@
package com.anthonyla.paperize.presentation.screens.folder_view
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
@@ -11,9 +13,11 @@ import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -21,6 +25,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.res.stringResource
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -34,6 +39,10 @@ import com.anthonyla.paperize.presentation.common.components.SortOption
import com.anthonyla.paperize.presentation.common.components.WallpaperGrid
import com.anthonyla.paperize.presentation.common.components.WallpaperItem
import com.anthonyla.paperize.presentation.common.components.wallpaperGridItem
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
private const val REMOVED_HEADER_KEY = "removed"
private const val REMOVED_ALPHA = 0.5f
@Composable
fun FolderViewScreen(
@@ -52,9 +61,13 @@ fun FolderViewScreen(
var showSortSheet by rememberSaveable { mutableStateOf(false) }
var sortOption by rememberSaveable { mutableStateOf(SortOption.DATE_ADDED_DESC) }
val removedWallpapers = folder?.removedWallpapers.orEmpty()
val sortedWallpapers = remember(wallpapers, sortOption) {
wallpapers.sortedWith(sortOption.wallpaperComparator)
}
val sortedRemoved = remember(removedWallpapers, sortOption) {
removedWallpapers.sortedWith(sortOption.wallpaperComparator)
}
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
@@ -70,7 +83,7 @@ fun FolderViewScreen(
}
) { paddingValues ->
Box(modifier = modifier.fillMaxSize().padding(paddingValues)) {
if (folder != null && wallpapers.isEmpty()) {
if (folder != null && wallpapers.isEmpty() && removedWallpapers.isEmpty()) {
EmptyCollection(
title = stringResource(R.string.folder_empty_title),
hint = stringResource(R.string.folder_empty_hint)
@@ -91,6 +104,29 @@ fun FolderViewScreen(
modifier = Modifier.wallpaperGridItem(this)
)
}
if (sortedRemoved.isNotEmpty()) {
item(key = REMOVED_HEADER_KEY, span = { GridItemSpan(maxLineSpan) }) {
Column(modifier = Modifier.padding(top = AppSpacing.large)) {
Text(stringResource(R.string.removed_wallpapers), style = MaterialTheme.typography.titleSmall)
Text(
stringResource(R.string.removed_wallpapers_hint),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
items(items = sortedRemoved, key = { wallpaper -> wallpaper.id }) { wallpaper ->
WallpaperItem(
wallpaperUri = wallpaper.uri,
wallpaperName = wallpaper.displayFileName,
isSelected = false,
isSelectionMode = false,
onClick = { viewModel.restore(wallpaper) },
onLongClick = null,
modifier = Modifier.wallpaperGridItem(this).alpha(REMOVED_ALPHA)
)
}
}
}
}
if (isRefreshing) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
@@ -7,6 +7,7 @@ import androidx.navigation.toRoute
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.runCatchingCancellable
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.usecase.RefreshFolderUseCase
import com.anthonyla.paperize.presentation.common.launchBusy
@@ -17,11 +18,12 @@ import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
@HiltViewModel
class FolderViewViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
albumRepository: AlbumRepository,
private val albumRepository: AlbumRepository,
private val refreshFolderUseCase: RefreshFolderUseCase
) : ViewModel() {
@@ -48,4 +50,11 @@ class FolderViewViewModel @Inject constructor(
}
}
}
fun restore(wallpaper: Wallpaper) {
viewModelScope.launch {
runCatchingCancellable { albumRepository.restoreWallpaper(wallpaper) }
.onFailure { _message.value = R.string.restore_wallpaper_failed }
}
}
}
@@ -22,18 +22,24 @@ import androidx.compose.material.icons.outlined.Image
import androidx.compose.material.icons.outlined.PhotoLibrary
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
@@ -43,6 +49,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.R
import com.anthonyla.paperize.presentation.common.components.SnackbarMessageEffect
import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
import com.anthonyla.paperize.presentation.screens.wallpaper.WallpaperScreen
import com.anthonyla.paperize.service.livewallpaper.PaperizeLiveWallpaperService
@@ -72,16 +79,29 @@ fun HomeScreen(
val animate by viewModel.animate.collectAsStateWithLifecycle()
val wallpaperMode by viewModel.wallpaperMode.collectAsStateWithLifecycle()
val showLiveWallpaperPrompt by viewModel.showLiveWallpaperPrompt.collectAsStateWithLifecycle()
val currentHomeWallpaperUri by viewModel.currentHomeWallpaperUri.collectAsStateWithLifecycle()
val currentLockWallpaperUri by viewModel.currentLockWallpaperUri.collectAsStateWithLifecycle()
val currentHomeWallpaper by viewModel.currentHomeWallpaper.collectAsStateWithLifecycle()
val currentLockWallpaper by viewModel.currentLockWallpaper.collectAsStateWithLifecycle()
val removedWallpaper by viewModel.removedWallpaper.collectAsStateWithLifecycle()
val message by viewModel.message.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
SnackbarMessageEffect(message, snackbarHostState, viewModel::dismissMessage)
val removedText = stringResource(R.string.wallpaper_removed)
val undoText = stringResource(R.string.undo)
LaunchedEffect(removedWallpaper) {
val wallpaper = removedWallpaper ?: return@LaunchedEffect
val result = snackbarHostState.showSnackbar(removedText, undoText, duration = SnackbarDuration.Long)
if (result == SnackbarResult.ActionPerformed) viewModel.restoreWallpaper(wallpaper)
else viewModel.dismissRemovedWallpaper()
}
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
val pagerState = rememberPagerState { homeTabs.size }
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
topBar = {
CenterAlignedTopAppBar(
TopAppBar(
title = { Text(stringResource(R.string.app_name)) },
actions = {
IconButton(onClick = onNavigateToSettings) {
@@ -138,8 +158,9 @@ fun HomeScreen(
onUpdateScheduleSettings = viewModel::updateScheduleSettings,
onUpdateScheduleSettingsDebounced = viewModel::updateScheduleSettingsDebounced,
onChangeWallpaperNow = viewModel::changeWallpaperNow,
homeWallpaperUri = currentHomeWallpaperUri,
lockWallpaperUri = currentLockWallpaperUri
homeWallpaper = currentHomeWallpaper,
lockWallpaper = currentLockWallpaper,
onRemoveWallpaper = viewModel::removeCurrentWallpaper
)
}
}
@@ -9,6 +9,7 @@ import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.runCatchingCancellable
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.repository.WallpaperRepository
@@ -29,11 +30,12 @@ import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.launch
@HiltViewModel
class HomeViewModel @Inject constructor(
albumRepository: AlbumRepository,
private val albumRepository: AlbumRepository,
settingsRepository: SettingsRepository,
private val wallpaperRepository: WallpaperRepository,
private val createAlbumUseCase: CreateAlbumUseCase,
@@ -53,13 +55,20 @@ class HomeViewModel @Inject constructor(
settingsRepository.getWallpaperModeFlow().stateWhileSubscribed(viewModelScope, null)
/**
* URI of the wallpaper Paperize last applied for the home / lock screen, for the in-app preview.
* Wallpaper Paperize last applied for the home / lock screen, for the in-app preview.
* Reading the source URI (rather than WallpaperManager.getDrawable) avoids the storage permission
* the preview would otherwise need. Falls back to the BOTH-mode record when home/lock are synced.
*/
val currentHomeWallpaperUri: StateFlow<String?> = currentWallpaperUri(ScreenType.HOME) { it.homeAlbumId }
val currentHomeWallpaper: StateFlow<Wallpaper?> = currentWallpaper(ScreenType.HOME) { it.homeAlbumId }
val currentLockWallpaperUri: StateFlow<String?> = currentWallpaperUri(ScreenType.LOCK) { it.lockAlbumId }
val currentLockWallpaper: StateFlow<Wallpaper?> = currentWallpaper(ScreenType.LOCK) { it.lockAlbumId }
private val _removedWallpaper = MutableStateFlow<Wallpaper?>(null)
/** The last wallpaper removed from the preview, while its undo is offered. */
val removedWallpaper: StateFlow<Wallpaper?> = _removedWallpaper.asStateFlow()
private val _message = MutableStateFlow<Int?>(null)
val message: StateFlow<Int?> = _message.asStateFlow()
private val _showLiveWallpaperPrompt = MutableStateFlow(false)
val showLiveWallpaperPrompt: StateFlow<Boolean> = _showLiveWallpaperPrompt.asStateFlow()
@@ -76,7 +85,7 @@ class HomeViewModel @Inject constructor(
}
/** Creates the album and returns null, or returns the string resource of the error to show. */
suspend fun createAlbum(name: String): Int? = runCatchingCancellable { createAlbumUseCase(name) }.fold(
suspend fun createAlbum(name: String, isEncrypted: Boolean = false): Int? = runCatchingCancellable { createAlbumUseCase(name, isEncrypted) }.fold(
onSuccess = { created -> if (created) null else R.string.album_name_exists_error },
onFailure = { R.string.album_create_failed }
)
@@ -108,16 +117,47 @@ class HomeViewModel @Inject constructor(
fun changeWallpaperNow() = coordinator.changeWallpaperNow()
/** Removes [wallpaper] from its album and replaces it on every screen that shows it. */
fun removeCurrentWallpaper(wallpaper: Wallpaper) {
val home = currentHomeWallpaper.value?.id == wallpaper.id
val lock = currentLockWallpaper.value?.id == wallpaper.id
viewModelScope.launch {
runCatchingCancellable { albumRepository.removeWallpaper(wallpaper.id) }
.onSuccess { removed ->
if (removed == null) return@onSuccess
_removedWallpaper.value = removed
coordinator.changeWallpaperNow(
if (home && lock) ScreenType.BOTH else if (lock) ScreenType.LOCK else ScreenType.HOME
)
}
.onFailure { _message.value = R.string.remove_wallpaper_failed }
}
}
fun restoreWallpaper(wallpaper: Wallpaper) {
_removedWallpaper.value = null
viewModelScope.launch {
runCatchingCancellable { albumRepository.restoreWallpaper(wallpaper) }
.onFailure { _message.value = R.string.restore_wallpaper_failed }
}
}
fun dismissRemovedWallpaper() { _removedWallpaper.value = null }
fun dismissMessage() { _message.value = null }
@OptIn(ExperimentalCoroutinesApi::class)
private fun currentWallpaperUri(screen: ScreenType, albumId: (ScheduleSettings) -> String?): StateFlow<String?> =
private fun currentWallpaper(screen: ScreenType, albumId: (ScheduleSettings) -> String?): StateFlow<Wallpaper?> =
scheduleSettings
.map(albumId)
.distinctUntilChanged()
.flatMapLatest { id -> if (id == null) flowOf(null) else currentWallpaperUriFlow(id, screen) }
.flatMapLatest { id -> if (id == null) flowOf(null) else currentWallpaperFlow(id, screen) }
.stateWhileSubscribed(viewModelScope, null)
private fun currentWallpaperUriFlow(albumId: String, screen: ScreenType): Flow<String?> = combine(
private fun currentWallpaperFlow(albumId: String, screen: ScreenType): Flow<Wallpaper?> = combine(
wallpaperRepository.getCurrentWallpaperFlow(albumId, screen),
wallpaperRepository.getCurrentWallpaperFlow(albumId, ScreenType.BOTH)
) { specific, both -> (specific ?: both)?.uri }
) { specific, both -> specific ?: both }
// Removing the shown image drops its record until the replacement is applied.
.scan(null as Wallpaper?) { last, current -> current ?: last }
}
@@ -4,15 +4,13 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Icon
import androidx.compose.material3.LargeFloatingActionButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -28,7 +26,6 @@ import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.presentation.common.components.AddAlbumDialog
import com.anthonyla.paperize.presentation.common.components.EmptyCollection
import com.anthonyla.paperize.presentation.common.theme.AppGrid
import com.anthonyla.paperize.presentation.common.theme.AppIconSizes
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
import com.anthonyla.paperize.presentation.screens.library.components.AlbumItem
import kotlinx.coroutines.launch
@@ -38,7 +35,7 @@ import kotlinx.coroutines.launch
fun LibraryScreen(
albums: List<AlbumSummary>,
onViewAlbum: (String) -> Unit,
onCreateAlbum: suspend (String) -> Int?,
onCreateAlbum: suspend (String, Boolean) -> Int?,
modifier: Modifier = Modifier
) {
var showAddAlbumDialog by rememberSaveable { mutableStateOf(false) }
@@ -49,17 +46,8 @@ fun LibraryScreen(
Scaffold(
modifier = modifier.fillMaxSize(),
floatingActionButton = {
LargeFloatingActionButton(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary,
onClick = { showAddAlbumDialog = true },
shape = MaterialTheme.shapes.large
) {
Icon(
Icons.Filled.Add,
contentDescription = stringResource(R.string.add_album),
modifier = Modifier.size(AppIconSizes.medium)
)
FloatingActionButton(onClick = { showAddAlbumDialog = true }) {
Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_album))
}
}
) { paddingValues ->
@@ -75,14 +63,14 @@ fun LibraryScreen(
.fillMaxSize()
.padding(paddingValues),
columns = GridCells.Adaptive(AppGrid.itemMinSize),
contentPadding = PaddingValues(AppSpacing.gridPadding),
horizontalArrangement = Arrangement.Start
contentPadding = PaddingValues(AppSpacing.medium),
horizontalArrangement = Arrangement.spacedBy(AppSpacing.medium),
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
items(albums, key = { album -> album.id }) { album ->
AlbumItem(
album = album,
onAlbumViewClick = { onViewAlbum(album.id) },
modifier = Modifier.padding(AppSpacing.gridPadding)
onAlbumViewClick = { onViewAlbum(album.id) }
)
}
}
@@ -95,12 +83,12 @@ fun LibraryScreen(
showAddAlbumDialog = false
albumNameError = null
},
onConfirm = { name ->
onConfirm = { name, isEncrypted ->
isSaving = true
albumNameError = null
scope.launch {
try {
albumNameError = onCreateAlbum(name)
albumNameError = onCreateAlbum(name, isEncrypted)
if (albumNameError == null) showAddAlbumDialog = false
} finally {
isSaving = false
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more