Compare commits

..
114 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
Anthonyy232 df5985f3d6 chore: release v4.2.2 2026-11-10 23:44:16 -08:00
Anthonyy232 e4e19faa24 chore: update the build plugins and dependencies
AGP 9.5.1, Kotlin plugins 2.4.21, Compose BOM 2026.09.00, material3
1.5.0-rc01, DataStore 1.3.0, WorkManager 2.12.0, serialization 1.12.0,
mockk 1.14.12 and zoomable 2.16.0.
2026-11-10 23:40:10 -08:00
Anthonyy232 e41920b65f chore: drop the redundant v26 qualifier from the launcher icon folder
minSdk is 31, so the qualifier never selects anything.
2026-11-10 23:35:43 -08:00
Anthonyy232 c21f9d11df refactor: drop code the platform and libraries already provide
- decode wallpapers with ImageDecoder only; the BitmapFactory and manual EXIF fallback could not be needed at minSdk 31
- remove BootReceiver: WorkManager reschedules periodic work after reboot
- replace the in-process reload broadcast with a shared flow
- remove the Room enum converter; Room stores enums by name
- stop importing SVG, which neither apply path can decode, and drop coil-svg
- remove the unused special-use foreground service permission
2026-11-10 15:12:40 -08:00
Anthonyy232 d2ffa9745b refactor: merge duplicated dialogs, switch rows, comparators and settings lookups
One ConfirmDialog, SettingSwitchRow, launchBusy and sort comparator replace their copies. ScheduleSettings gains albumId(screen) and isRotating(mode). CreateAlbumUseCase is now the only owner of the duplicate-name rule (case-insensitive, as the user already saw); the unused name query is gone. TimeIntervalPicker splits durations with kotlin.time.
2026-11-10 15:12:40 -08:00
Anthonyy232 d6bd404add refactor: move test fixtures and test-only queries out of main
The empty() model factories and four DAO methods were only called by tests. Fixtures now live in a source dir shared by unit and instrumented tests.
2026-11-10 12:25:33 -08:00
Anthonyy232 b3c2264bd3 fix: hide shuffle and adaptive brightness descriptions whenever enabled
They depended on the unrelated individual scheduling switch; the other toggles hide the description when on.
2026-11-10 12:25:33 -08:00
Anthonyy232 11724d99d3 refactor: use the SliderState slider overload
The value overload is deprecated in material3 1.5; this is what it did internally.
2026-11-10 12:25:33 -08:00
Anthonyy232 4e05b62d6e fix: load one live wallpaper at start and redraw on theme change
The engine requested a wallpaper in onCreate and again on the first settings emission, consuming two queue items. Adaptive brightness now gets a new frame when dark mode changes while visible.

Also drops the reload throttle, which only the album switch used, the renderer teardown that could never run because the surface is destroyed before the engine, and the catch that silently ended settings observation.
2026-11-10 08:25:05 -08:00
Anthonyy232 2044748e20 fix: stop the library tab padding system bars twice
The nested Scaffold re-applied the insets the home Scaffold had already padded, on edge-to-edge devices.
2026-11-10 08:25:05 -08:00
Anthonyy232 97dc38bbfb test: cut tests that cannot fail and tighten weak ones
- Remove tests that repeat another test, only verify a one-line delegate,
  compare a helper with itself, or exercise the platform.
- Make the EXIF rotation, lock interval validation, partial import and
  render selection tests fail when the behaviour breaks.
- Round-trip every schedule setting through the settings repository.
2026-11-10 02:47:40 -08:00
Anthonyy232 d169b84430 refactor: untangle the UI, remove the dead sort screen and trim leftovers
Dead code
- Remove the manual sort screen, unreachable since sorting moved into the
  album screen, with its route, strings, reorder repository/DAO methods and
  the reorderable dependency.
- Remove unused parameters, defaults, typography styles and constants.

UI
- Share the settings card, selectable grid card, wallpaper grid, back top
  bar, album cover, snackbar effect and onboarding button instead of
  keeping copies per screen; move shared pieces to common/components.
- HomeViewModel owns the duplicate album name rule and exposes only the
  animate flag; WallpaperViewViewModel exposes its own route arguments.
- The wallpaper viewer title shows the decoded file name.
- The empty library uses the same empty state as albums and folders.

Data and services
- Keep document-provider scanning next to AndroidDocumentSource and return
  SourceImage directly.
- Define preference keys where they are used; query the current wallpaper
  once.
- Use runCatchingCancellable for the remaining hand-written rethrows.

Live wallpaper
- Draw the crossfade without the always-opaque alpha helper and drop
  redundant program binds, guards and dead stores.
- Stop checking GL errors after deletes, which threw stale errors from
  cleanup and leaked tiles.
- A crashed GL thread refuses queued events instead of holding them.
2026-11-10 02:47:40 -08:00
renovate[bot] f153eebc71 fix(deps): update dependency androidx.compose.material3:material3 to v1.5.0-beta01 (#643)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-10-21 22:24:08 +00:00
259 changed files with 15295 additions and 5331 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.
-139
View File
@@ -1,139 +0,0 @@
## 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, TIFF, and SVG
- **Folder Support** — Organize wallpapers into folders for auto-updating
- **Dual Screen Support** — Choose the same or separate albums for home and lock screen
- **Wallpaper Effects** — Apply various effects including brightness, blur, scaling, vignette, and more
- **On-Device Storage** — All wallpapers and settings stored locally on your device
An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and every hour while a schedule is running, so new files join the rotation and deleted ones leave it by themselves; **Refresh folder** rescans one straight away. Open an album's options menu to rename or delete it, filter it (encrypted albums), or rescan all its folders. Removing something from an album never touches the file on your device.
---
When creating an album, you can mark it encrypted; this choice is permanent and imports only `.jpg_enc` files made by wallpaper_changer. Set the same passphrase in **Settings → Encrypted albums**. **Filter wallpapers** in the album menu takes a regular expression matched (ignoring case) against each line of the folder's `naming_table.enc` (`name;encrypted file;hash`), as wallpaper_changer does; every image is imported but only matching ones are picked as wallpaper, and images in folders without a naming table never match. It is protected by Android Keystore and remains available for scheduled changes. Encrypted previews are off by default; enabling them decrypts images in memory without caching them to disk. Turning previews off removes them from the app's display. Android may still retain the applied wallpaper, and wallpaper_changer's encryption format does not authenticate its contents.
## Download
Supported formats: JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF and TIFF.
[<img src="https://github.com/Anthonyy232/Paperize/assets/60626873/1c034414-21cd-4a0a-838d-89fe7bd56910" alt="Download from GitHub" height="60">](https://github.com/Anthonyy232/Paperize/releases)
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="60">](https://f-droid.org/en/packages/com.anthonyla.paperize/)
[<img src="https://gitlab.com/IzzyOnDroid/repo/-/raw/master/assets/IzzyOnDroid.png" alt="Get it on IzzyOnDroid" height="60">](https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize)
<picture>
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-schedule-dark.png">
<img src=".github/readme/feature-schedule-light.png" alt="02. Home and lock, your call. The wallpaper tab with the current lock and home wallpapers, an album for each, and the time interval.">
</picture>
---
Turn on **Lock**, **Home** or both and pick an album for each. One interval covers both screens, from 15 minutes to 30 days; **Individual Scheduling** gives each screen its own. Wallpapers go in order unless **Shuffle** is on. Tired of the one on screen? Tap the bin under it in **Current Wallpapers** to take it out of its album and move on to the next. An image removed from a folder stays out when the folder is rescanned, and tapping it under **Removed** in that folder puts it back.
## Localization
<picture>
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-effects-dark.png">
<img src=".github/readme/feature-effects-light.png" alt="03. Effects, to taste. Brightness, blur and vignette, each with a switch for home and lock and a strength slider.">
</picture>
Help translate Paperize into your language! Currently, most translations are provided using machine translation — contributions from native speakers are greatly appreciated.
Brightness, blur, vignette and a gray filter each have a strength slider and separate switches for home and lock. **Adaptive Brightness** adjusts the wallpaper to the system's light or dark mode. Scaling is Fill, Fit, Stretch or None. **Blurred background** fills the space around a Fit wallpaper with a blurred copy of it instead of black, and **Horizontal scrolling** lets a wide Fill wallpaper move between home-screen pages.
**[Contribute on Crowdin →](https://crowdin.com/project/paperize/invite?h=d8d7a7513d2beb0c96ba9b2a5f85473e2084922)**
## How it works
---
1. On first launch, choose **Static Mode** or **Live Wallpaper Mode**.
2. In **Library**, tap **+** to create an album, then add images or a folder to it.
3. In **Wallpaper**, choose the screens and their albums, and set the time interval.
4. Leave the rest to Paperize. **Wallpaper changing** pauses and resumes the schedule without clearing your albums.
## Tech Stack
To skip ahead, use **Change wallpaper now** in the app, the Quick Settings tile, or the shortcut you get by long-pressing the app icon. In static mode you can also open any image in an album and set it as the wallpaper yourself. Tick **Continue rotation from here** to have the rotation carry on from that image; it is off by default and hidden while **Shuffle** is on.
| Category | Technology |
|----------|------------|
| **Language** | [Kotlin](https://kotlinlang.org/) |
| **UI Framework** | [Jetpack Compose](https://developer.android.com/develop/ui/compose) |
| **Design System** | [Material 3](https://m3.material.io/) |
| **Dependency Injection** | [Dagger Hilt](https://dagger.dev/hilt/) |
| **Database** | [Room](https://developer.android.com/training/data-storage/room) |
| **Image Loading** | [Coil](https://coil-kt.github.io/coil/) |
## 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, reordering, removal, covers,
and queue invalidation use Room transactions; provider scans run outside them.
- `DocumentSource` and `WallpaperRenderer` (domain interfaces, Android implementations in
`data/source`) keep use cases free of document-provider and bitmap-decoding details.
- `WallpaperRepository` owns rotation queues and current-wallpaper records.
Queue creation checks and writes in one transaction, including synchronized screens.
Static changes and the live wallpaper engine both dequeue through
`ChangeWallpaperUseCase.dequeueNext`.
- `WallpaperController` shares static wallpaper application between the service
and worker. Callers hold `WallpaperChangeLock` through application and schedule
updates. The controller recycles applied bitmaps.
- `SettingsCoordinator` persists wallpaper settings edits and applies their side effects
(schedules, queues, immediate changes) one at a time; ViewModels only hold UI state.
`WallpaperChangeService` helpers are the single way to start a manual change.
- Repositories and use cases throw on failure. ViewModels, services, and workers
catch at the edge, using `runCatchingCancellable` where they need a `Result`, so
coroutine cancellation always propagates. Progress belongs to UI state.
- Room migrations preserve versions 1–3 when upgrading to version 4. New schema
changes must include a migration; destructive fallback is disabled.
- **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.
+23 -8
View File
@@ -14,7 +14,9 @@ ksp {
android {
namespace = "com.anthonyla.paperize"
compileSdk = 37
compileSdk {
version = release(37) { minorApiLevel = 2 }
}
signingConfigs {
create("release") {
@@ -29,13 +31,16 @@ android {
}
sourceSets.getByName("androidTest").assets.directories.add("$projectDir/schemas")
listOf("test", "androidTest").forEach {
sourceSets.getByName(it).kotlin.directories.add("$projectDir/src/sharedTest/java")
}
defaultConfig {
applicationId = "com.anthonyla.paperize"
minSdk = 31
targetSdk = 36
versionCode = 58
versionName = "4.2.1"
targetSdk = 37
versionCode = 61
versionName = "4.3.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
@@ -70,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
@@ -79,6 +95,7 @@ android {
kotlin {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_17)
allWarningsAsErrors = true
}
}
@@ -90,13 +107,11 @@ 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)
implementation(libs.coil.compose)
implementation(libs.coil.gif)
implementation(libs.coil.svg)
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.material.icons.extended)
implementation(libs.androidx.hilt.navigation.compose)
@@ -104,19 +119,19 @@ dependencies {
implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.documentfile)
implementation(libs.androidx.exifinterface)
implementation(libs.zoomable)
implementation(libs.androidx.work.runtime.ktx)
implementation(libs.androidx.hilt.work)
implementation(libs.androidx.foundation)
implementation(libs.androidx.profileinstaller)
implementation(libs.reorderable)
lintChecks(libs.compose.lint.checks)
testImplementation(libs.junit)
testImplementation(libs.mockk)
testImplementation(libs.kotlinx.coroutines.test)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(libs.androidx.exifinterface)
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(platform(libs.androidx.compose.bom))
debugImplementation(libs.androidx.ui.tooling)
+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')"
]
}
}
@@ -18,6 +18,8 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import com.anthonyla.paperize.data.database.PaperizeDatabase
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
import com.anthonyla.paperize.data.source.isDocumentMissing
import com.anthonyla.paperize.data.source.scanFolderImages
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@@ -70,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)
@@ -89,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().lastModified)
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 {
@@ -104,7 +145,7 @@ class DocumentAccessInstrumentedTest {
} else null
}
try {
treeUri.scanFolderImages(context)
treeUri.scanFolderImages(context, false)
fail("Expected child folder failure")
} catch (_: java.io.IOException) { }
}
@@ -118,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()
@@ -133,7 +174,7 @@ class DocumentAccessInstrumentedTest {
val uri = documentUri.toString()
val missing = WallpaperEntity("first", "one", null, uri, "photo.png", 0L)
db.wallpaperDao().insertWallpapers((0..504).map { missing.copy(id = "missing-$it") })
db.wallpaperDao().insertWallpaper(missing.copy(id = "other-album", albumId = "two"))
db.wallpaperDao().insertWallpapers(listOf(missing.copy(id = "other-album", albumId = "two")))
provider.answer = {
if (provider.queries == 1) {
// Move an unread image before the first page while that page is being scanned.
@@ -144,7 +185,7 @@ class DocumentAccessInstrumentedTest {
val repository = com.anthonyla.paperize.data.repository.AlbumRepositoryImpl(
com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db)
assertEquals(505, repository.pruneMissingEntries("one"))
assertEquals(0, db.wallpaperDao().getWallpaperCountByAlbum("one"))
assertEquals(0, db.wallpaperDao().getWallpaperIdsByAlbum("one").size)
assertNull(db.albumDao().getAlbumById("one")?.coverUri)
assertNotNull(db.wallpaperDao().getWallpaperById("other-album"))
} finally { db.close() }
@@ -167,7 +208,7 @@ class DocumentAccessInstrumentedTest {
repository.pruneMissingEntries("album")
fail("Expected cancellation")
} catch (_: kotlinx.coroutines.CancellationException) { }
assertEquals(2, db.wallpaperDao().getWallpaperCountByAlbum("album"))
assertEquals(2, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
assertEquals("content://test/document/first", db.albumDao().getAlbumById("album")?.coverUri)
} finally { db.close() }
}
@@ -1,13 +1,8 @@
package com.anthonyla.paperize.core.util
import android.app.WallpaperManager
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Color
import android.hardware.display.DisplayManager
import android.net.Uri
import android.os.Build
import android.os.SystemClock
import androidx.exifinterface.media.ExifInterface
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -18,7 +13,6 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
@@ -70,9 +64,12 @@ class WallpaperUtilInstrumentedTest {
wallpaperUri = Uri.fromFile(image),
width = 20,
height = 40,
scaling = ScalingType.STRETCH
scaling = ScalingType.FILL,
preserveSourceOverflow = true
)
// Rotated, the 20x40 source covers the canvas at scale 1. Unrotated, the 40x20 source
// would need scale 2 to cover the height and come back 80x40.
assertNotNull(result)
assertEquals(20, result?.width)
assertEquals(40, result?.height)
@@ -153,39 +150,35 @@ class WallpaperUtilInstrumentedTest {
}
@Test
fun android17FoldableSizingIncludesInactiveBuiltInPanel() {
assumeTrue(Build.VERSION.SDK_INT >= 37)
val displayManager = context.getSystemService(DisplayManager::class.java)
val builtInDisplays = displayManager.getDisplays(
"android.hardware.display.category.BUILT_IN_DISPLAYS"
)
assertTrue("Expected both foldable panels", builtInDisplays.size >= 2)
val expected = selectLargestDisplayDimensions(
builtInDisplays.flatMap { display ->
display.supportedModes.map { mode ->
mode.physicalWidth to mode.physicalHeight
}
}
)
val actual = getDeviceScreenSize(context)
assertNotNull(expected)
assertEquals(expected?.first, actual.width)
assertEquals(expected?.second, actual.height)
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 staticRenderSizeDoesNotRotateWithForegroundAppConfiguration() {
val landscapeConfiguration = Configuration(context.resources.configuration).apply {
orientation = Configuration.ORIENTATION_LANDSCAPE
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()
}
val landscapeContext = context.createConfigurationContext(landscapeConfiguration)
val naturalPanel = getDeviceScreenSize(context)
val renderSize = getDeviceScreenSize(landscapeContext)
assertEquals(naturalPanel.width, renderSize.width)
assertEquals(naturalPanel.height, renderSize.height)
}
@Test
@@ -271,55 +264,6 @@ class WallpaperUtilInstrumentedTest {
result.recycle()
}
@Test
fun staticWallpaperChangesRefreshAospWallpaperColors() {
assumeTrue(
"Wallpaper color extraction test is destructive and must run only on an emulator",
Build.FINGERPRINT.contains("/emu") ||
Build.FINGERPRINT.contains("generic") ||
Build.MODEL.contains("Emulator", ignoreCase = true) ||
Build.MODEL.contains("sdk", ignoreCase = true)
)
val wallpaperManager = WallpaperManager.getInstance(context)
val red = mutableBitmap(256, 256, Color.rgb(230, 20, 20))
val blue = mutableBitmap(256, 256, Color.rgb(20, 20, 230))
try {
wallpaperManager.setBitmapChecked(red, WallpaperManager.FLAG_SYSTEM)
val redPrimary = awaitPrimaryWallpaperColor(wallpaperManager) { color ->
Color.red(color) > Color.blue(color) * 2
}
wallpaperManager.setBitmapChecked(blue, WallpaperManager.FLAG_SYSTEM)
val bluePrimary = awaitPrimaryWallpaperColor(wallpaperManager) { color ->
Color.blue(color) > Color.red(color) * 2
}
assertTrue(Color.red(redPrimary) > Color.blue(redPrimary))
assertTrue(Color.blue(bluePrimary) > Color.red(bluePrimary))
} finally {
red.recycle()
blue.recycle()
}
}
private fun awaitPrimaryWallpaperColor(
wallpaperManager: WallpaperManager,
predicate: (Int) -> Boolean
): Int {
val deadline = SystemClock.uptimeMillis() + 10_000L
var lastColor: Int? = null
while (SystemClock.uptimeMillis() < deadline) {
lastColor = wallpaperManager
.getWallpaperColors(WallpaperManager.FLAG_SYSTEM)
?.primaryColor
?.toArgb()
if (lastColor != null && predicate(lastColor)) return lastColor
SystemClock.sleep(100L)
}
throw AssertionError("Wallpaper colors did not refresh; last primary color was $lastColor")
}
private fun mutableBitmap(width: Int, height: Int, color: Int): Bitmap =
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply {
eraseColor(color)
@@ -6,6 +6,7 @@ import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.platform.app.InstrumentationRegistry
import com.anthonyla.paperize.core.ScreenType
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
import org.junit.Assert.*
@@ -15,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 {
@@ -25,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)
@@ -32,7 +34,8 @@ class LibraryMigrationInstrumentedTest {
assertEquals(42L, image.addedAt)
assertEquals("content://image", db.folderDao().getFolderById("folder")?.coverUri)
assertEquals(listOf("image"), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
assertEquals(if (version >= 3) "image" else null, db.wallpaperCurrentDao().getCurrentWallpaper("album", ScreenType.HOME)?.id)
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"))
@@ -42,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")
@@ -56,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")
@@ -1,5 +1,7 @@
package com.anthonyla.paperize.data.repository
import com.anthonyla.paperize.testFolder
import com.anthonyla.paperize.testWallpaper
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
@@ -9,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
@@ -24,15 +29,36 @@ 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 = Folder.empty("folder", "album").copy(
wallpapers = (0..599).map { Wallpaper.empty("image-$it", "album").copy(folderId = "folder", uri = "content://image-$it") }
val folder = testFolder("folder", "album").copy(
wallpapers = (0..599).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://image-$it") }
)
try {
albums.addFolderToAlbum("album", folder) { saved, _ ->
@@ -40,29 +66,29 @@ class AlbumRepositoryInstrumentedTest {
}
fail("Expected cancellation")
} catch (_: CancellationException) { }
assertEquals(0, db.wallpaperDao().getWallpaperCountByAlbum("album"))
assertEquals(0, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
assertNull(db.folderDao().getFolderWithWallpapers("folder").first())
assertNull(db.albumDao().getAlbumById("album")?.coverUri)
}
@Test fun importingImagesUpdatesCoverAndRotationQueueTogether() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val first = Wallpaper.empty("first", "album").copy(uri = "content://first")
db.wallpaperDao().insertWallpaper(first.toEntity())
val first = testWallpaper("first", "album").copy(uri = "content://first")
db.wallpaperDao().insertWallpapers(listOf(first.toEntity()))
db.wallpaperQueueDao().rebuildQueue("album", ScreenType.HOME, listOf("first"))
db.folderDao().insertFolder(Folder.empty("folder", "album").toEntity())
db.folderDao().insertFolder(testFolder("folder", "album").toEntity())
val second = first.copy(id = "second", uri = "content://second", folderId = "folder")
assertEquals(1, albums.addWallpapersToAlbum("album", listOf(second)))
assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
assertEquals(2, db.wallpaperDao().getWallpaperCountByAlbum("album"))
assertEquals(2, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
assertEquals("content://second", db.folderDao().getFolderById("folder")?.coverUri)
}
@Test fun removingCoverUsesOnlyWallpapersFromThatAlbum() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("one", "One", "content://shared"))
db.albumDao().insertAlbum(AlbumEntity("two", "Two", "content://shared"))
val cover = Wallpaper.empty("cover", "one").copy(uri = "content://shared")
val cover = testWallpaper("cover", "one").copy(uri = "content://shared")
val replacement = cover.copy(id = "replacement", uri = "content://replacement", displayOrder = 1)
db.wallpaperDao().insertWallpapers(listOf(cover, replacement, cover.copy(id = "other", albumId = "two")).map { it.toEntity() })
@@ -74,8 +100,8 @@ class AlbumRepositoryInstrumentedTest {
@Test fun coverRefreshUsesDisplayOrderAndClearsEmptyFolders() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
db.folderDao().insertFolder(Folder.empty("folder", "album").toEntity())
val later = Wallpaper.empty("later", "album").copy(folderId = "folder", uri = "content://later", displayOrder = 9)
db.folderDao().insertFolder(testFolder("folder", "album").toEntity())
val later = testWallpaper("later", "album").copy(folderId = "folder", uri = "content://later", displayOrder = 9)
val first = later.copy(id = "first", uri = "content://first", displayOrder = 1)
val direct = later.copy(id = "direct", folderId = null, uri = "content://direct", displayOrder = 99)
db.wallpaperDao().insertWallpapers(listOf(later, first, direct).map { it.toEntity() })
@@ -84,60 +110,46 @@ class AlbumRepositoryInstrumentedTest {
assertEquals("content://first", db.folderDao().getFolderById("folder")?.coverUri)
assertEquals("content://direct", db.wallpaperDao().getAlbumCoverUri("album"))
db.wallpaperDao().deleteWallpapersByFolder("folder")
db.wallpaperDao().deleteAlbumWallpapers("album", listOf("later", "first"))
db.folderDao().refreshFolderCovers("album")
assertNull(db.folderDao().getFolderById("folder")?.coverUri)
}
@Test fun concurrentImportsDeduplicateInsideTheTransaction() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val image = Wallpaper.empty("one", "album").copy(uri = "content://same")
val image = testWallpaper("one", "album").copy(uri = "content://same")
val first = async(Dispatchers.IO) { albums.addWallpapersToAlbum("album", listOf(image)) }
val second = async(Dispatchers.IO) { albums.addWallpapersToAlbum("album", listOf(image.copy(id = "two"))) }
assertEquals(1, first.await() + second.await())
assertEquals(1, db.wallpaperDao().getWallpaperCountByAlbum("album"))
assertEquals(1, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
db.folderDao().insertFolder(Folder.empty("folder", "album").toEntity())
db.folderDao().insertFolder(testFolder("folder", "album").toEntity())
assertEquals(1, albums.addWallpapersToAlbum("album", listOf(image.copy(id = "folder-image", folderId = "folder"))))
db.folderDao().deleteFolderById("folder")
db.folderDao().deleteAlbumFolder("album", "folder")
assertEquals(0, albums.addWallpapersToAlbum("album", listOf(image.copy(id = "stale", folderId = "folder"))))
}
@Test fun reorderPersistsNestedImagesWithoutOverwritingMetadata() = runBlocking {
@Test fun continuingFromAPickedWallpaperFollowsAlbumOrderAndWraps() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val first = Wallpaper.empty("first", "album").copy(uri = "content://first", folderId = "folder")
val second = first.copy(id = "second", uri = "content://second")
val folder = Folder.empty("folder", "album").copy(wallpapers = listOf(first, second))
albums.addFolderToAlbum("album", folder)
wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, false)
db.wallpaperDao().updateWallpaper(first.copy(fileName = "new-name.jpg").toEntity())
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
albums.reorderAlbum("album", listOf(folder.copy(wallpapers = listOf(second, first))), emptyList())
assertEquals(listOf("second", "first"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
assertEquals("new-name.jpg", db.wallpaperDao().getWallpaperById("first")?.fileName)
assertEquals("content://second", db.folderDao().getFolderById("folder")?.coverUri)
assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
}
change.completeSpecific("album", ScreenType.HOME, "3", shuffle = false, startSequenceHere = true)
assertEquals(listOf("4", "5", "1"), List(3) { next() })
@Test fun failedReorderRollsBackEarlierRowsAndPreservesQueue() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val first = Wallpaper.empty("first", "album").copy(uri = "content://first")
val second = first.copy(id = "second", uri = "content://second")
albums.addWallpapersToAlbum("album", listOf(first, second))
wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, false)
db.openHelper.writableDatabase.execSQL("""
CREATE TRIGGER reject_order BEFORE UPDATE OF displayOrder ON wallpapers
WHEN NEW.id = 'first' BEGIN SELECT RAISE(ABORT, 'test write failure'); END
""")
assertTrue(runCatching { albums.reorderAlbum("album", emptyList(), listOf(second, first)) }.isFailure)
assertEquals(listOf("first", "second"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
assertEquals(listOf("first", "second"), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
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 {
Wallpaper.empty("image-$it", "album").copy(uri = "content://image-$it")
testWallpaper("image-$it", "album").copy(uri = "content://image-$it")
})
val home = async(Dispatchers.IO) { wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, true) }
val lock = async(Dispatchers.IO) { wallpapers.ensureWallpaperQueue("album", ScreenType.LOCK, true) }
@@ -149,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()
@@ -48,14 +61,25 @@ class SettingsRepositoryInstrumentedTest {
enableVignette = true, vignettePercentage = 40, enableGrayscale = true, grayscalePercentage = 50,
enableDoubleTap = true, enableChangeOnScreenOff = true, enableParallax = true, parallaxIntensity = 60
)
preferences.updateScheduleSettings(ScheduleSettings(
// Each screen gets distinct effects so a cross-screen key swap cannot round-trip.
val lockEffects = effects.copy(
blurPercentage = 31, darkenPercentage = 21, vignettePercentage = 41, grayscalePercentage = 51,
enableVignette = false, enableDoubleTap = false, parallaxIntensity = 61
)
val liveEffects = effects.copy(
blurPercentage = 32, darkenPercentage = 22, vignettePercentage = 42, grayscalePercentage = 52,
enableGrayscale = false, enableChangeOnScreenOff = false, parallaxIntensity = 62
)
val full = ScheduleSettings(
enableChanger = true, separateSchedules = true, shuffleEnabled = true,
homeEnabled = true, lockEnabled = true, homeAlbumId = "home", lockAlbumId = "lock", liveAlbumId = "live",
homeIntervalMinutes = 25, lockIntervalMinutes = 35, liveIntervalMinutes = 45,
homeScalingType = ScalingType.FIT, lockScalingType = ScalingType.STRETCH, liveScalingType = ScalingType.NONE,
homeScrollingEnabled = true, homeEffects = effects, lockEffects = effects, liveEffects = effects,
homeScrollingEnabled = true, blurFitBackground = true, homeEffects = effects, lockEffects = lockEffects, liveEffects = liveEffects,
adaptiveBrightness = true
))
)
preferences.updateScheduleSettings(full)
assertEquals(full, preferences.getScheduleSettings())
preferences.clearScheduleSettings()
assertEquals(ScheduleSettings(), preferences.getScheduleSettings())
assertEquals(appearance, preferences.getAppSettings())
@@ -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)
}
}
@@ -1,5 +1,7 @@
package com.anthonyla.paperize.domain.model
import com.anthonyla.paperize.testFolder
import com.anthonyla.paperize.testWallpaper
import org.junit.Assert.assertEquals
import org.junit.Test
@@ -11,8 +13,8 @@ class DisplayNameInstrumentedTest {
"Pictures/Summer+Sun.jpg" to "Summer+Sun.jpg",
"" to ""
).forEach { (stored, displayed) ->
assertEquals(displayed, Folder.empty().copy(name = stored).displayName)
assertEquals(displayed, Wallpaper.empty().copy(fileName = stored).displayFileName)
assertEquals(displayed, testFolder().copy(name = stored).displayName)
assertEquals(displayed, testWallpaper().copy(fileName = stored).displayFileName)
}
}
}
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.presentation
import com.anthonyla.paperize.testAlbumSummary
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
@@ -17,21 +18,20 @@ import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.test.core.app.ApplicationProvider
import com.anthonyla.paperize.R
import com.anthonyla.paperize.presentation.common.theme.PaperizeTheme
import com.anthonyla.paperize.presentation.screens.album_view.components.SortBottomSheet
import com.anthonyla.paperize.presentation.screens.album_view.components.SortOption
import com.anthonyla.paperize.presentation.screens.album_view.components.WallpaperItem
import com.anthonyla.paperize.presentation.common.components.SortBottomSheet
import com.anthonyla.paperize.presentation.common.components.SortOption
import com.anthonyla.paperize.presentation.common.components.WallpaperItem
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
import com.anthonyla.paperize.presentation.screens.album_view.components.AlbumViewTopBar
import kotlinx.coroutines.CompletableDeferred
import androidx.compose.ui.semantics.SemanticsActions
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.model.WallpaperEffects
import com.anthonyla.paperize.presentation.screens.wallpaper.WallpaperScreen
@@ -53,11 +53,11 @@ class AlbumUiInstrumentedTest {
PaperizeTheme(false, false) {
WallpaperScreen(
albums = emptyList(), persistedScheduleSettings = settings.value,
appSettings = AppSettings(), wallpaperMode = mode.value,
animate = true, wallpaperMode = mode.value,
onToggleChanger = {}, onSelectAlbum = { _, _ -> },
onUpdateScheduleSettings = { latest = it },
onUpdateScheduleSettingsDebounced = { latest = it },
onChangeWallpaperNow = {}, homeWallpaperUri = null, lockWallpaperUri = null
onChangeWallpaperNow = {}, homeWallpaper = null, lockWallpaper = null, onRemoveWallpaper = {}
)
}
}
@@ -89,22 +89,23 @@ class AlbumUiInstrumentedTest {
}
@Test fun failedAlbumCreationKeepsNameAndAllowsRetryAfterPendingSave() {
val pending = CompletableDeferred<Result<Album>>()
val pending = CompletableDeferred<Int?>()
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 Result.success(Album.empty(id = "album", name = name))
if (attempts == 1) pending.await() else null
})
}
}
compose.onNodeWithContentDescription(context.getString(R.string.add_album)).performClick()
compose.onNodeWithText(context.getString(R.string.album_name)).performTextInput("Mountains")
compose.onNodeWithText(context.getString(R.string.encrypted_album)).performClick()
compose.onNodeWithText(context.getString(R.string.save)).performClick().assertIsNotEnabled()
compose.runOnIdle { pending.complete(Result.failure(IllegalStateException("Storage unavailable"))) }
compose.runOnIdle { pending.complete(R.string.album_create_failed) }
compose.onNodeWithText(context.getString(R.string.album_create_failed)).assertIsDisplayed()
compose.onNodeWithText(context.getString(R.string.album_name)).assertTextContains("Mountains")
compose.onNodeWithText(context.getString(R.string.save)).performClick()
@@ -112,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
@@ -144,7 +172,7 @@ class AlbumUiInstrumentedTest {
try {
compose.setContent {
PaperizeTheme(false, false) {
AlbumItem(AlbumSummary.empty("album").copy(name = "Cover", coverUri = uri.value), {}, Modifier.size(180.dp))
AlbumItem(testAlbumSummary("album").copy(name = "Cover", coverUri = uri.value), {}, Modifier.size(180.dp))
}
}
fun centerColor(): Int {
@@ -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
@@ -102,7 +103,7 @@ class LiveWallpaperShaderInstrumentedTest {
}
@Test
fun rendererDrawsTheFinalCrossfadeFrameAndRejectsSupersededUploads() {
fun rendererSurvivesSupersededUploadsCrossfadeResizeAndContextLoss() {
val app = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
val uploads = java.util.concurrent.LinkedBlockingQueue<() -> Unit>()
var renderRequests = 0
@@ -165,24 +166,78 @@ class LiveWallpaperShaderInstrumentedTest {
assertTrue(Color.green(readPixel(SIZE / 2, SIZE / 2)) <= 2)
GLUtil.checkGLError("recreated wallpaper surface")
} finally {
renderer.destroy()
renderer.cancelLoading()
file.delete()
replacement.delete()
}
}
@Test
fun everyLiveWallpaperShaderCompilesAndLinksOnDevice() {
listOf(
GLShaders.BLUR_FRAGMENT_SHADER,
GLShaders.EFFECTS_FRAGMENT_SHADER
).forEach { fragmentShader ->
val program = GLUtil.createProgram(GLShaders.VERTEX_SHADER, fragmentShader)
assertTrue(program != 0)
GLES20.glDeleteProgram(program)
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)
@@ -240,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,
-13
View File
@@ -4,11 +4,9 @@
<!-- Permissions -->
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<!-- WorkManager contributes this permission for optional network constraints. Paperize never
@@ -73,17 +71,6 @@
android:exported="false"
android:foregroundServiceType="dataSync" />
<!-- Broadcast Receivers -->
<receiver
android:name=".service.alarm.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<!-- Quick Settings Tile -->
<service
android:name=".service.tile.WallpaperTileService"
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

@@ -1,21 +1,9 @@
package com.anthonyla.paperize.core
enum class ScalingType {
/**
* Fill the screen, cropping if necessary
*/
FILL,
/**
* Fit the entire image, adding letterboxing/pillarboxing if necessary
*/
FIT,
STRETCH,
/**
* Display at original size
*/
NONE;
companion object {
@@ -1,21 +1,14 @@
package com.anthonyla.paperize.core.constants
object Constants {
// Database
const val DATABASE_NAME = "paperize_database"
const val DATABASE_VERSION = 4
const val DATABASE_VERSION = 7
// DataStore
const val PREFERENCES_NAME = "paperize_preferences"
// Notifications
const val NOTIFICATION_CHANNEL_ID = "paperize_channel"
const val NOTIFICATION_ID = 1
// Services
const val ACTION_RELOAD_WALLPAPER = "com.anthonyla.paperize.ACTION_RELOAD_WALLPAPER"
// WorkManager
const val WORK_NAME_HOME = "wallpaper_change_home"
const val WORK_NAME_LOCK = "wallpaper_change_lock"
const val WORK_NAME_BOTH = "wallpaper_change_both"
@@ -23,10 +16,8 @@ object Constants {
const val WORK_NAME_REFRESH = "album_refresh"
const val MAX_WORK_RETRY_ATTEMPTS = 3
// Intents
const val EXTRA_SCREEN_TYPE = "screen_type"
// Wallpaper
const val DEFAULT_BLUR_PERCENTAGE = 0
const val DEFAULT_DARKEN_PERCENTAGE = 0
const val DEFAULT_VIGNETTE_PERCENTAGE = 0
@@ -34,17 +25,14 @@ 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
// Scheduling
const val MIN_LIVE_INTERVAL_MINUTES = 1
const val MIN_INTERVAL_MINUTES = 15
const val MAX_INTERVAL_MINUTES = 43200 // 30 days in minutes
const val DEFAULT_INTERVAL_MINUTES = 60
// UI
const val ANIMATION_DURATION_LONG_MS = 800 // For item reordering animations
const val ANIMATION_DURATION_LONG_MS = 800
const val DEBOUNCE_DELAY_MS = 500L
const val SETTINGS_DEBOUNCE_MS = 2000L
const val WALLPAPER_ASPECT_RATIO = 9f / 16f
@@ -54,80 +42,37 @@ object Constants {
const val PREVIEW_THUMBNAIL_WIDTH = 600
const val PREVIEW_THUMBNAIL_HEIGHT = 1200
// Time conversion
const val MINUTES_PER_HOUR = 60
const val MINUTES_PER_DAY = 1440
// Image processing
const val MAX_BLUR_RADIUS = 25.0f
const val BACKDROP_MAX_SIZE = 64
const val BACKDROP_BLUR_PERCENT = 25
const val BRIGHTNESS_SAMPLE_SIZE = 10
// Luminance coefficients (ITU-R BT.709 standard)
// ITU-R BT.709
const val LUMINANCE_RED = 0.2126
const val LUMINANCE_GREEN = 0.7152
const val LUMINANCE_BLUE = 0.0722
// Adaptive brightness thresholds (based on WallYou implementation)
// Adaptive brightness thresholds follow WallYou.
const val LIGHT_BRIGHTNESS_MIN = 0.8f
const val DARK_BRIGHTNESS_MAX = 0.3f
const val TARGET_BRIGHTNESS_DARK = 0.7f
const val TARGET_BRIGHTNESS_LIGHT = 0.4f
// Vignette effect
const val VIGNETTE_DIVISOR = 150f
const val VIGNETTE_MIN_RADIUS = 1f // guards against zero-radius RadialGradient crash
const val VIGNETTE_INNER_ALPHA = 0.1f
const val VIGNETTE_OUTER_ALPHA = 0.8f
val VIGNETTE_GRADIENT_POSITIONS = floatArrayOf(0f, 0.7f, 1f)
// Input validation
const val MAX_DAYS_INPUT_LENGTH = 3
const val MAX_HOURS_MINUTES_INPUT_LENGTH = 2
// File types
val SUPPORTED_IMAGE_EXTENSIONS = setOf(
"jpg", "jpeg", "png", "webp", "avif", "heic", "heif", "bmp", "gif", "tiff", "tif", "svg"
"jpg", "jpeg", "png", "webp", "avif", "heic", "heif", "bmp", "gif", "tiff", "tif"
)
// Renderer
const val CROSSFADE_DURATION_MS = 750f
const val RELOAD_THROTTLE_MS = 250L
const val BLUR_MIN_THRESHOLD = 0.01f
const val PERCENTAGE_DIVISOR = 100f
const val GL_ES_VERSION = 2
// Wallpaper loading
const val MAX_WALLPAPER_LOAD_RETRIES = 10
}
object PreferenceKeys {
// Theme
const val DARK_MODE = "dark_mode"
const val DYNAMIC_THEMING = "dynamic_theming"
const val ANIMATE = "animate"
// Scheduling
const val ENABLE_CHANGER = "enable_changer"
const val SEPARATE_SCHEDULES = "separate_schedules"
const val SHUFFLE_ENABLED = "shuffle_enabled"
const val HOME_ENABLED = "home_enabled"
const val LOCK_ENABLED = "lock_enabled"
const val HOME_ALBUM_ID = "home_album_id"
const val LOCK_ALBUM_ID = "lock_album_id"
const val HOME_INTERVAL_MINUTES = "home_interval_minutes"
const val LOCK_INTERVAL_MINUTES = "lock_interval_minutes"
// Live Wallpaper Mode Settings (effect keys are built in SettingsRepositoryImpl)
const val LIVE_ALBUM_ID = "live_album_id"
const val LIVE_INTERVAL_MINUTES = "live_interval_minutes"
// Scaling
const val HOME_SCALING_TYPE = "home_scaling_type"
const val LOCK_SCALING_TYPE = "lock_scaling_type"
const val LIVE_SCALING_TYPE = "live_scaling_type"
const val HOME_SCROLLING_ENABLED = "home_scrolling_enabled"
const val ADAPTIVE_BRIGHTNESS = "adaptive_brightness"
const val FIRST_LAUNCH = "first_launch"
const val WALLPAPER_MODE = "wallpaper_mode"
}
@@ -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)
}
@@ -36,17 +36,12 @@ object BrightnessCalculator {
}
fun getAdaptiveMultiplier(isDarkMode: Boolean, brightness: Float): Float {
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
val targetBrightnessDark = Constants.TARGET_BRIGHTNESS_DARK
val targetBrightnessLight = Constants.TARGET_BRIGHTNESS_LIGHT
// Avoid issues with very dark items or division by zero
if (brightness < 0.01f) return 1.0f
return when {
isDarkMode && brightness > lightBrightnessMin -> targetBrightnessDark / brightness
!isDarkMode && brightness < darkBrightnessMax -> targetBrightnessLight / brightness
isDarkMode && brightness > Constants.LIGHT_BRIGHTNESS_MIN -> Constants.TARGET_BRIGHTNESS_DARK / brightness
!isDarkMode && brightness < Constants.DARK_BRIGHTNESS_MAX -> Constants.TARGET_BRIGHTNESS_LIGHT / brightness
else -> 1.0f
}
}
@@ -7,10 +7,8 @@ import androidx.datastore.preferences.preferencesDataStoreFile
import com.anthonyla.paperize.core.constants.Constants
/**
* Manages one-time data reset for major version upgrades.
*
* Uses a separate preferences file (version_prefs) to track reset status,
* ensuring the flag survives the data wipe itself.
* Wipes all data once when upgrading across a major version whose data is incompatible.
* The flag lives in its own preferences file so it survives the wipe.
*/
object DataResetManager {
private const val TAG = "DataResetManager"
@@ -18,41 +16,21 @@ object DataResetManager {
private const val VERSION_PREFS_NAME = "version_prefs"
private const val KEY_LAST_RESET_VERSION = "last_reset_version"
/**
* Target reset version - increment this for future major version upgrades
* that require a complete data wipe.
*
* Version 4 = v4.0.0 release (complete app rewrite)
*/
/** Increment for a release that needs a wipe. 4 = the v4.0.0 rewrite. */
private const val TARGET_RESET_VERSION = 4
/**
* Performs a complete data reset if needed for the current app version.
*
* This should be called at the very start of Application.onCreate(),
* before any other initialization occurs.
*
* @return true if a reset was performed, false otherwise
*/
fun performResetIfNeeded(context: Context): Boolean {
/** Must run before anything opens the database or preferences. */
fun performResetIfNeeded(context: Context) {
val versionPrefs = context.getSharedPreferences(VERSION_PREFS_NAME, Context.MODE_PRIVATE)
val lastResetVersion = versionPrefs.getInt(KEY_LAST_RESET_VERSION, 0)
if (lastResetVersion >= TARGET_RESET_VERSION) {
Log.d(TAG, "No reset needed (last=$lastResetVersion, target=$TARGET_RESET_VERSION)")
return false
}
if (lastResetVersion >= TARGET_RESET_VERSION) return
Log.w(TAG, "Performing data reset: upgrading from version $lastResetVersion to $TARGET_RESET_VERSION")
return try {
try {
context.deleteDatabase(Constants.DATABASE_NAME)
context.preferencesDataStoreFile(Constants.PREFERENCES_NAME).delete()
Log.i(TAG, "Data reset completed successfully")
true
} catch (e: Exception) {
Log.e(TAG, "Error during data reset", e)
false
} finally {
// Do not repeat a destructive upgrade attempt on the next launch after a failure.
versionPrefs.edit { putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION) }
@@ -1,143 +1,16 @@
package com.anthonyla.paperize.core.util
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.CancellationSignal
import android.provider.DocumentsContract
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.runCatchingCancellable
import java.io.IOException
import java.util.UUID
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resumeWithException
fun Uri.isValid(contentResolver: ContentResolver): Boolean {
if (scheme != "content") return false
return try {
contentResolver.query(this, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
cursor.moveToFirst()
} ?: false
} catch (_: Exception) {
// Fallback to opening the stream if the provider doesn't support the specific query
try {
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
} catch (_: Exception) {
false
}
}
}
/** Only a successful, complete query with no rows proves that a document was removed. */
fun Uri.isDocumentMissing(contentResolver: ContentResolver): Boolean {
fun Uri.isReadable(contentResolver: ContentResolver): Boolean {
if (scheme != ContentResolver.SCHEME_CONTENT) return false
// Offline providers, revoked permissions and query failures do not prove deletion.
return runCatchingCancellable {
contentResolver.query(this, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { cursor ->
cursor.requireComplete()
!cursor.moveToFirst()
} ?: false
}.getOrDefault(false)
}
private fun Cursor.requireComplete() {
val metadata = extras
if (metadata.getBoolean(DocumentsContract.EXTRA_LOADING, false) ||
metadata.getString(DocumentsContract.EXTRA_ERROR) != null) {
throw IOException("Document provider has not returned a complete result")
return try {
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
} catch (_: Exception) {
false
}
}
/**
* One image file discovered while scanning a folder tree.
*
* [name] and [lastModified] are read from the same cursor row as [uri], so callers
* do not need a follow-up per-file query to obtain them.
*/
data class ScannedImage(
val uri: Uri,
val name: String,
val lastModified: Long
)
/**
* Traverses directories iteratively, querying metadata once per directory.
* Rejects incomplete provider results and cancels in-flight queries with the caller.
* [onProgress] reports every [PROGRESS_REPORT_INTERVAL] discoveries and on completion.
*/
suspend fun Uri.scanFolderImages(context: Context, onProgress: ((found: Int) -> Unit)? = null): List<ScannedImage> {
val rootDocumentId = DocumentsContract.getTreeDocumentId(this)
val projection = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED
)
val results = mutableListOf<ScannedImage>()
var lastReported = 0
val pendingDirs = ArrayDeque<String>()
val visitedDocuments = mutableSetOf(rootDocumentId)
pendingDirs.addLast(rootDocumentId)
while (pendingDirs.isNotEmpty()) {
currentCoroutineContext().ensureActive()
val parentDocumentId = pendingDirs.removeLast()
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(this, parentDocumentId)
val cursor = suspendCancellableCoroutine<Cursor> { continuation ->
val signal = CancellationSignal()
continuation.invokeOnCancellation { signal.cancel() }
try {
val result = context.contentResolver.query(childrenUri, projection, null, null, null, signal)
?: throw IOException("Document provider could not read the folder")
continuation.resume(result) { _, value, _ -> value.close() }
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
cursor.use {
cursor.requireComplete()
val idColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val nameColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val modifiedColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) {
currentCoroutineContext().ensureActive()
val documentId = cursor.getString(idColumn) ?: continue
if (!visitedDocuments.add(documentId)) continue
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
pendingDirs.addLast(documentId)
} else {
val name = cursor.getString(nameColumn) ?: continue
val extension = name.substringAfterLast('.', "").lowercase()
if (extension in Constants.SUPPORTED_IMAGE_EXTENSIONS) {
results.add(
ScannedImage(
uri = DocumentsContract.buildDocumentUriUsingTree(this, documentId),
name = name,
lastModified = if (cursor.isNull(modifiedColumn)) 0L else cursor.getLong(modifiedColumn)
)
)
if (onProgress != null && results.size - lastReported >= PROGRESS_REPORT_INTERVAL) {
lastReported = results.size
onProgress(results.size)
}
}
}
}
}
}
onProgress?.invoke(results.size)
return results
}
private const val PROGRESS_REPORT_INTERVAL = 512
fun generateId(): String = UUID.randomUUID().toString()
@@ -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,18 +1,14 @@
package com.anthonyla.paperize.core.util
import com.anthonyla.paperize.core.constants.Constants
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
import androidx.core.graphics.createBitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.HardwareRenderer
import android.graphics.ImageDecoder
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.PorterDuff
@@ -20,6 +16,7 @@ import android.graphics.PorterDuffXfermode
import android.graphics.RadialGradient
import android.graphics.RenderEffect
import android.graphics.RenderNode
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Shader
import android.hardware.display.DisplayManager
@@ -33,79 +30,17 @@ import android.view.WindowManager
import android.view.WindowMetrics
import androidx.compose.ui.util.fastRoundToInt
import androidx.core.graphics.scale
import androidx.exifinterface.media.ExifInterface
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.constants.Constants
import kotlin.math.hypot
private const val TAG = "WallpaperUtil"
private const val BUILT_IN_DISPLAY_CATEGORY =
"android.hardware.display.category.BUILT_IN_DISPLAYS"
fun Uri.getExifOrientation(context: Context): Int {
return try {
context.contentResolver.openInputStream(this)?.use { inputStream ->
val exif = ExifInterface(inputStream)
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
} ?: ExifInterface.ORIENTATION_UNDEFINED
} catch (e: Exception) {
Log.w(TAG, "Error reading EXIF orientation: $e")
ExifInterface.ORIENTATION_UNDEFINED
}
}
fun getExifTransformationMatrix(orientation: Int, width: Int, height: Int): Matrix {
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> {
matrix.setScale(-1f, 1f)
matrix.postTranslate(width.toFloat(), 0f)
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
matrix.setRotate(180f)
matrix.postTranslate(width.toFloat(), height.toFloat())
}
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setScale(1f, -1f)
matrix.postTranslate(0f, height.toFloat())
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> {
matrix.setRotate(90f)
matrix.postTranslate(height.toFloat(), 0f)
}
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
matrix.setRotate(-90f)
matrix.postTranslate(0f, width.toFloat())
}
}
return matrix
}
fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
if (imageSize.width == 0 || imageSize.height == 0) return 1
if (width == 0 || height == 0) return 1
if (imageSize.width > width || imageSize.height > height) {
// Integer division (floor) ensures inSampleSize is never larger than needed,
// guaranteeing the decoded bitmap is at least as wide/tall as the target.
// fastRoundToInt() can round UP, producing a bitmap smaller than the target.
val heightRatio = imageSize.height / height
val widthRatio = imageSize.width / width
return minOf(heightRatio, widthRatio).coerceAtLeast(1)
}
return 1
}
fun getDeviceScreenSize(context: Context): Size {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val windowManager = context.getSystemService(WindowManager::class.java)
val metrics: WindowMetrics = windowManager.currentWindowMetrics
val currentWindow = metrics.bounds.width() to metrics.bounds.height()
@@ -166,13 +101,13 @@ internal fun selectLargestDisplayDimensions(
* FIT/STRETCH/NONE use an exact launcher canvas so Android cannot rescale them into FILL.
*/
internal fun usesLauncherManagedScrolling(
screenType: com.anthonyla.paperize.core.ScreenType,
screenType: ScreenType,
scaling: ScalingType,
scrollingEnabled: Boolean
): Boolean =
scrollingEnabled &&
(screenType == com.anthonyla.paperize.core.ScreenType.HOME ||
screenType == com.anthonyla.paperize.core.ScreenType.BOTH) &&
(screenType == ScreenType.HOME ||
screenType == ScreenType.BOTH) &&
scaling == ScalingType.FILL
fun retrieveBitmap(
@@ -181,13 +116,14 @@ 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 reports dimensions after applying EXIF orientation.
var decodedWithImageDecoder = false
// ImageDecoder applies EXIF orientation and reports dimensions after it.
val bitmap = try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
val result = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
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
)
@@ -198,48 +134,27 @@ fun retrieveBitmap(
) {
val cropX = ((targetW - width) / 2).coerceAtLeast(0)
val cropY = ((targetH - height) / 2).coerceAtLeast(0)
decoder.setCrop(android.graphics.Rect(cropX, cropY, cropX + width, cropY + height))
decoder.setCrop(Rect(cropX, cropY, cropX + width, cropY + height))
}
decoder.isMutableRequired = true
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
decoder.setOnPartialImageListener { true }
}
decodedWithImageDecoder = true
result
} catch (e: Exception) {
Log.w(TAG, "ImageDecoder failed, falling back to BitmapFactory: $e")
try {
val sampleSize = context.contentResolver.openInputStream(wallpaperUri)?.use { stream ->
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeStream(stream, null, opts)
if (scaling == ScalingType.NONE || opts.outWidth <= 0 || opts.outHeight <= 0) 1
else calculateInSampleSize(Size(opts.outWidth, opts.outHeight), width, height)
} ?: 1
context.contentResolver.openInputStream(wallpaperUri)?.use { stream ->
BitmapFactory.decodeStream(stream, null, BitmapFactory.Options().apply {
inSampleSize = sampleSize
inMutable = true
inPreferredConfig = Bitmap.Config.ARGB_8888
})
}
} catch (oom: OutOfMemoryError) {
Log.e(TAG, "OOM during BitmapFactory fallback for $wallpaperUri: $oom")
null
}
Log.w(TAG, "Could not decode $wallpaperUri: $e")
null
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM during retrieveBitmap for $wallpaperUri: $e")
null
}
// Only apply EXIF orientation for the BitmapFactory path — ImageDecoder already handles it
val oriented = if (decodedWithImageDecoder) bitmap else bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
// An exact canvas prevents the launcher from undoing the selected scaling mode.
return oriented?.let {
return bitmap?.let {
if (preserveSourceOverflow && scaling == ScalingType.FILL) {
scaleToFillPreservingOverflow(it, width, height)
} else {
finalizeToCanvas(it, width, height, scaling)
finalizeToCanvas(it, width, height, scaling, blurFitBackground)
}
}
}
@@ -268,55 +183,66 @@ private fun scaleToFillPreservingOverflow(
return scaled
}
/** Render either decoder's output onto the requested canvas; consumes [source]. */
internal fun finalizeToCanvas(source: Bitmap, canvasW: Int, canvasH: Int, scaling: ScalingType): Bitmap {
/** Render the decoded bitmap onto the requested canvas; consumes [source]. */
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
}
private fun applyExifOrientation(source: Bitmap, uri: Uri, context: Context): Bitmap {
val orientation = uri.getExifOrientation(context)
if (orientation == ExifInterface.ORIENTATION_UNDEFINED || orientation == ExifInterface.ORIENTATION_NORMAL) {
return source
}
return try {
val matrix = getExifTransformationMatrix(orientation, source.width, source.height)
val rotated = Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
if (rotated != source) {
source.recycle() // Recycle old bitmap to free memory
}
rotated
} catch (e: Exception) {
Log.e(TAG, "Error applying EXIF orientation: $e")
source
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM applying EXIF orientation: $e")
source
/**
* 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
val radius = (kotlin.math.hypot(centerX, centerY) *
val radius = (hypot(centerX, centerY) *
(1 - percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))
.coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
@@ -333,10 +259,6 @@ private fun drawVignette(canvas: Canvas, width: Int, height: Int, percent: Int)
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
}
/**
* Adjust bitmap brightness by a multiplier
* @param brightnessFactor Brightness multiplier (e.g., 0.7 to darken, 1.5 to brighten)
*/
fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
if (brightnessFactor == 1.0f) return source
if (!source.isMutable) {
@@ -357,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,15 +1,16 @@
package com.anthonyla.paperize.data.database
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.anthonyla.paperize.data.database.converters.TypeConverters as PaperizeTypeConverters
import com.anthonyla.paperize.data.database.dao.AlbumDao
import com.anthonyla.paperize.data.database.dao.ExcludedWallpaperDao
import com.anthonyla.paperize.data.database.dao.FolderDao
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
import com.anthonyla.paperize.data.database.dao.WallpaperDao
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.ExcludedWallpaperEntity
import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
@@ -22,16 +23,18 @@ 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)]
)
@TypeConverters(PaperizeTypeConverters::class)
abstract class PaperizeDatabase : RoomDatabase() {
abstract fun albumDao(): AlbumDao
abstract fun wallpaperDao(): WallpaperDao
abstract fun folderDao(): FolderDao
abstract fun wallpaperQueueDao(): WallpaperQueueDao
abstract fun wallpaperCurrentDao(): WallpaperCurrentDao
abstract fun excludedWallpaperDao(): ExcludedWallpaperDao
}
@@ -1,12 +0,0 @@
package com.anthonyla.paperize.data.database.converters
import androidx.room.TypeConverter
import com.anthonyla.paperize.core.ScreenType
class TypeConverters {
@TypeConverter
fun fromScreenType(value: ScreenType): String = value.name
@TypeConverter
fun toScreenType(value: String): ScreenType = ScreenType.fromString(value)
}
@@ -33,15 +33,18 @@ interface AlbumDao {
@Query("SELECT * FROM albums WHERE id = :albumId")
suspend fun getAlbumById(albumId: String): AlbumEntity?
@Query("SELECT * FROM albums WHERE name = :name LIMIT 1")
suspend fun getAlbumByName(name: String): AlbumEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAlbum(album: AlbumEntity)
@Query("DELETE FROM albums WHERE id = :albumId")
suspend fun deleteAlbumById(albumId: String)
@Query("UPDATE albums SET 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>)
}
@@ -33,9 +33,6 @@ interface FolderDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertFolder(folder: FolderEntity)
@Query("UPDATE folders SET displayOrder = :order WHERE id = :folderId AND albumId = :albumId")
suspend fun updateFolderOrder(albumId: String, folderId: String, order: Int)
@Query("UPDATE folders SET coverUri = :coverUri WHERE id = :folderId")
suspend fun updateFolderCover(folderId: String, coverUri: String?)
@@ -45,7 +42,4 @@ interface FolderDao {
) WHERE albumId = :albumId
""")
suspend fun refreshFolderCovers(albumId: String)
@Query("DELETE FROM folders WHERE id = :folderId")
suspend fun deleteFolderById(folderId: String)
}
@@ -12,18 +12,7 @@ import kotlinx.coroutines.flow.Flow
@Dao
interface WallpaperCurrentDao {
/**
* Return the wallpaper entity that was last applied for this album/screen,
* or null if none has been recorded yet (or if it was deleted via CASCADE).
*/
@Query("""
SELECT w.* FROM wallpapers w
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
WHERE wc.albumId = :albumId AND wc.screenType = :screenType
LIMIT 1
""")
suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity?
/** Emits null until a wallpaper is applied, and again if that wallpaper or album is deleted. */
@Query("""
SELECT w.* FROM wallpapers w
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
@@ -4,7 +4,6 @@ import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
@Dao
@@ -15,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
@@ -30,23 +32,11 @@ interface WallpaperDao {
@Query("SELECT * FROM wallpapers WHERE id = :wallpaperId")
suspend fun getWallpaperById(wallpaperId: String): WallpaperEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertWallpaper(wallpaper: WallpaperEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertWallpapers(wallpapers: List<WallpaperEntity>)
@Update
suspend fun updateWallpaper(wallpaper: WallpaperEntity)
@Query("UPDATE wallpapers SET displayOrder = :order WHERE id = :wallpaperId AND albumId = :albumId")
suspend fun updateAlbumWallpaperOrder(albumId: String, wallpaperId: String, order: Int)
@Query("DELETE FROM wallpapers WHERE folderId = :folderId")
suspend fun deleteWallpapersByFolder(folderId: String)
@Query("SELECT COUNT(*) FROM wallpapers WHERE albumId = :albumId")
suspend fun getWallpaperCountByAlbum(albumId: String): Int
@Query("SELECT * 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()
)
@@ -1,12 +1,16 @@
package com.anthonyla.paperize.data.mapper
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
fun AlbumEntity.toDomainModel(
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList(),
folders: List<com.anthonyla.paperize.domain.model.Folder> = emptyList()
wallpapers: List<Wallpaper> = emptyList(),
folders: List<Folder> = emptyList()
): Album = Album(
id = id,
name = name,
@@ -14,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(
@@ -22,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 {
@@ -41,13 +49,12 @@ fun AlbumWithDetails.toDomainModel(): Album {
)
}
fun com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity.toDomainModel(): com.anthonyla.paperize.domain.model.AlbumSummary =
com.anthonyla.paperize.domain.model.AlbumSummary(
id = id,
name = name,
coverUri = coverUri,
wallpaperCount = wallpaperCount,
folderCount = folderCount,
createdAt = createdAt,
modifiedAt = modifiedAt
)
fun AlbumSummaryEntity.toDomainModel(): AlbumSummary = AlbumSummary(
id = id,
name = name,
coverUri = coverUri,
wallpaperCount = wallpaperCount,
folderCount = folderCount,
createdAt = createdAt,
modifiedAt = modifiedAt
)
@@ -3,9 +3,11 @@ package com.anthonyla.paperize.data.mapper
import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
fun FolderEntity.toDomainModel(
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList()
wallpapers: List<Wallpaper> = emptyList(),
removedWallpapers: List<Wallpaper> = emptyList()
): Folder = Folder(
id = id,
albumId = albumId,
@@ -15,6 +17,7 @@ fun FolderEntity.toDomainModel(
dateModified = dateModified,
displayOrder = displayOrder,
wallpapers = wallpapers,
removedWallpapers = removedWallpapers,
addedAt = addedAt
)
@@ -30,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,15 +38,15 @@ class AlbumRepositoryImpl @Inject constructor(
override fun getAlbumById(albumId: String): Flow<Album?> =
albumDao.getAlbumWithDetails(albumId).map { it?.toDomainModel() }
override suspend fun getAlbumByName(name: String): Album? =
albumDao.getAlbumByName(name)?.toDomainModel()
override suspend fun getAlbumEncryption(albumId: String): Boolean? =
albumDao.getAlbumById(albumId)?.isEncrypted
override fun getFolderById(folderId: String): Flow<Folder?> =
folderDao.getFolderWithWallpapers(folderId).map { it?.toDomainModel() }
override suspend fun createAlbum(name: String, coverUri: String?): 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
}
@@ -52,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>,
@@ -76,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>,
@@ -118,27 +162,6 @@ class AlbumRepositoryImpl @Inject constructor(
}
}
override suspend fun reorderAlbum(
albumId: String,
folders: List<Folder>,
wallpapers: List<Wallpaper>
) {
database.withTransaction {
folders.forEachIndexed { index, folder ->
folderDao.updateFolderOrder(albumId, folder.id, index)
}
// Rotation follows direct images, then each folder in the saved order.
(wallpapers.asSequence() + folders.asSequence().flatMap { it.wallpapers })
.forEachIndexed { index, wallpaper ->
wallpaperDao.updateAlbumWallpaperOrder(albumId, wallpaper.id, index)
}
folderDao.refreshFolderCovers(albumId)
updateAlbumCoverIfNeeded(albumId)
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
database.wallpaperQueueDao().clearAllQueues(albumId)
}
}
override suspend fun removeWallpapersFromAlbum(
albumId: String,
wallpaperIds: List<String>
@@ -154,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)
@@ -13,7 +13,6 @@ import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.constants.PreferenceKeys
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.model.WallpaperEffects
@@ -29,27 +28,29 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
name = Constants.PREFERENCES_NAME
)
private val DARK_MODE = booleanPreferencesKey(PreferenceKeys.DARK_MODE)
private val DYNAMIC_THEMING = booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)
private val ANIMATE = booleanPreferencesKey(PreferenceKeys.ANIMATE)
private val FIRST_LAUNCH = booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)
private val WALLPAPER_MODE = stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)
private val ENABLE_CHANGER = booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)
private val SEPARATE_SCHEDULES = booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)
private val SHUFFLE_ENABLED = booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)
private val HOME_ENABLED = booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)
private val LOCK_ENABLED = booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)
private val HOME_ALBUM_ID = stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)
private val LOCK_ALBUM_ID = stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)
private val LIVE_ALBUM_ID = stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)
private val HOME_INTERVAL_MINUTES = intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)
private val LOCK_INTERVAL_MINUTES = intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)
private val LIVE_INTERVAL_MINUTES = intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)
private val HOME_SCALING_TYPE = stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)
private val LOCK_SCALING_TYPE = stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)
private val LIVE_SCALING_TYPE = stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)
private val HOME_SCROLLING_ENABLED = booleanPreferencesKey(PreferenceKeys.HOME_SCROLLING_ENABLED)
private val ADAPTIVE_BRIGHTNESS = booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)
private val DARK_MODE = booleanPreferencesKey("dark_mode")
private val DYNAMIC_THEMING = booleanPreferencesKey("dynamic_theming")
private val ANIMATE = booleanPreferencesKey("animate")
private val ENCRYPTED_PREVIEWS = booleanPreferencesKey("encrypted_previews")
private val FIRST_LAUNCH = booleanPreferencesKey("first_launch")
private val WALLPAPER_MODE = stringPreferencesKey("wallpaper_mode")
private val ENABLE_CHANGER = booleanPreferencesKey("enable_changer")
private val SEPARATE_SCHEDULES = booleanPreferencesKey("separate_schedules")
private val SHUFFLE_ENABLED = booleanPreferencesKey("shuffle_enabled")
private val HOME_ENABLED = booleanPreferencesKey("home_enabled")
private val LOCK_ENABLED = booleanPreferencesKey("lock_enabled")
private val HOME_ALBUM_ID = stringPreferencesKey("home_album_id")
private val LOCK_ALBUM_ID = stringPreferencesKey("lock_album_id")
private val LIVE_ALBUM_ID = stringPreferencesKey("live_album_id")
private val HOME_INTERVAL_MINUTES = intPreferencesKey("home_interval_minutes")
private val LOCK_INTERVAL_MINUTES = intPreferencesKey("lock_interval_minutes")
private val LIVE_INTERVAL_MINUTES = intPreferencesKey("live_interval_minutes")
private val HOME_SCALING_TYPE = stringPreferencesKey("home_scaling_type")
private val LOCK_SCALING_TYPE = stringPreferencesKey("lock_scaling_type")
private val LIVE_SCALING_TYPE = stringPreferencesKey("live_scaling_type")
private val HOME_SCROLLING_ENABLED = booleanPreferencesKey("home_scrolling_enabled")
private val BLUR_FIT_BACKGROUND = booleanPreferencesKey("blur_fit_background")
private val ADAPTIVE_BRIGHTNESS = booleanPreferencesKey("adaptive_brightness")
/** Effect keys are "<screen>_<field>", e.g. "home_enable_blur" or "live_parallax_intensity". */
private class EffectKeys(screen: String) {
@@ -85,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
)
}
@@ -124,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)
@@ -157,13 +160,8 @@ class SettingsRepositoryImpl @Inject constructor(
val targets = albumIdKeys(screen).filter { prefs[it] == albumId }
if (targets.isEmpty()) return@edit
targets.forEach { prefs.remove(it) }
val active = if (WallpaperMode.fromString(prefs[WALLPAPER_MODE]) == WallpaperMode.LIVE) {
prefs[LIVE_ALBUM_ID] != null
} else {
(prefs[HOME_ENABLED] == true && prefs[HOME_ALBUM_ID] != null) ||
(prefs[LOCK_ENABLED] == true && prefs[LOCK_ALBUM_ID] != null)
}
if (!active) prefs[ENABLE_CHANGER] = false
val mode = WallpaperMode.fromString(prefs[WALLPAPER_MODE])
if (scheduleSettings(prefs).activeScreens(mode).isEmpty()) prefs[ENABLE_CHANGER] = false
}
}
@@ -179,8 +177,12 @@ class SettingsRepositoryImpl @Inject constructor(
dataStore.edit { it[ANIMATE] = enabled }
}
override suspend fun updateFirstLaunch(isFirstLaunch: Boolean) {
dataStore.edit { it[FIRST_LAUNCH] = isFirstLaunch }
override suspend fun updateEncryptedPreviews(enabled: Boolean) {
dataStore.edit { it[ENCRYPTED_PREVIEWS] = enabled }
}
override suspend fun completeFirstLaunch() {
dataStore.edit { it[FIRST_LAUNCH] = false }
}
override suspend fun updateEnableChanger(enabled: Boolean) {
@@ -205,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,15 +7,22 @@ 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
import kotlinx.coroutines.flow.first
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()
@@ -49,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
@@ -59,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()) {
@@ -72,12 +81,42 @@ 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()
}
override suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
wallpaperCurrentDao.getCurrentWallpaper(albumId, screenType)?.toDomainModel()
getCurrentWallpaperFlow(albumId, screenType).first()
override fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<Wallpaper?> =
wallpaperCurrentDao.getCurrentWallpaperFlow(albumId, screenType).map { it?.toDomainModel() }
@@ -1,19 +1,30 @@
package com.anthonyla.paperize.data.source
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.CancellationSignal
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.anthonyla.paperize.core.util.isDocumentMissing
import com.anthonyla.paperize.core.util.scanFolderImages
import com.anthonyla.paperize.core.runCatchingCancellable
import com.anthonyla.paperize.domain.source.DocumentSource
import com.anthonyla.paperize.domain.source.NAMING_TABLE_FILE
import com.anthonyla.paperize.domain.source.SourceFolder
import com.anthonyla.paperize.domain.source.SourceImage
import com.anthonyla.paperize.domain.source.isSupportedSourceName
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.io.IOException
import javax.inject.Inject
import kotlin.coroutines.resumeWithException
class AndroidDocumentSource @Inject constructor(
@param:ApplicationContext private val context: Context
@@ -27,12 +38,25 @@ 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()
val images = tree.scanFolderImages(context, onProgress).map {
SourceImage(it.uri.toString(), it.name, it.lastModified)
}
SourceFolder(DocumentFile.fromTreeUri(context, tree)?.name ?: uri.substringAfterLast('/'), images)
SourceFolder(
DocumentFile.fromTreeUri(context, tree)?.name ?: uri.substringAfterLast('/'),
tree.scanFolderImages(context, isEncrypted, onProgress)
)
}
override suspend fun readNamingTable(folderUri: String): ByteArray? = withContext(Dispatchers.IO) {
val tree = folderUri.toUri()
val children = DocumentsContract.buildChildDocumentsUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))
val projection = arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val documentId = context.contentResolver.query(children, projection, null, null, null)?.use { cursor ->
cursor.requireComplete()
generateSequence { if (cursor.moveToNext()) cursor else null }
.firstOrNull { it.getString(1) == NAMING_TABLE_FILE }?.getString(0)
} ?: return@withContext null
val table = DocumentsContract.buildDocumentUriUsingTree(tree, documentId)
context.contentResolver.openInputStream(table)?.use { it.readBytes() }
}
override suspend fun isMissing(uri: String, isTree: Boolean): Boolean = withContext(Dispatchers.IO) {
@@ -43,3 +67,102 @@ class AndroidDocumentSource @Inject constructor(
document.isDocumentMissing(context.contentResolver)
}
}
/** Only a successful, complete query with no rows proves that a document was removed. */
internal fun Uri.isDocumentMissing(contentResolver: ContentResolver): Boolean {
if (scheme != ContentResolver.SCHEME_CONTENT) return false
// Offline providers, revoked permissions and query failures do not prove deletion.
return runCatchingCancellable {
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { cursor ->
cursor.requireComplete()
!cursor.moveToFirst()
} ?: false
}.getOrDefault(false)
}
private fun Cursor.requireComplete() {
val metadata = extras
if (metadata.getBoolean(DocumentsContract.EXTRA_LOADING, false) ||
metadata.getString(DocumentsContract.EXTRA_ERROR) != null) {
throw IOException("Document provider has not returned a complete result")
}
}
/**
* Traverses directories iteratively, querying metadata once per directory.
* Rejects incomplete provider results and cancels in-flight queries with the caller.
* [onProgress] reports every [PROGRESS_REPORT_INTERVAL] discoveries and on completion.
*/
internal suspend fun Uri.scanFolderImages(context: Context, isEncrypted: Boolean, onProgress: (found: Int) -> Unit = {}): List<SourceImage> {
val rootDocumentId = DocumentsContract.getTreeDocumentId(this)
val projection = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED
)
val results = mutableListOf<SourceImage>()
var lastReported = 0
val pendingDirs = ArrayDeque<String>()
val visitedDocuments = mutableSetOf(rootDocumentId)
pendingDirs.addLast(rootDocumentId)
while (pendingDirs.isNotEmpty()) {
currentCoroutineContext().ensureActive()
val parentDocumentId = pendingDirs.removeLast()
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(this, parentDocumentId)
val cursor = suspendCancellableCoroutine<Cursor> { continuation ->
val signal = CancellationSignal()
continuation.invokeOnCancellation { signal.cancel() }
try {
val result = context.contentResolver.query(childrenUri, projection, null, null, null, signal)
?: throw IOException("Document provider could not read the folder")
continuation.resume(result) { _, value, _ -> value.close() }
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
cursor.use {
cursor.requireComplete()
val idColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val nameColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val modifiedColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) {
currentCoroutineContext().ensureActive()
val documentId = cursor.getString(idColumn) ?: continue
if (!visitedDocuments.add(documentId)) continue
val name = cursor.getString(nameColumn) ?: continue
// Galleries rename deleted files in place: .trashed-…, .Trash-…
// HyperOS keeps reporting the old display name, so the id is checked too.
val fileName = documentId.substringAfterLast('/').substringAfterLast(':')
if (listOf(name, fileName).any { it.startsWith(".trash", ignoreCase = true) }) continue
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
pendingDirs.addLast(documentId)
} else {
if (isSupportedSourceName(name, isEncrypted)) {
results.add(
SourceImage(
uri = DocumentsContract.buildDocumentUriUsingTree(this, documentId).toString(),
name = name,
modifiedAt = if (cursor.isNull(modifiedColumn)) 0L else cursor.getLong(modifiedColumn)
)
)
if (results.size - lastReported >= PROGRESS_REPORT_INTERVAL) {
lastReported = results.size
onProgress(results.size)
}
}
}
}
}
}
onProgress(results.size)
return results
}
private const val PROGRESS_REPORT_INTERVAL = 512
@@ -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,13 +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()
) {
companion object {
fun empty(id: String = "", name: String = "") = Album(
id = id,
name = name,
coverUri = null
)
}
}
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
)
@@ -13,16 +13,4 @@ data class AlbumSummary(
val folderCount: Int,
val createdAt: Long,
val modifiedAt: Long
) {
companion object {
fun empty(id: String = "", name: String = "") = AlbumSummary(
id = id,
name = name,
coverUri = null,
wallpaperCount = 0,
folderCount = 0,
createdAt = System.currentTimeMillis(),
modifiedAt = System.currentTimeMillis()
)
}
}
)
@@ -4,6 +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,21 +11,14 @@ 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
get() = Uri.decode(name).let { decoded ->
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
}
get() = decodedLastSegment(name)
}
companion object {
fun empty(id: String = "", albumId: String = "") = Folder(
id = id,
albumId = albumId,
name = "",
uri = "",
coverUri = null,
dateModified = 0L
)
}
/** Readable name of a document URI or encoded path: the part after the last '/', else after the last ':'. */
internal fun decodedLastSegment(encoded: String): String = Uri.decode(encoded).let { decoded ->
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
}
@@ -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,
@@ -46,6 +47,14 @@ data class ScheduleSettings(
}
}
fun isRotating(mode: WallpaperMode): Boolean = enableChanger && hasRequiredAlbums(mode)
fun albumId(screen: ScreenType): String? = when (screen) {
ScreenType.HOME, ScreenType.BOTH -> homeAlbumId
ScreenType.LOCK -> lockAlbumId
ScreenType.LIVE -> liveAlbumId
}
fun intervalMinutes(screen: ScreenType): Int = when (screen) {
ScreenType.HOME, ScreenType.BOTH -> homeIntervalMinutes
ScreenType.LOCK -> effectiveLockIntervalMinutes
@@ -79,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 ||
@@ -1,7 +1,5 @@
package com.anthonyla.paperize.domain.model
import android.net.Uri
data class Wallpaper(
val id: String,
val albumId: String,
@@ -13,17 +11,5 @@ data class Wallpaper(
val addedAt: Long = System.currentTimeMillis()
) {
val displayFileName: String
get() = Uri.decode(fileName).let { decoded ->
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
}
companion object {
fun empty(id: String = "", albumId: String = "") = Wallpaper(
id = id,
albumId = albumId,
uri = "",
fileName = "",
dateModified = 0L
)
}
get() = decodedLastSegment(fileName)
}
@@ -11,11 +11,17 @@ interface AlbumRepository {
fun getAlbumById(albumId: String): Flow<Album?>
suspend fun getAlbumByName(name: String): 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)
@@ -33,10 +39,22 @@ interface AlbumRepository {
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
): Boolean
suspend fun reorderAlbum(albumId: String, folders: List<Folder>, wallpapers: List<Wallpaper>)
/** 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,7 +42,8 @@ interface SettingsRepository {
suspend fun updateDarkMode(enabled: Boolean)
suspend fun updateDynamicTheming(enabled: Boolean)
suspend fun updateAnimate(enabled: Boolean)
suspend fun updateFirstLaunch(isFirstLaunch: 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
@@ -1,15 +1,16 @@
package com.anthonyla.paperize.domain.usecase
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.repository.AlbumRepository
import javax.inject.Inject
import kotlinx.coroutines.flow.first
class CreateAlbumUseCase @Inject constructor(
private val albumRepository: AlbumRepository
) {
suspend operator fun invoke(name: String, coverUri: String? = null): Album {
require(name.isNotBlank()) { "Album name cannot be empty" }
require(albumRepository.getAlbumByName(name) == null) { "Album with this name already exists" }
return albumRepository.createAlbum(name, coverUri)
/** Returns false, creating nothing, when an album already has this name ignoring case. */
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, 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) }
)
}
}
@@ -38,13 +38,11 @@ class MainActivity : ComponentActivity() {
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
if (currentSettings != null) {
currentSettings?.let { settings ->
NavigationGraph(
startDestination = if (currentSettings?.firstLaunch != false) StartupRoute else HomeRoute,
animate = currentSettings?.animate ?: true,
onFirstLaunchComplete = {
settingsViewModel.updateFirstLaunch(false)
}
startDestination = if (settings.firstLaunch) StartupRoute else HomeRoute,
animate = settings.animate,
onFirstLaunchComplete = settingsViewModel::completeFirstLaunch
)
}
}
@@ -1,11 +1,27 @@
package com.anthonyla.paperize.presentation.common
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/** Share while the UI collects, keeping the upstream alive across configuration changes. */
fun <T> Flow<T>.stateWhileSubscribed(scope: CoroutineScope, initialValue: T): StateFlow<T> =
stateIn(scope, SharingStarted.WhileSubscribed(5_000), initialValue)
/** Runs [block] with [busy] raised, lowering it however the block ends. */
fun ViewModel.launchBusy(busy: MutableStateFlow<Boolean>, block: suspend () -> Unit) {
busy.value = true
viewModelScope.launch {
try {
block()
} finally {
busy.value = false
}
}
}
@@ -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
@@ -30,15 +29,13 @@ import com.anthonyla.paperize.R
fun AddAlbumAnimatedFab(
isLoading: Boolean,
onImageClick: () -> Unit,
onFolderClick: () -> Unit,
modifier: Modifier = Modifier
onFolderClick: () -> Unit
) {
var fabMenuExpanded by rememberSaveable { mutableStateOf(false) }
BackHandler(fabMenuExpanded) { fabMenuExpanded = false }
FloatingActionButtonMenu(
modifier = modifier,
expanded = fabMenuExpanded,
button = {
ToggleFloatingActionButton(
@@ -51,7 +48,7 @@ fun AddAlbumAnimatedFab(
}
}
Icon(
painter = rememberVectorPainter(imageVector),
imageVector = imageVector,
contentDescription = if (fabMenuExpanded) {
stringResource(R.string.content_desc_collapse)
} else {
@@ -0,0 +1,52 @@
package com.anthonyla.paperize.presentation.common.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PhotoAlbum
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import coil3.compose.AsyncImagePainter
import coil3.compose.rememberAsyncImagePainter
import com.anthonyla.paperize.domain.model.AlbumSummary
/** The album's cover image, or a placeholder icon until one loads. */
@Composable
fun AlbumCover(
album: AlbumSummary,
thumbnailSize: Int,
placeholderTint: Color,
modifier: Modifier = Modifier,
placeholderModifier: Modifier = Modifier
) {
val cover = rememberAsyncImagePainter(
encryptedAwareImageRequest(album.coverUri, thumbnailSize, thumbnailSize),
contentScale = ContentScale.Crop
)
val coverState by cover.state.collectAsState()
Box(modifier = modifier, contentAlignment = Alignment.Center) {
if (coverState is AsyncImagePainter.State.Success) {
Image(
painter = cover,
contentDescription = album.name,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
} else {
Icon(
imageVector = Icons.Filled.PhotoAlbum,
contentDescription = album.name,
modifier = placeholderModifier,
tint = placeholderTint
)
}
}
}
@@ -1,29 +1,24 @@
package com.anthonyla.paperize.presentation.screens.folder_view.components
package com.anthonyla.paperize.presentation.common.components
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.filled.Refresh
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.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import com.anthonyla.paperize.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FolderViewTopBar(
fun BackTopAppBar(
title: String,
onBackClick: () -> Unit,
onSortClick: () -> Unit,
onRefreshClick: () -> Unit,
modifier: Modifier = Modifier,
isRefreshing: Boolean = false
onBack: () -> Unit,
actions: @Composable RowScope.() -> Unit = {}
) {
TopAppBar(
title = {
@@ -34,21 +29,13 @@ fun FolderViewTopBar(
)
},
navigationIcon = {
IconButton(onClick = onBackClick) {
IconButton(onClick = onBack) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.back)
)
}
},
actions = {
IconButton(onClick = onRefreshClick, enabled = !isRefreshing) {
Icon(Icons.Default.Refresh, contentDescription = stringResource(R.string.refresh_folder))
}
IconButton(onClick = onSortClick) {
Icon(Icons.AutoMirrored.Filled.Sort, contentDescription = stringResource(R.string.sort))
}
},
modifier = modifier
actions = actions
)
}
@@ -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,
modifier: Modifier = Modifier,
errorMessage: String? = null,
isSaving: Boolean = false
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))
@@ -52,7 +69,38 @@ fun AddAlbumDialog(
TextButton(onClick = onDismiss, enabled = !isSaving) {
Text(stringResource(R.string.cancel))
}
}
)
}
/** [enabled] false locks the dialog open while the confirmed action runs. */
@Composable
fun ConfirmDialog(
title: String,
text: String,
onConfirm: () -> Unit,
onDismiss: () -> Unit,
confirmLabel: String = stringResource(R.string.confirm),
confirmColor: Color = Color.Unspecified,
enabled: Boolean = true
) {
AlertDialog(
onDismissRequest = { if (enabled) onDismiss() },
title = { Text(title) },
text = { Text(text) },
confirmButton = {
TextButton(
onClick = onConfirm,
enabled = enabled,
colors = ButtonDefaults.textButtonColors(contentColor = confirmColor)
) {
Text(confirmLabel)
}
},
modifier = modifier
dismissButton = {
TextButton(onClick = onDismiss, enabled = enabled) {
Text(stringResource(R.string.cancel))
}
}
)
}
@@ -19,6 +19,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.presentation.common.theme.AppIconSizes
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
@Composable
@@ -36,7 +37,7 @@ fun EmptyCollection(
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
Icon(Icons.Outlined.PhotoLibrary, contentDescription = null,
modifier = Modifier.size(64.dp), tint = MaterialTheme.colorScheme.primary)
modifier = Modifier.size(AppIconSizes.huge), tint = MaterialTheme.colorScheme.primary)
Text(title, style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center)
Text(hint, style = MaterialTheme.typography.bodyLarge, textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -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()
}
}
}
}
@@ -0,0 +1,150 @@
package com.anthonyla.paperize.presentation.common.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.presentation.common.navigation.util.NavConstants
import com.anthonyla.paperize.presentation.common.theme.AppSpacing
import kotlinx.coroutines.delay
@Composable
fun OnboardingLayout(
title: String,
iconContent: @Composable () -> Unit,
content: @Composable () -> Unit,
modifier: Modifier = Modifier,
actions: @Composable () -> Unit
) {
var visible by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
// Let the navigation transition finish so the two animations don't overlap.
delay(NavConstants.NAVIGATION_TIME.toLong())
visible = true
}
BoxWithConstraints(modifier = modifier.fillMaxSize()) {
val minContentHeight = maxHeight - (AppSpacing.extraLarge * 2)
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(AppSpacing.extraLarge),
horizontalAlignment = Alignment.CenterHorizontally
) {
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = minContentHeight),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Entrance(visible = visible, delayMillis = 0) {
Box(
modifier = Modifier
.size(120.dp)
.background(
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f),
shape = CircleShape
),
contentAlignment = Alignment.Center
) {
iconContent()
}
}
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
Entrance(visible = visible, delayMillis = 100) {
Text(
text = title,
style = MaterialTheme.typography.headlineLarge,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(AppSpacing.large))
Entrance(visible = visible, delayMillis = 200, content = content)
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
Entrance(visible = visible, delayMillis = 300, offsetY = 100) {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
actions()
}
}
}
}
}
}
@Composable
fun OnboardingButton(
text: String,
onClick: () -> Unit,
enabled: Boolean = true
) {
Button(
onClick = onClick,
modifier = Modifier.fillMaxWidth(),
enabled = enabled,
shape = MaterialTheme.shapes.large
) {
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
@Composable
private fun ColumnScope.Entrance(
visible: Boolean,
delayMillis: Int,
offsetY: Int = 50,
content: @Composable () -> Unit
) {
AnimatedVisibility(
visible = visible,
enter = fadeIn(animationSpec = tween(500, delayMillis)) +
slideInVertically(animationSpec = tween(500, delayMillis)) { offsetY }
) {
content()
}
}
@@ -1,9 +1,10 @@
package com.anthonyla.paperize.presentation.screens.album_view.components
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
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -18,55 +19,37 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
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.selected
import androidx.compose.ui.semantics.semantics
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.presentation.common.theme.AppSpacing
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun WallpaperItem(
wallpaperUri: String,
wallpaperName: String,
fun SelectableGridCard(
isSelected: Boolean,
isSelectionMode: Boolean,
onClick: () -> Unit,
onLongClick: (() -> Unit)?,
modifier: Modifier = Modifier
modifier: Modifier = Modifier,
content: @Composable BoxScope.() -> Unit
) {
val context = LocalContext.current
val transition = updateTransition(isSelected, label = "WallpaperItemSelection")
val paddingTransition by transition.animateDp(label = "padding") { selected ->
val transition = updateTransition(isSelected, label = "selection")
val padding by transition.animateDp(label = "padding") { selected ->
if (selected) 5.dp else 0.dp
}
val roundedCornerShapeTransition by transition.animateDp(label = "roundedCornerShape") { selected ->
val cornerRadius by transition.animateDp(label = "cornerRadius") { selected ->
if (selected) 24.dp else 16.dp
}
Card(
modifier = modifier
.padding(paddingTransition)
.semantics {
contentDescription = wallpaperName
if (isSelectionMode) selected = isSelected
}
.semantics { if (isSelectionMode) selected = isSelected }
.padding(padding)
.combinedClickable(
role = Role.Button,
onClick = onClick,
onLongClick = onLongClick
),
shape = RoundedCornerShape(roundedCornerShapeTransition),
shape = RoundedCornerShape(cornerRadius),
colors = if (isSelected) {
CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer
@@ -76,16 +59,7 @@ fun WallpaperItem(
}
) {
Box(modifier = Modifier.fillMaxSize()) {
AsyncImage(
model = ImageRequest.Builder(context)
.data(wallpaperUri.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
)
content()
if (isSelectionMode) {
Icon(
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff. Show more