Compare commits

..
203 Commits
Author SHA1 Message Date
Anthonyy232 66c3a4bb2e Bump version 2025-09-15 12:47:15 -07:00
Anthonyy232 1b317798a4 fix effects not applying to lock when singular
https://github.com/Anthonyy232/Paperize/issues/393
2025-09-15 12:46:18 -07:00
Anthonyy232 95feb975ea Bump version code 2025-09-13 16:06:10 -07:00
renovate[bot] bf1d2d4793 Update dependency com.google.devtools.ksp to v2.2.20-2.0.3 2025-09-13 14:29:01 -07:00
Anthonyy232 1f66b1c616 Updated dependencies and localization 2025-09-13 14:08:17 -07:00
renovate[bot] 8cee52fcd6 Update dependency androidx.compose.ui:ui-test-manifest to v1.9.1 2025-09-13 10:56:58 -07:00
renovate[bot] 44692cde8e Update dependency androidx.compose.ui:ui to v1.9.1 2025-09-13 10:55:00 -07:00
renovate[bot] 23359ee714 Update dependency androidx.compose.material3:material3 to v1.4.0-rc01 2025-09-13 10:54:50 -07:00
renovate[bot] 25004356b5 Update dependency androidx.compose.material:material to v1.9.1 2025-09-13 10:54:44 -07:00
renovate[bot] 7e4e5ff452 Update dependency androidx.compose.foundation:foundation to v1.9.1 2025-09-13 10:54:36 -07:00
renovate[bot] d63c1005b7 Update dependency androidx.compose.animation:animation to v1.9.1 2025-09-13 10:54:15 -07:00
renovate[bot] bf71bca11a Update kotlin monorepo to v2.2.20 2025-09-13 10:54:02 -07:00
Anthonyy232 c35b87a1da Updated localization 2025-09-13 10:53:42 -07:00
malteish afa520a68a enable large collections through larger cursor window 2025-09-12 11:43:08 -07:00
Anthonyy232 b67734b8e1 Fix file picker not limiting user for large image imports 2025-09-12 11:42:30 -07:00
Anthonyy232 d124da717d Fix crash on launch during db changes 2025-09-12 11:21:22 -07:00
Anthonyy232 40417b99b1 fix crash on adding through image virtual directory
https://github.com/Anthonyy232/Paperize/issues/374
2025-09-12 11:18:48 -07:00
Anthony La ba7d29990c Merge pull request #352 from Anthonyy232/renovate/androidx.lifecycle-lifecycle-runtime-compose-2.x
Update dependency androidx.lifecycle:lifecycle-runtime-compose to v2.9.3
2025-08-28 11:31:36 -07:00
renovate[bot] b18c5bdb1e Update dependency androidx.lifecycle:lifecycle-runtime-compose to v2.9.3 2025-08-28 18:31:17 +00:00
Anthony La 1191872b3e Merge pull request #351 from Anthonyy232/renovate/androidx.compose.material3-material3-1.x
Update dependency androidx.compose.material3:material3 to v1.4.0-beta03
2025-08-28 11:30:59 -07:00
Anthony La ae5a533baf Merge pull request #350 from Anthonyy232/renovate/androidx.compose-compose-bom-2025.x
Update dependency androidx.compose:compose-bom to v2025.08.01
2025-08-28 11:30:51 -07:00
renovate[bot] 9cc7c0e26a Update dependency androidx.compose.material3:material3 to v1.4.0-beta03 2025-08-28 18:30:44 +00:00
renovate[bot] 7ca5e2bac4 Update dependency androidx.compose:compose-bom to v2025.08.01 2025-08-28 18:30:41 +00:00
Anthony La e064c31175 Merge pull request #353 from Anthonyy232/renovate/androidx.lifecycle-lifecycle-runtime-ktx-2.x
Update dependency androidx.lifecycle:lifecycle-runtime-ktx to v2.9.3
2025-08-28 11:30:36 -07:00
Anthony La 8959e239fe Merge pull request #354 from Anthonyy232/renovate/actions-checkout-5.x
Update actions/checkout action to v5
2025-08-28 11:30:28 -07:00
Anthony La 06c9566df4 Merge pull request #355 from Anthonyy232/renovate/actions-setup-java-5.x
Update actions/setup-java action to v5
2025-08-28 11:30:22 -07:00
Anthony La 108f5cd9c1 Merge pull request #356 from Anthonyy232/renovate/major-github-artifact-actions
Update actions/download-artifact action to v5
2025-08-28 11:30:14 -07:00
renovate[bot] 9b86b54ae1 Update actions/setup-java action to v5 2025-08-28 18:26:05 +00:00
renovate[bot] 40e0884ee7 Update actions/download-artifact action to v5 2025-08-28 18:26:02 +00:00
renovate[bot] e1fa4e7890 Update actions/checkout action to v5 2025-08-28 18:25:59 +00:00
renovate[bot] 4161b8817b Update dependency androidx.lifecycle:lifecycle-runtime-ktx to v2.9.3 2025-08-28 18:25:53 +00:00
Anthony La 4554190912 Refactor CI/CD pipeline by removing lint job 2025-08-28 11:24:57 -07:00
Anthony La b714ad8eb6 Change branch reference from 'main' to 'master' 2025-08-28 11:19:29 -07:00
Anthony La 6cd5c1eed3 Change default branch to 'main' and enhance artifact management 2025-08-28 11:19:14 -07:00
Anthony La 6784e2a2de Change CI/CD branch from 'main' to 'master' 2025-08-28 11:09:36 -07:00
Anthony La 7f69debe1d Update CI/CD workflow for Android release process 2025-08-28 11:01:37 -07:00
Anthonyy232 f8df7c2a6a Fix master branch naming 2025-08-28 10:54:04 -07:00
Anthonyy232 b3fb2b82f2 Update CI/CD 2025-08-28 10:53:11 -07:00
Anthony La 04d0c57cb0 Add CI workflow for Android release 2025-08-28 10:48:57 -07:00
Anthonyy232 27b0fe62c8 Bump version code 2025-08-28 10:38:50 -07:00
Anthonyy232 096beb22d7 Bump version to 3.1.2 2025-08-28 10:37:50 -07:00
Anthonyy232 21766a5dc6 Fix app losing permission after some time https://github.com/Anthonyy232/Paperize/issues/349 2025-08-28 10:36:29 -07:00
Anthonyy232 fd5e8b63b2 Revert AGP
https://github.com/Anthonyy232/Paperize/issues/310#issuecomment-3226685236
2025-08-26 22:31:49 -07:00
Anthonyy232 2f514e6464 Remove unused AAR dependency
https://github.com/Anthonyy232/Paperize/issues/310#issuecomment-3226539843
2025-08-26 19:45:54 -07:00
Anthonyy232 74d2c614fd Update version code 2025-08-26 18:31:55 -07:00
Anthonyy232 da0d8c45e6 Fixed bad decompressing of URi 2025-08-26 18:11:07 -07:00
Anthony La e87d8116a6 Merge pull request #344 from Anthonyy232/renovate/hilt
Update hilt to v2.57.1
2025-08-26 18:04:42 -07:00
renovate[bot] 8aaff066b3 Update hilt to v2.57.1 2025-08-27 01:04:32 +00:00
Anthony La 685c9d1981 Merge pull request #346 from Anthonyy232/renovate/actions-upload-pages-artifact-4.x
Update actions/upload-pages-artifact action to v4
2025-08-26 18:04:25 -07:00
Anthony La 81ae25035e Merge pull request #347 from OasisAkari/skip_non-interactive
add skip in non-interactive state setting
2025-08-26 18:04:07 -07:00
yzhh 530ff36a16 add skip in non-interactive state setting 2025-08-25 22:18:15 +08:00
renovate[bot] 9fd52e7bc4 Update actions/upload-pages-artifact action to v4 2025-08-22 17:58:36 +00:00
Anthonyy232 0c2ca68dcd Fixed last change time not updating from initial 2025-08-20 11:09:33 -07:00
Anthony La e7c92eae71 Merge pull request #338 from Anthonyy232/renovate/androidx.compose.ui-ui-tooling-preview-1.x
Update dependency androidx.compose.ui:ui-tooling-preview to v1.9.0
2025-08-19 16:55:26 -07:00
Anthony La 7b26e323ac Merge pull request #339 from Anthonyy232/renovate/androidx.core-core-ktx-1.x
Update dependency androidx.core:core-ktx to v1.17.0
2025-08-19 16:55:19 -07:00
Anthony La b0069e3bc9 Merge pull request #340 from Anthonyy232/renovate/actions-checkout-5.x
Update actions/checkout action to v5
2025-08-19 16:55:13 -07:00
Anthony La 8582bc903b Merge pull request #341 from Anthonyy232/renovate/gradle-9.x
Update dependency gradle to v9
2025-08-19 16:55:07 -07:00
Anthony La 8690284ac2 Merge pull request #342 from Anthonyy232/renovate/sh.calvin.reorderable-reorderable-3.x
Update dependency sh.calvin.reorderable:reorderable to v3
2025-08-19 16:55:02 -07:00
Anthonyy232 c9e485ac88 Fixed time drift issue when setting wallpaper https://github.com/Anthonyy232/Paperize/issues/343 2025-08-19 16:49:28 -07:00
renovate[bot] 9d577880e0 Update dependency sh.calvin.reorderable:reorderable to v3 2025-08-19 22:26:59 +00:00
renovate[bot] 09bacfb3e5 Update dependency gradle to v9 2025-08-19 22:26:56 +00:00
renovate[bot] 3fd9cec67d Update actions/checkout action to v5 2025-08-19 22:23:59 +00:00
renovate[bot] ac7a1e0cb0 Update dependency androidx.core:core-ktx to v1.17.0 2025-08-19 22:23:56 +00:00
renovate[bot] 53ba0a2347 Update dependency androidx.compose.ui:ui-tooling-preview to v1.9.0 2025-08-19 22:23:54 +00:00
Anthonyy232 83cc89e1b3 Updated gradle version 2025-08-19 15:22:58 -07:00
Anthony La 655c4a91e5 Merge pull request #336 from Anthonyy232/renovate/androidx.compose.ui-ui-test-manifest-1.x
Update dependency androidx.compose.ui:ui-test-manifest to v1.9.0
2025-08-18 09:32:18 -07:00
renovate[bot] 083f269605 Update dependency androidx.compose.ui:ui-test-manifest to v1.9.0 2025-08-18 16:32:08 +00:00
Anthony La 9880bac0c6 Merge pull request #309 from Anthonyy232/renovate/ksp-monorepo
Update dependency com.google.devtools.ksp to v2.2.10-2.0.2
2025-08-18 09:31:46 -07:00
Anthony La 0f87776d16 Merge pull request #337 from Anthonyy232/renovate/androidx.compose.ui-ui-tooling-1.x
Update dependency androidx.compose.ui:ui-tooling to v1.9.0
2025-08-18 09:31:37 -07:00
renovate[bot] ed291459d1 Update dependency com.google.devtools.ksp to v2.2.10-2.0.2 2025-08-18 16:31:29 +00:00
Anthony La bc1eb7f996 Merge pull request #334 from Anthonyy232/renovate/androidx.compose.ui-ui-graphics-1.x
Update dependency androidx.compose.ui:ui-graphics to v1.9.0
2025-08-18 09:31:22 -07:00
Anthony La 8366965a03 Merge pull request #330 from Anthonyy232/renovate/androidx.compose.animation-animation-1.x
Update dependency androidx.compose.animation:animation to v1.9.0
2025-08-18 09:31:08 -07:00
Anthony La 904f77191c Merge pull request #315 from Anthonyy232/renovate/com.github.skydoves-landscapist-glide-2.x
Update dependency com.github.skydoves:landscapist-glide to v2.5.2
2025-08-18 09:31:01 -07:00
renovate[bot] ec9f56cf1e Update dependency androidx.compose.ui:ui-tooling to v1.9.0 2025-08-18 16:30:49 +00:00
renovate[bot] 980527cdde Update dependency androidx.compose.ui:ui-graphics to v1.9.0 2025-08-18 16:30:42 +00:00
renovate[bot] efe794c63f Update dependency androidx.compose.animation:animation to v1.9.0 2025-08-18 16:30:38 +00:00
renovate[bot] 65a677ea91 Update dependency com.github.skydoves:landscapist-glide to v2.5.2 2025-08-18 16:30:29 +00:00
Anthony La dabf63fc58 Merge pull request #331 from Anthonyy232/renovate/androidx.compose.foundation-foundation-1.x
Update dependency androidx.compose.foundation:foundation to v1.9.0
2025-08-18 09:28:28 -07:00
Anthony La 1da95e09b5 Merge pull request #332 from Anthonyy232/renovate/androidx.compose.material-material-1.x
Update dependency androidx.compose.material:material to v1.9.0
2025-08-18 09:28:19 -07:00
Anthony La ad195a985e Merge pull request #333 from Anthonyy232/renovate/androidx.compose.ui-ui-1.x
Update dependency androidx.compose.ui:ui to v1.9.0
2025-08-18 09:28:11 -07:00
Anthony La 0e06584780 Merge pull request #335 from Anthonyy232/renovate/androidx.compose.ui-ui-test-junit4-1.x
Update dependency androidx.compose.ui:ui-test-junit4 to v1.9.0
2025-08-18 09:27:47 -07:00
Anthony La a6f44ecad5 Merge pull request #329 from Anthonyy232/renovate/androidx.compose-compose-bom-2025.x
Update dependency androidx.compose:compose-bom to v2025.08.00
2025-08-18 09:27:36 -07:00
Anthony La d527fa9a80 Merge pull request #320 from Anthonyy232/renovate/gradle-8.x
Update dependency gradle to v8.14.3
2025-08-18 09:26:52 -07:00
Anthony La ffe360ee80 Merge pull request #316 from Anthonyy232/renovate/androidx.compose.material3-material3-1.x
Update dependency androidx.compose.material3:material3 to v1.4.0-beta02
2025-08-18 09:26:25 -07:00
renovate[bot] 8fd9c9b80e Update dependency androidx.compose.material3:material3 to v1.4.0-beta02 2025-08-18 16:26:17 +00:00
Anthony La d77f2fe8df Merge pull request #308 from Anthonyy232/renovate/kotlin-monorepo
Update kotlin monorepo to v2.2.10
2025-08-18 09:25:51 -07:00
renovate[bot] 86c44825d9 Update dependency androidx.compose.ui:ui-test-junit4 to v1.9.0 2025-08-15 18:37:57 +00:00
renovate[bot] b5d8bb5548 Update dependency androidx.compose.ui:ui to v1.9.0 2025-08-15 18:37:51 +00:00
renovate[bot] 9000be1951 Update dependency androidx.compose.material:material to v1.9.0 2025-08-15 18:37:48 +00:00
renovate[bot] 38ba5154f9 Update dependency androidx.compose.foundation:foundation to v1.9.0 2025-08-15 18:37:45 +00:00
renovate[bot] 9f670031b1 Update dependency androidx.compose:compose-bom to v2025.08.00 2025-08-15 18:37:40 +00:00
renovate[bot] c0dd7baeaa Update kotlin monorepo to v2.2.10 2025-08-15 18:37:37 +00:00
renovate[bot] 1c96dcfc4a Update dependency gradle to v8.14.3 2025-08-15 18:37:34 +00:00
Anthonyy232 2a3821e1e7 Improved robustness of image picker for album view screen 2025-08-15 09:40:03 -07:00
Anthonyy232 8b61b1d719 Improved robustness of image picker 2025-08-15 09:38:46 -07:00
Anthonyy232 431df5c334 Fixed next and last time label swapped based on temporal locality https://github.com/Anthonyy232/Paperize/issues/327 2025-08-15 09:35:46 -07:00
Anthonyy232 2b49a01eb4 Added setting to prevent changing wallpaper during landscape mode https://github.com/Anthonyy232/Paperize/issues/328 2025-08-14 23:33:40 -07:00
Anthonyy232 3bc438a06d Migrated blur to rendereffect and min version to 31 2025-08-13 19:50:49 -07:00
Anthonyy232 57d6b7dc8e Fixed broken blur effect using home percentage for all cases https://github.com/Anthonyy232/Paperize/issues/322 2025-08-12 17:05:12 -07:00
Anthonyy232 5d87257516 Fixed scanning for new wallpapers/folders https://github.com/Anthonyy232/Paperize/issues/326 2025-08-11 11:28:29 -07:00
Anthonyy232 cb9ab7d1af Fixed crash due to interpreting string as int without cast https://github.com/Anthonyy232/Paperize/issues/323 2025-08-07 11:28:23 -07:00
Anthony La 598f00c536 Merge pull request #305 from Anthonyy232/renovate/gradle-8.x
Update dependency gradle to v8.14.2
2025-06-24 10:39:51 -07:00
renovate[bot] 426dbf1457 Update dependency gradle to v8.14.2 2025-06-24 17:38:34 +00:00
Anthony La ba1b139f40 Merge pull request #304 from Anthonyy232/renovate/ksp-monorepo
Update dependency com.google.devtools.ksp to v2.1.21-2.0.2
2025-06-24 10:31:17 -07:00
renovate[bot] 40dc4b788d Update dependency com.google.devtools.ksp to v2.1.21-2.0.2 2025-06-24 17:30:04 +00:00
Anthony La 69d5ec6477 Updated dependencies 2025-06-24 10:29:13 -07:00
Anthony La 96cb5538da Updated localization 2025-06-24 10:07:02 -07:00
Anthony La c3101ea5f6 Update in sample calculation for None scaling 2025-06-24 10:06:21 -07:00
Anthony La 493e6559df Major refactor and localization update 2025-06-07 14:02:49 -07:00
Anthony La 8945002652 Updated WallpaperManager usage 2025-05-15 17:00:51 -07:00
Anthony La 8f30f3558a Update renderscript dependency and refactored wallpaper alarm code 2025-05-15 15:30:19 -07:00
Anthony La 15ba07198d Merge pull request #288 from Anthonyy232/renovate/ksp-monorepo
Update dependency com.google.devtools.ksp to v2.1.21-2.0.1
2025-05-14 18:21:18 -07:00
Anthony La 39fff2bfc9 Merge pull request #267 from Anthonyy232/renovate/com.google.dagger-hilt-android-2.x
Update dependency com.google.dagger:hilt-android to v2.56.2
2025-05-14 18:21:06 -07:00
Anthony La 8339c2d86b Merge pull request #287 from Anthonyy232/renovate/com.google.code.gson-gson-2.x
Update dependency com.google.code.gson:gson to v2.13.1
2025-05-14 18:20:54 -07:00
renovate[bot] 29ca2d1c50 Update dependency com.google.devtools.ksp to v2.1.21-2.0.1 2025-05-15 01:20:40 +00:00
renovate[bot] 8b2cd301c9 Update dependency com.google.dagger:hilt-android to v2.56.2 2025-05-15 01:20:38 +00:00
renovate[bot] 5240320d99 Update dependency com.google.code.gson:gson to v2.13.1 2025-05-15 01:20:34 +00:00
Anthony La 25205d579b Merge pull request #268 from Anthonyy232/renovate/com.google.dagger-hilt-android-compiler-2.x
Update dependency com.google.dagger:hilt-android-compiler to v2.56.2
2025-05-14 18:19:26 -07:00
Anthony La 32c904f504 Merge pull request #285 from Anthonyy232/renovate/com.github.skydoves-landscapist-glide-2.x
Update dependency com.github.skydoves:landscapist-glide to v2.4.8
2025-05-14 18:19:15 -07:00
Anthony La 9e3a62a283 Merge pull request #286 from Anthonyy232/renovate/com.google.accompanist-accompanist-permissions-0.x
Update dependency com.google.accompanist:accompanist-permissions to v0.37.3
2025-05-14 18:19:07 -07:00
Anthony La 050e172949 Merge pull request #266 from Anthonyy232/renovate/hilt
Update dependency com.google.dagger.hilt.android to v2.56.2
2025-05-14 18:18:55 -07:00
renovate[bot] b231fe8f4e Update dependency com.google.dagger.hilt.android to v2.56.2 2025-05-15 00:30:23 +00:00
renovate[bot] 14c2fd8aed Update dependency com.google.dagger:hilt-android-compiler to v2.56.2 2025-05-15 00:30:20 +00:00
renovate[bot] 27ac32648c Update dependency com.google.accompanist:accompanist-permissions to v0.37.3 2025-05-15 00:30:13 +00:00
renovate[bot] f6c3a4b34a Update dependency com.github.skydoves:landscapist-glide to v2.4.8 2025-05-15 00:30:08 +00:00
Anthony La fcf0513356 Updated dependencies 2025-05-14 17:29:18 -07:00
Anthony La 26f51acc0c Merge pull request #277 from Nikster3k/master
Add scrollable Column to AlbumBottomSheet
2025-04-28 19:14:37 -07:00
Nikster3k 9a36ad35e4 Fix album selection taking up too much space 2025-04-27 17:15:20 +00:00
Anthony La 4771eaaa7e Merge pull request #278 from Anthonyy232/docFileCompat_test
Improve reliability of alarm manager
2025-04-25 23:30:07 -07:00
Anthony La 170a642858 Fix alarm manager handler crash 2025-04-25 23:29:29 -07:00
Nikster3k 2dd4fb9e58 Add scrollable Column to AlbumBottomSheet
When you had more than 10 albums they would be hidden
2025-04-25 15:01:10 +00:00
Anthony La 77c95ed14a Fix test code 2025-04-14 13:43:38 -07:00
Anthony La 75b3467f89 Remove unused imports 2025-04-14 13:41:22 -07:00
Anthony La 7c77f4a75e Merge pull request #204 from Anthonyy232/renovate/gradle-8.x
Update dependency gradle to v8.14-rc-1
2025-04-12 00:51:24 -07:00
Anthony La a36403ee14 Merge pull request #257 from Anthonyy232/renovate/ksp-monorepo
Update dependency com.google.devtools.ksp to v2.1.20-2.0.0
2025-04-12 00:51:13 -07:00
Anthony La 31c99f3e6e Remove unused imports 2025-04-12 00:31:56 -07:00
Anthony La fdd85b2df3 Removed unused marker 2025-04-12 00:31:00 -07:00
Anthony La 1e971d4ec3 Implemented toggle for wallpaper refresh 2025-04-12 00:20:17 -07:00
renovate[bot] 1274349fc9 Update dependency gradle to v8.14-rc-1 2025-04-12 06:10:59 +00:00
renovate[bot] f2065c3ec8 Update dependency com.google.devtools.ksp to v2.1.20-2.0.0 2025-04-12 06:07:51 +00:00
Anthony La bb34c1e02f Updated dependencies and reset database and app version 2025-04-11 23:07:10 -07:00
Anthony La 41ac2482d8 Update zoomable dependency 2025-04-06 23:13:15 -07:00
Anthony La 9baacea029 Fixed a bug where using only folders would cause album to self-delete 2025-04-05 01:07:21 -07:00
Anthony La 1d87208dca Localization fix 2025-04-02 22:20:13 -07:00
Anthony La af315b7775 Localization fix 2025-04-02 22:15:36 -07:00
Anthony La 212d21761b Localization update 2025-04-02 22:04:20 -07:00
Anthony La eb48200149 Implemented wallpaper changer widget (1x1 icon) 2025-04-01 13:46:23 -07:00
Anthony La 814db9020a Fix wallpaper changing time not accurate 2025-04-01 12:04:00 -07:00
Anthony La 893a729093 Fix wallpaper changing time not accurate 2025-04-01 12:03:46 -07:00
Anthony La 43b06d11eb Fix wallpaper color banding 2025-03-31 22:52:21 -07:00
Anthony La 3e9e8ca299 Fixed service not starting 2025-03-07 18:01:56 -08:00
Anthony La 0a6ce5bf07 Improved memory usage 2025-02-16 14:07:55 -08:00
Anthony La 813eb7fb32 Refactored wallpaper service 2025-02-16 11:45:11 -08:00
Anthony La e30056eb5d Implement non-shuffle setting 2025-01-25 15:32:15 -08:00
Anthony La 7f039fa2b4 Refactored app flow and album logic 2025-01-24 12:07:59 -08:00
Anthony La 9be3a9c6d3 Refactored app flow and album logic 2025-01-24 12:07:59 -08:00
Anthony La a8989b0810 Merge pull request #238 from DevBhalavat/master
Update CurrentAndNextChange.kt
2025-01-22 18:03:34 -08:00
bhalavatdev c9f27e3157 Update CurrentAndNextChange.kt 2025-01-03 00:03:53 +05:30
Anthony La 26f1e17b7c Refactored album view and album logic 2024-11-14 22:18:23 -08:00
Anthony La 47fa7563c0 Refactored folder view 2024-11-13 22:06:59 -08:00
Anthony La f2fc197df7 Added sorting 2024-11-13 21:30:14 -08:00
Anthony La 647ebea95b Fixed scoping for service 2024-11-04 11:06:43 -08:00
Anthony La eebc4d4ee4 Fixed slow updates when wallpaper changing 2024-11-04 11:02:11 -08:00
Anthony La e1ff89d3d9 chore/Refactor WallpaperScreenViewModel.kt and selected album for flow usage 2024-11-04 10:48:13 -08:00
Anthony La 11d72a2336 chore/Refactor usage of flow for settings viewmodel 2024-11-04 10:34:53 -08:00
Anthony La 68e6544da8 chore/Refactor code 2024-11-03 16:53:14 -08:00
Anthony La a26f7e30a4 Fixed staggered alarms 2024-11-03 16:53:14 -08:00
Anthony La b989a47b9e Fixed staggered alarms 2024-11-03 16:53:14 -08:00
Anthony La a7f98989b3 Merge pull request #220 from Anthonyy232/renovate/composebom
Update dependency androidx.compose:compose-bom to v2024.10.01
2024-10-31 12:22:16 -07:00
renovate[bot] 4aaded50ac Update dependency androidx.compose:compose-bom to v2024.10.01 2024-10-31 19:04:20 +00:00
Anthony La 3089841a05 Merge pull request #212 from Anthonyy232/renovate/animation
Update dependency androidx.compose.animation:animation to v1.7.5
2024-10-31 12:01:30 -07:00
Anthony La eeabdd24fd Merge pull request #213 from Anthonyy232/renovate/foundation
Update dependency androidx.compose.foundation:foundation to v1.7.5
2024-10-31 12:01:23 -07:00
Anthony La 8c82ed7d8c Merge pull request #214 from Anthonyy232/renovate/material3
Update dependency androidx.compose.material3:material3 to v1.3.1
2024-10-31 12:01:16 -07:00
renovate[bot] 5fd289afb5 Update dependency androidx.compose.material3:material3 to v1.3.1 2024-10-31 19:01:00 +00:00
renovate[bot] 8d0213c7bb Update dependency androidx.compose.foundation:foundation to v1.7.5 2024-10-31 19:00:57 +00:00
renovate[bot] 7e8b83aefe Update dependency androidx.compose.animation:animation to v1.7.5 2024-10-31 19:00:54 +00:00
Anthony La 136432b97b Merge pull request #215 from Anthonyy232/renovate/workruntimektx
Update dependency androidx.work:work-runtime-ktx to v2.10.0
2024-10-31 11:58:24 -07:00
renovate[bot] cbcf71da8a Update dependency androidx.work:work-runtime-ktx to v2.10.0 2024-10-31 18:58:18 +00:00
Anthony La 9bc58aa9fe Merge pull request #216 from Anthonyy232/renovate/lifecycleruntimektx
Update lifecycleRuntimeKtx to v2.8.7
2024-10-31 11:58:17 -07:00
Anthony La 74e3fd8878 Merge pull request #217 from Anthonyy232/renovate/material
Update material to v1.7.5
2024-10-31 11:58:02 -07:00
Anthony La c857f4a1e7 Merge pull request #218 from Anthonyy232/renovate/ui
Update ui to v1.7.5
2024-10-31 11:57:53 -07:00
Anthony La fb853086e6 Merge pull request #219 from Anthonyy232/renovate/corektx
Update dependency androidx.core:core-ktx to v1.15.0
2024-10-31 11:57:47 -07:00
renovate[bot] 54f4130bab Update dependency androidx.core:core-ktx to v1.15.0 2024-10-31 04:42:07 +00:00
renovate[bot] 2acc11875b Update ui to v1.7.5 2024-10-31 04:42:03 +00:00
renovate[bot] 0c1b341ce9 Update material to v1.7.5 2024-10-31 01:32:48 +00:00
renovate[bot] b4d89a54e3 Update lifecycleRuntimeKtx to v2.8.7 2024-10-31 01:32:45 +00:00
Anthony La c7d3ae137f Merge pull request #211 from Anthonyy232/renovate/lottiecompose
Update dependency com.airbnb.android:lottie-compose to v6.6.0
2024-10-28 00:39:51 -07:00
renovate[bot] e71ae4fda1 Update dependency com.airbnb.android:lottie-compose to v6.6.0 2024-10-27 21:52:59 +00:00
Anthony La 8c111ffaf2 Merge pull request #208 from Anthonyy232/renovate/ksp
Update dependency com.google.devtools.ksp to v2.0.21-1.0.26
2024-10-24 13:04:06 -07:00
Anthony La 238c7b512a Merge pull request #210 from Anthonyy232/renovate/workruntimektx
Update dependency androidx.work:work-runtime-ktx to v2.10.0-rc01
2024-10-24 13:03:57 -07:00
renovate[bot] 68e5be5214 Update dependency androidx.work:work-runtime-ktx to v2.10.0-rc01 2024-10-24 18:02:57 +00:00
renovate[bot] b417da22a2 Update dependency com.google.devtools.ksp to v2.0.21-1.0.26 2024-10-23 21:05:36 +00:00
Anthony La 3758363dd3 Downgraded Gradle to 8.10
Upgraded AGP to 8.7.1
Updated dependencies
2024-10-17 22:04:13 -07:00
Anthony La b7587e419b Downgraded AGP to 8.6.0 2024-10-14 10:50:16 -07:00
Anthony La 4decb78017 Revert baseline profiles due to reproducible build error 2024-10-14 01:09:57 -07:00
Anthony La 129e0c36fa Merge pull request #193 from Anthonyy232/renovate/landscapistglide
Update dependency com.github.skydoves:landscapist-glide to v2.4.1
2024-10-13 12:29:58 -07:00
renovate[bot] a784ff2cd8 Update dependency com.github.skydoves:landscapist-glide to v2.4.1 2024-10-13 19:26:51 +00:00
Anthony La 52badae681 Updated version code 2024-10-13 12:26:25 -07:00
Anthony La 2bfd46d5f5 Updated baseline profile dependencies 2024-10-13 01:40:51 -07:00
Anthony La 10240aaa4e Remove duplicate line 2024-10-13 01:34:52 -07:00
Anthony La 4855d59e99 Revert NDK version upgrade 2024-10-13 01:27:28 -07:00
Anthony La 59594878ab Downgraded NDK version to LTS 2024-10-12 01:27:29 -07:00
Anthony La 7fc552ab67 Updated apk naming 2024-10-12 00:47:15 -07:00
164 changed files with 9746 additions and 111950 deletions

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
# ===================================================================
# Paperize CI/CD Pipeline
#
# Automates the building and release process for the Paperize Android application.
#
# Workflow Architecture:
# 1. Build: Compiles and signs the release APK.
# 2. Release: Publishes the APK to a draft GitHub Release, but only for version tags.
#
# Triggering Conditions:
# - On push to `master`:
# - Executes the `build` job.
# - Produces a versioned build artifact for testing and internal distribution.
# - On push of a tag (e.g., `v1.2.3`):
# - Executes both jobs: `build` and `release`.
# - Creates a formal, versioned draft release on GitHub with the signed APK attached.
# ===================================================================
name: Paperize CI/CD Pipeline
on:
push:
branches: [ "master" ]
tags: [ 'v*' ]
jobs:
# ===================================================================
# JOB: build
#
# Compiles, signs, and packages the release APK. This job produces a
# versioned artifact that is used for both internal testing and the final release.
# ===================================================================
build:
name: Build Signed APK
runs-on: ubuntu-latest
steps:
- name: Checkout repository source code
uses: actions/checkout@v5
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
java-version: '17'
distribution: 'temurin'
cache: gradle
- name: Grant execute permission for gradlew
# The gradlew wrapper requires execute permissions to run on the Linux-based runner.
run: chmod +x gradlew
- name: Decode Base64 Keystore
# Reconstructs the binary .jks keystore file from the Base64 encoded secret.
env:
SIGNING_KEYSTORE_BASE64: ${{ secrets.SIGNING_KEYSTORE_BASE64 }}
run: |
echo $SIGNING_KEYSTORE_BASE64 | base64 --decode > ${{ github.workspace }}/keystore.jks
- name: Build Release APK
env:
SIGNING_KEYSTORE_PATH: ${{ github.workspace }}/keystore.jks
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
run: ./gradlew assembleRelease
- name: Get Version Name
# Determines the application version for artifact naming.
# - For tag pushes (e.g., 'v1.2.3'), it uses the tag name directly.
# - For master branch pushes, it parses the `versionName` from the app's build.gradle.kts file.
id: get_version
shell: bash
run: |
if [[ $GITHUB_REF == refs/tags/v* ]]; then
VERSION_NAME=${GITHUB_REF_NAME}
else
RAW_VERSION=$(grep "versionName =" app/build.gradle.kts | awk -F'"' '{print $2}')
VERSION_NAME="v${RAW_VERSION}"
fi
echo "VERSION_NAME=$VERSION_NAME" >> $GITHUB_OUTPUT
- name: Upload APK as a build artifact
# Archives the generated APK with a dynamic, versioned name. This artifact is essential
# for passing the APK file to the subsequent `release` job.
uses: actions/upload-artifact@v4
with:
name: paperize-${{ steps.get_version.outputs.VERSION_NAME }}
path: app/build/outputs/apk/release/paperize-v*.apk
if-no-files-found: error
# ===================================================================
# JOB: release
#
# Creates a draft GitHub Release and attaches the signed APK. This job is
# conditional and will only execute for pushes that include a version tag.
# ===================================================================
release:
name: Create GitHub Release
runs-on: ubuntu-latest
needs: build
if: startsWith(github.ref, 'refs/tags/')
steps:
- name: Download signed APK artifact
# Downloads the versioned artifact produced by the `build` job. The pattern ensures
# it finds the correct artifact regardless of the specific version number.
uses: actions/download-artifact@v5
with:
pattern: paperize-v*
path: ./apk-artifact
merge-multiple: true
- name: Create Draft Release
# Publishes a new release to GitHub. `draft: true` ensures the release is not made
# public until it has been manually reviewed and published.
uses: softprops/action-gh-release@v2
with:
files: ./apk-artifact/paperize-v*.apk
draft: true
generate_release_notes: true
+2 -2
View File
@@ -30,11 +30,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
uses: actions/upload-pages-artifact@v4
with:
# Upload entire repository
path: '.'
+32 -31
View File
@@ -4,9 +4,7 @@ plugins {
alias(libs.plugins.kotlinCompose)
alias(libs.plugins.hiltAndroid)
alias(libs.plugins.ksp)
alias(libs.plugins.aboutLibraries)
alias(libs.plugins.kotlinSerialization)
alias(libs.plugins.baselineProfile)
}
ksp {
@@ -15,14 +13,27 @@ ksp {
android {
namespace = "com.anthonyla.paperize"
compileSdk = 35
compileSdk = 36
signingConfigs {
create("release") {
val storeFilePath = System.getenv("SIGNING_KEYSTORE_PATH")
if (storeFilePath != null) {
storeFile = file(storeFilePath)
storePassword = System.getenv("SIGNING_STORE_PASSWORD")
keyAlias = System.getenv("SIGNING_KEY_ALIAS")
keyPassword = System.getenv("SIGNING_KEY_PASSWORD")
}
}
}
defaultConfig {
applicationId = "com.anthonyla.paperize"
minSdk = 26
targetSdk = 35
versionCode = 33
versionName = "2.3.1"
minSdk = 31
targetSdk = 36
versionCode = 42
versionName = "3.2.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
@@ -37,6 +48,7 @@ android {
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
signingConfig = signingConfigs.getByName("release")
}
}
@@ -45,6 +57,7 @@ android {
targetCompatibility = JavaVersion.VERSION_17
}
@Suppress("DEPRECATION")
kotlinOptions {
jvmTarget = "17"
}
@@ -55,35 +68,24 @@ android {
buildConfig = true
}
@Suppress("UnstableApiUsage")
androidResources {
@Suppress("UnstableApiUsage")
generateLocaleConfig = true
}
ndkVersion = "28.0.12433566"
buildToolsVersion = "35.0.0"
buildToolsVersion = "35.0.1"
dependenciesInfo {
includeInApk = false
includeInBundle = false
}
aboutLibraries {
excludeFields = arrayOf("generated")
}
androidComponents {
onVariants { variant ->
variant.outputs.forEach { output ->
val apkName = "paperize-v${output.versionName}"
output.versionName.set(apkName)
applicationVariants.all {
this.outputs
.map { it as com.android.build.gradle.internal.api.ApkVariantOutputImpl }
.forEach { output ->
val apkName = "paperize-v${this.versionName}.apk"
output.outputFileName = apkName
}
}
}
}
androidComponents {
onVariants(selector().withBuildType("release")) {
it.packaging.resources.excludes.add("META-INF/**")
}
}
@@ -113,18 +115,18 @@ dependencies {
implementation(libs.androidx.hilt.work)
implementation(libs.lottie.compose)
implementation(libs.accompanist.permissions)
implementation(libs.aboutlibraries.core)
implementation(libs.aboutlibraries.compose.m3)
implementation(libs.androidx.foundation)
implementation(libs.lazycolumnscrollbar)
implementation(libs.taskerpluginlibrary)
implementation(libs.filament.android)
implementation(libs.androidx.profileinstaller)
implementation(libs.reorderable)
implementation(libs.androidx.glance.appwidget)
implementation(libs.androidx.glance.material3)
implementation(libs.androidx.glance.material)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(libs.androidx.ui.test.junit4)
"baselineProfile"(project(":baselineprofile"))
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
implementation(libs.hilt.android)
@@ -134,6 +136,5 @@ dependencies {
implementation(libs.androidx.room.ktx)
implementation(libs.dfc)
implementation (libs.kotlinx.serialization.json)
implementation(libs.renderscript.intrinsics.replacement.toolkit)
implementation(libs.toolbar.compose)
}
+15
View File
@@ -23,6 +23,8 @@
-keep class com.google.gson.reflect.TypeToken { *; }
-keep class * extends com.google.gson.reflect.TypeToken
-keep class kotlin.coroutines.Continuation
-keep class androidx.datastore.*.** {*;}
-keepclassmembers class com.anthonyla.paperize.feature.wallpaper.domain.model.Album {
!transient <fields>;
}
@@ -35,3 +37,16 @@
-keepclassmembers class com.anthonyla.paperize.feature.wallpaper.domain.model.Folder {
!transient <fields>;
}
# Keep wallpaper services and their action enums
-keep class com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService { *; }
-keep class com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService$Actions { *; }
-keep class com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperService { *; }
-keep class com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperService$Actions { *; }
# Keep WallpaperAction classes
-keep class com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAction { *; }
-keep class com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAction$* { *; }
# Keep Type enum
-keep class com.anthonyla.paperize.core.Type { *; }
+21 -6
View File
@@ -2,14 +2,15 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<application
android:allowBackup="false"
@@ -20,6 +21,7 @@
android:icon="@mipmap/app_icon"
android:label="@string/app_name"
android:supportsRtl="true"
android:enableOnBackInvokedCallback="true"
android:theme="@style/Theme.Paperize" tools:targetApi="tiramisu">
<activity
android:name=".feature.wallpaper.presentation.MainActivity"
@@ -36,8 +38,10 @@
android:theme="@android:style/Theme.NoDisplay">
</activity>
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver" />
<service android:name=".feature.wallpaper.wallpaper_service.HomeWallpaperService" />
<service android:name=".feature.wallpaper.wallpaper_service.LockWallpaperService" />
<service android:name=".feature.wallpaper.wallpaper_service.HomeWallpaperService"
android:foregroundServiceType="dataSync|specialUse" />
<service android:name=".feature.wallpaper.wallpaper_service.LockWallpaperService"
android:foregroundServiceType="dataSync|specialUse" />
<service
android:name=".feature.wallpaper.wallpaper_tile.ChangeWallpaperTileService"
android:exported="true"
@@ -52,8 +56,18 @@
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="com.anthonyla.paperize.SHORTCUT" />
</intent-filter>
</receiver>
<receiver android:name="com.anthonyla.paperize.feature.wallpaper.glance_widget.PaperizeWidgetReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/paperize_widget_info" />
</receiver>
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
@@ -81,4 +95,5 @@
</intent-filter>
</activity>
</application>
</manifest>
</manifest>
@@ -1,9 +1,13 @@
package com.anthonyla.paperize
import android.annotation.SuppressLint
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.database.CursorWindow
import dagger.hilt.android.HiltAndroidApp
import java.lang.reflect.Field
/**
* Application class for Hilt
@@ -12,6 +16,24 @@ import dagger.hilt.android.HiltAndroidApp
class App: Application() {
override fun onCreate() {
super.onCreate()
// Increase CursorWindow size to handle large datasets
// Default is usually 2MB, increasing to 10MB
try {
val field: Field = CursorWindow::class.java.getDeclaredField("sCursorWindowSize")
field.isAccessible = true
field.set(null, 10 * 1024 * 1024) // 10MB
} catch (e: Exception) {
// Fallback for newer Android versions where field might be different
try {
val field: Field = CursorWindow::class.java.getDeclaredField("CURSOR_WINDOW_SIZE")
field.isAccessible = true
field.set(null, 10 * 1024 * 1024) // 10MB
} catch (e2: Exception) {
e2.printStackTrace()
}
}
val channel = NotificationChannel("wallpaper_service_channel", "Paperize", NotificationManager.IMPORTANCE_LOW)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
@@ -18,6 +18,7 @@ object SettingsConstants {
const val LOCK_ALBUM_NAME = "lock_album_name"
const val HOME_WALLPAPER_CHANGE_INTERVAL = "home_wallpaper_change_interval"
const val LOCK_WALLPAPER_CHANGE_INTERVAL = "lock_wallpaper_change_interval"
const val REFRESH = "refresh"
const val WALLPAPER_CHANGE_INTERVAL_DEFAULT = 15
const val WALLPAPER_CHANGE_INTERVAL_MIN = 1
const val FIRST_LAUNCH = "first_launch"
@@ -45,4 +46,7 @@ object SettingsConstants {
const val CHANGE_START_TIME = "change_start_time"
const val START_HOUR = "start_hour"
const val START_MINUTE = "start_minute"
const val SHUFFLE = "shuffle"
const val SKIP_LANDSCAPE = "skip_landscape"
const val SKIP_NON_INTERACTIVE = "skip_non_interactive"
}
@@ -1,7 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
package com.anthonyla.paperize.core
import android.graphics.Bitmap
import com.anthonyla.paperize.core.vignetteBitmap
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.util.Util
@@ -8,14 +8,16 @@ 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.RadialGradient
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Shader
import android.net.Uri
import android.os.Build
import android.provider.DocumentsContract
import android.util.Base64
import android.util.DisplayMetrics
import android.util.Log
import android.util.Size
@@ -23,15 +25,29 @@ import android.view.WindowManager
import android.view.WindowMetrics
import androidx.annotation.RequiresApi
import androidx.compose.ui.util.fastRoundToInt
import androidx.core.graphics.createBitmap
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import androidx.exifinterface.media.ExifInterface
import com.anthonyla.paperize.core.ScreenMetricsCompat.getScreenSize
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Metadata
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.google.android.renderscript.Toolkit
import com.lazygeniouz.dfc.file.DocumentFileCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.charset.Charset
import java.util.zip.DeflaterOutputStream
import java.util.zip.InflaterInputStream
import android.graphics.PixelFormat
import android.graphics.RenderEffect
import android.graphics.RenderNode
import android.hardware.HardwareBuffer
import android.media.ImageReader
import kotlin.compareTo
import kotlin.or
enum class Type { HOME, LOCK, SINGLE, REFRESH }
@@ -39,39 +55,49 @@ enum class Type { HOME, LOCK, SINGLE, REFRESH }
* Get the dimensions of the image from the uri
*/
fun Uri.getImageDimensions(context: Context): Size? {
return try {
try {
context.contentResolver.openInputStream(this)?.use { inputStream ->
val exif = ExifInterface(inputStream)
var width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
var height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
if (width == 0 || height == 0) {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(
context.contentResolver.openInputStream(this),
null,
options
)
width = options.outWidth
height = options.outHeight
val width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
val height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
if (width > 0 && height > 0) {
return Size(width, height)
}
Size(width, height)
}
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error getting image dimensions: $e")
null
Log.w("WallpaperUtil", "Error reading EXIF dimensions for $this, falling back: $e")
}
try {
context.contentResolver.openInputStream(this)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(inputStream, null, options)
if (options.outWidth > 0 && options.outHeight > 0) {
return Size(options.outWidth, options.outHeight)
}
}
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error getting image dimensions with BitmapFactory for $this: $e")
return null
}
Log.w("WallpaperUtil", "Could not get image dimensions for $this")
return null
}
/**
* Calculate the inSampleSize for the image
*/
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) {
val heightRatio = (imageSize.height.toFloat() / height.toFloat()).fastRoundToInt()
val widthRatio = (imageSize.width.toFloat() / width.toFloat()).fastRoundToInt()
return if (heightRatio < widthRatio) { heightRatio } else { widthRatio }
return (if (heightRatio < widthRatio) heightRatio else widthRatio).coerceAtLeast(1)
}
else { return 1 }
}
@@ -81,13 +107,13 @@ fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
* https://stackoverflow.com/a/70087378
*/
object ScreenMetricsCompat {
private val api: Api =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30() else Api()
private val api: Api = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30() else Api()
fun getScreenSize(context: Context): Size = api.getScreenSize(context)
@Suppress("DEPRECATION")
private open class Api {
open fun getScreenSize(context: Context): Size {
val display = context.getSystemService(WindowManager::class.java).defaultDisplay
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = windowManager.defaultDisplay
val metrics = if (display != null) {
DisplayMetrics().also { display.getRealMetrics(it) }
} else {
@@ -100,7 +126,8 @@ object ScreenMetricsCompat {
@RequiresApi(Build.VERSION_CODES.R)
private class ApiLevel30 : Api() {
override fun getScreenSize(context: Context): Size {
val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val metrics: WindowMetrics = windowManager.currentWindowMetrics
return Size(metrics.bounds.width(), metrics.bounds.height())
}
}
@@ -113,9 +140,9 @@ fun getDeviceScreenSize(context: Context): Size {
val orientation = context.resources.configuration.orientation
val size = getScreenSize(context)
return if (orientation == Configuration.ORIENTATION_PORTRAIT) {
Size(size.width, size.height)
Size(minOf(size.width, size.height), maxOf(size.width, size.height))
} else {
Size(size.height, size.width)
Size(maxOf(size.width, size.height), minOf(size.width, size.height))
}
}
@@ -126,27 +153,33 @@ fun retrieveBitmap(
context: Context,
wallpaper: Uri,
width: Int,
height: Int
height: Int,
scaling: ScalingConstants = ScalingConstants.FIT
): Bitmap? {
val imageSize = wallpaper.getImageDimensions(context) ?: return null
if (imageSize.width <= 0 || imageSize.height <= 0) {
Log.e("WallpaperUtil", "Invalid image dimensions from URI: $imageSize")
return null
}
val sampleSize = if (scaling == ScalingConstants.NONE) {
1
} else {
calculateInSampleSize(imageSize, width, height)
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSampleSize(
calculateInSampleSize(
imageSize,
width,
height
)
)
decoder.setTargetSampleSize(sampleSize)
decoder.isMutableRequired = true
}
} catch (e: Exception) {
Log.w("WallpaperUtil", "ImageDecoder failed, falling back to BitmapFactory: $e")
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize =
calculateInSampleSize(imageSize, width, height)
inSampleSize = sampleSize
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
@@ -155,8 +188,7 @@ fun retrieveBitmap(
} else {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize =
calculateInSampleSize(imageSize, width, height)
inSampleSize = sampleSize
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
@@ -164,21 +196,33 @@ fun retrieveBitmap(
}
}
private val SharedPaintFilterAntiAlias = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
/**
* Scale a bitmap using the fit width method
* The bitmap will fit into the given width while maintaining the same aspect ratio
*/
fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
if (source.width == width && source.height == height) {
return source
}
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
Log.w("WallpaperUtil", "Invalid dimensions for fitBitmap, returning source.")
return source
}
return try {
val aspectRatio = source.height.toFloat() / source.width.toFloat()
val newHeight = (width * aspectRatio).toInt()
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(newBitmap)
val scaledBitmap = Bitmap.createScaledBitmap(source, width, newHeight, true)
val top = (height - newHeight) / 2f
canvas.drawBitmap(scaledBitmap, 0f, top, null)
scaledBitmap.recycle()
newBitmap
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val scale = width.toFloat() / source.width
val scaledSourceHeight = source.height * scale
val yOffset = (height - scaledSourceHeight) / 2f
val matrix = Matrix().apply {
postScale(scale, scale)
postTranslate(0f, yOffset)
}
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
bitmap
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error fitting bitmap: $e")
source
@@ -186,27 +230,37 @@ fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
}
/**
* Scale a bitmap using the fit method
* Scale a bitmap using the fill method
*/
fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
if (source.width == width && source.height == height) {
return source
}
return try {
val aspectRatio = source.width.toFloat() / source.height.toFloat()
val newWidth: Int
val newHeight: Int
if (width > height * aspectRatio) {
newWidth = width
newHeight = (width / aspectRatio).toInt()
} else {
newHeight = height
newWidth = (height * aspectRatio).toInt()
}
val scaledBitmap = Bitmap.createScaledBitmap(source, newWidth, newHeight, true)
val x = ((width - newWidth) / 2f)
val y = ((height - newHeight) / 2f)
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawBitmap(scaledBitmap, x, y, null)
scaledBitmap.recycle()
val sourceAspect = source.width.toFloat() / source.height.toFloat()
val targetAspect = width.toFloat() / height.toFloat()
val scale: Float
val xOffset: Float
val yOffset: Float
if (sourceAspect >= targetAspect) {
scale = height.toFloat() / source.height.toFloat()
xOffset = (width - source.width * scale) / 2f
yOffset = 0f
} else {
scale = width.toFloat() / source.width.toFloat()
xOffset = 0f
yOffset = (height - source.height * scale) / 2f
}
val matrix = Matrix().apply {
postScale(scale, scale)
postTranslate(xOffset, yOffset)
}
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
bitmap
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error filling bitmap: $e")
@@ -218,13 +272,20 @@ fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
* Stretch the bitmap to fit the given width and height
*/
fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
if (source.width == width && source.height == height) {
return source
}
return try {
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(newBitmap)
val bitmap = Bitmap.createScaledBitmap(source, width, height, true)
canvas.drawBitmap(bitmap, 0f, 0f, null)
bitmap.recycle()
newBitmap
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val matrix = Matrix().apply {
setScale(
width.toFloat() / source.width,
height.toFloat() / source.height
)
}
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
bitmap
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error stretching bitmap: $e")
source
@@ -234,75 +295,126 @@ fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
/**
* Darken the bitmap by a certain percentage - 0 is darkest, 100 is original
*/
fun darkenBitmap(source: Bitmap, percent: Int): Bitmap {
return try {
val safePercentage = (100 - percent).coerceIn(0, 100)
val factor = 1 - safePercentage / 100f
val canvas = Canvas(source)
val paint = Paint().apply {
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
setScale(factor, factor, factor, 1f)
})
}
canvas.drawBitmap(source, 0f, 0f, paint)
source
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error darkening bitmap: $e")
source
fun darkenBitmap(source: Bitmap, brightnessToRetainPercent: Int): Bitmap {
if (!source.isMutable) {
Log.w("WallpaperUtil", "darkenBitmap received an immutable bitmap. Returning a copy.")
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
return darkenBitmap(mutableCopy, brightnessToRetainPercent)
}
val targetBrightnessFactor = brightnessToRetainPercent.coerceIn(0, 100) / 100f
if (targetBrightnessFactor >= 1.0f) {
return source
}
val paint = Paint().apply {
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
setScale(targetBrightnessFactor, targetBrightnessFactor, targetBrightnessFactor, 1f)
})
}
Canvas(source).drawBitmap(source, 0f, 0f, paint)
return source
}
/**
* Blur the bitmap by a certain percentage
*/
fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
return try {
val factor = percent.toFloat().div(100f) * 20f
Toolkit.blur(source, factor.toInt())
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error darkening bitmap: $e")
source
val clampedPercent = percent.coerceIn(0, 100)
if (clampedPercent == 0) {
return source
}
val maxBlurRadius = 25.0f
val radius = (clampedPercent / 100.0f) * maxBlurRadius
val imageReader = ImageReader.newInstance(
source.width, source.height,
PixelFormat.RGBA_8888, 1,
HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
)
val renderNode = RenderNode("BlurEffect")
val hardwareRenderer = HardwareRenderer()
var resultBitmap: Bitmap?
try {
hardwareRenderer.setSurface(imageReader.surface)
hardwareRenderer.setContentRoot(renderNode)
renderNode.setPosition(0, 0, source.width, source.height)
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.MIRROR)
renderNode.setRenderEffect(blurEffect)
val canvas = renderNode.beginRecording()
canvas.drawBitmap(source, 0f, 0f, null)
renderNode.endRecording()
hardwareRenderer.createRenderRequest()
.setWaitForPresent(true)
.syncAndDraw()
val image = imageReader.acquireNextImage()
?: throw IllegalStateException("Failed to acquire blurred image")
val hardwareBuffer = image.hardwareBuffer
?: throw IllegalStateException("Failed to acquire hardware buffer")
val hardwareBitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, null)
?: throw IllegalStateException("Failed to create bitmap from hardware buffer")
// Convert hardware bitmap to regular bitmap for further processing
resultBitmap = hardwareBitmap.copy(Bitmap.Config.ARGB_8888, false)
hardwareBuffer.close()
image.close()
} finally {
hardwareRenderer.destroy()
renderNode.discardDisplayList()
imageReader.close()
}
return resultBitmap
}
/**
* Apply a vignette effect to the bitmap
*/
fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
return try {
val image = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(image)
canvas.drawBitmap(source, 0f, 0f, Paint())
val rad: Int = if (source.width < source.height) {
val o = (source.height * 2) / 100
source.height - o * percent / 3
} else {
val o = (source.width * 2) / 100
source.width - o * percent / 3
}
val rect = Rect(0, 0, source.width, source.height)
val rectF = RectF(rect)
val colors = intArrayOf(0, 0, Color.BLACK)
val pos = floatArrayOf(0.0f, 0.1f, 1.0f)
val linGradLR: Shader = RadialGradient(
rect.centerX().toFloat(),
rect.centerY().toFloat(),
rad.toFloat(),
colors,
pos,
Shader.TileMode.CLAMP
if (percent <= 0) return source
if (!source.isMutable) {
Log.w("WallpaperUtil", "vignetteBitmap received an immutable bitmap. Returning a copy.")
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
return vignetteBitmap(mutableCopy, percent)
}
try {
val canvas = Canvas(source)
val dim = if (source.width < source.height) source.height else source.width
val rad = (dim * (1 - (percent.coerceIn(0, 100) / 150f))).coerceAtLeast(0.1f)
val centerX = source.width / 2f
val centerY = source.height / 2f
val colors = intArrayOf(
Color.TRANSPARENT,
Color.argb((0.1f * 255).toInt(), 0, 0, 0),
Color.argb((0.8f * 255).toInt(), 0, 0, 0)
)
val paint = Paint().apply {
shader = linGradLR
isAntiAlias = true
isDither = true
alpha = 128
val pos = floatArrayOf(0f, 0.7f, 1f)
val vignettePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
shader = RadialGradient(
centerX, centerY, rad,
colors, pos, Shader.TileMode.CLAMP
)
}
canvas.drawRect(rectF, paint)
image
canvas.drawRect(0f, 0f, source.width.toFloat(), source.height.toFloat(), vignettePaint)
return source
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error applying vignette effect: $e")
source
Log.e("WallpaperUtil", "Error applying vignette: $e")
return source
}
}
@@ -310,129 +422,191 @@ fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
* Apply a grey filter to the bitmap based on a percentage
*/
fun grayBitmap(bitmap: Bitmap, percent: Int): Bitmap {
val factor = percent / 100f
val colorMatrix = ColorMatrix().apply {
setSaturation(1 - factor)
if (percent <= 0) return bitmap
if (!bitmap.isMutable) {
Log.w("WallpaperUtil", "grayBitmap received an immutable bitmap. Returning a copy.")
val mutableCopy = bitmap.copy(bitmap.config ?: Bitmap.Config.ARGB_8888, true)
return grayBitmap(mutableCopy, percent)
}
val paint = Paint().apply {
colorFilter = ColorMatrixColorFilter(colorMatrix)
}
val grayBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(grayBitmap)
canvas.drawBitmap(bitmap, 0f, 0f, paint)
return grayBitmap
val factor = percent.coerceIn(0, 100) / 100f
if (factor <= 0f) return bitmap
val colorMatrix = ColorMatrix().apply { setSaturation(1 - factor) }
val paint = Paint().apply { colorFilter = ColorMatrixColorFilter(colorMatrix) }
Canvas(bitmap).drawBitmap(bitmap, 0f, 0f, paint)
return bitmap
}
/**
* Calculate the brightness of a bitmap (0-100)
* https://gist.github.com/httnn/b1d772caf76cdc0c11e2
* Get all wallpapers from a folder URI
*/
fun calculateBrightness(bitmap: Bitmap, pixelSpacing: Int = 1): Int {
var brightness = 0.0
val pixels = IntArray(bitmap.width * bitmap.height)
bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
for (i in pixels.indices step pixelSpacing.coerceAtLeast(1)) {
val color = pixels[i]
val R = Color.red(color)
val G = Color.green(color)
val B = Color.blue(color)
brightness += 0.299*R + 0.587*G + 0.114*B
}
return (brightness / (pixels.size / pixelSpacing)).toInt()
}
suspend fun getWallpaperFromFolder(folderUri: String, context: Context): List<Wallpaper> = withContext(Dispatchers.IO) {
val allowedExtensions = setOf("jpg", "jpeg", "png", "heif", "heic", "webp")
val contentResolver = context.contentResolver
val wallpapers = mutableListOf<Wallpaper>()
/**
* Retrieve wallpaper URIs from a folder directory URI
*/
fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
return try {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
listFilesRecursive(folderDocumentFile, context)
} catch (_: Exception) {
val folderDocumentFile = DocumentFile.fromTreeUri(context, folderUri.toUri())
listFilesRecursive(folderDocumentFile, context)
if (folderUri.isEmpty()) {
return@withContext emptyList<Wallpaper>()
}
}
val rootUri = folderUri.toUri()
val foldersToVisit = ArrayDeque<Uri>()
foldersToVisit.add(rootUri)
/**
* Helper function to recursively list files in a directory for DocumentFileCompat
*/
fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<String> {
val files = mutableListOf<String>()
parent?.listFiles()?.forEach { file ->
if (file.isDirectory()) {
files.addAll(listFilesRecursive(file, context))
} else {
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
if (file.extension in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
val projection = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
)
/** Overloaded version of the function for DocumentFile */
fun listFilesRecursive(parent: DocumentFile?, context: Context): List<String> {
val files = mutableListOf<String>()
parent?.listFiles()?.forEach { file ->
if (file.isDirectory) {
files.addAll(listFilesRecursive(file, context))
} else {
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
if ((file.name?.substringAfterLast(".") ?: "") in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
try {
while (foldersToVisit.isNotEmpty()) {
val currentFolderDocumentUri = foldersToVisit.removeFirst()
val currentFolderTreeDocId = DocumentsContract.getTreeDocumentId(currentFolderDocumentUri)
?: DocumentsContract.getDocumentId(currentFolderDocumentUri)
/**
* Helper function to find the first valid URI from a list of wallpapers
* It will search through all wallpapers of an album first, and then all wallpapers of every folder of an album
*/
fun findFirstValidUri(context: Context, wallpapers: List<Wallpaper>, folders: List<Folder>): String? {
wallpapers.forEach { wallpaper ->
try {
val file = DocumentFileCompat.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
if (file?.exists() == true) {
return wallpaper.wallpaperUri
if (currentFolderTreeDocId == null) {
Log.w("WallpaperUtil", "Could not get tree document ID for $currentFolderDocumentUri")
continue
}
} catch (_: Exception) {
val file = DocumentFile.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
if (file?.exists() == true) {
return wallpaper.wallpaperUri
}
}
}
folders.forEach { folder ->
folder.wallpapers.forEach { wallpaper ->
try {
val file = DocumentFileCompat.fromSingleUri(context, wallpaper.toUri())
if (file?.exists() == true) {
return wallpaper
}
} catch (_: Exception) {
val file = DocumentFile.fromSingleUri(context, wallpaper.toUri())
if (file?.exists() == true) {
return wallpaper
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
rootUri,
currentFolderTreeDocId
)
contentResolver.query(childrenUri, projection, null, null, null)?.use { cursor ->
val idIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) {
val documentId = cursor.getString(idIndex)
val displayName = cursor.getString(nameIndex)
val mimeType = cursor.getString(mimeTypeIndex)
val dateModified = cursor.getLong(lastModifiedIndex)
val documentUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, documentId)
if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) {
val dirTreeUri = DocumentsContract.buildTreeDocumentUri(rootUri.authority, documentId)
foldersToVisit.add(dirTreeUri)
} else {
val extension = displayName.substringAfterLast('.', "").lowercase()
if (extension in allowedExtensions) {
wallpapers.add(
Wallpaper(
initialAlbumName = "",
wallpaperUri = documentUri.toString().compress("content://com.android.externalstorage.documents/"),
fileName = displayName.substringBeforeLast('.', displayName),
dateModified = dateModified,
order = wallpapers.size,
key = 0
)
)
}
}
}
}
}
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error getting wallpapers from folder '$folderUri': ", e)
return@withContext emptyList<Wallpaper>()
}
return null
return@withContext wallpapers
}
/**
* Get the folder name from the folder URI
*/
fun getFolderNameFromUri(folderUri: String, context: Context): String? {
return try {
DocumentFileCompat.fromTreeUri(context, folderUri.toUri())?.name
} catch (_: Exception) {
DocumentFile.fromTreeUri(context, folderUri.toUri())?.name
suspend fun getFolderMetadata(folderUri: String, context: Context): Metadata = withContext(Dispatchers.IO) {
if (folderUri.isEmpty()) return@withContext Metadata("", 0)
return@withContext try {
val uri = folderUri.toUri()
val file = DocumentFileCompat.fromTreeUri(context, uri)
val name = file?.name?.substringBeforeLast('.', file.name) ?: ""
val lastModified = file?.lastModified ?: 0
Metadata(name, lastModified)
} catch (e: Exception) {
Log.w("WallpaperUtil", "Error getting folder metadata with DocumentFileCompat for '$folderUri': $e, trying DocumentFile")
try {
val uri = folderUri.toUri()
val file = DocumentFile.fromTreeUri(context, uri)
val name = file?.name?.substringBeforeLast('.', file.name.orEmpty()) ?: ""
val lastModified = file?.lastModified() ?: 0
Metadata(name, lastModified)
} catch (e2: Exception) {
Log.e("WallpaperUtil", "Error getting folder metadata with DocumentFile for '$folderUri': $e2")
Metadata("", 0)
}
}
}
/**
* Get filename and last modified date from an image URI
* @param context Android context
* @param uriString URI string of the image
*/
suspend fun getImageMetadata(context: Context, uriString: String): Metadata = withContext(Dispatchers.IO) {
if (uriString.isEmpty()) return@withContext Metadata("", 0)
return@withContext try {
val uri = uriString.toUri()
val file = DocumentFileCompat.fromSingleUri(context, uri)
val name = file?.name?.substringBeforeLast('.', file.name) ?: ""
val lastModified = file?.lastModified ?: 0
Metadata(name, lastModified)
} catch (e: Exception) {
Log.w("WallpaperUtil", "Error getting image metadata with DocumentFileCompat for '$uriString': $e, trying DocumentFile")
try {
val uri = uriString.toUri()
val file = DocumentFile.fromSingleUri(context, uri)
val name = file?.name?.substringBeforeLast('.', file.name.orEmpty()) ?: ""
val lastModified = file?.lastModified() ?: 0
Metadata(name, lastModified)
} catch (e2: Exception) {
Log.e("WallpaperUtil", "Error getting image metadata with DocumentFile for '$uriString': $e2")
Metadata("", 0)
}
}
}
/**
* Helper function to find the first valid URI from a list of wallpapers and folders
*/
suspend fun findFirstValidUri(
context: Context,
folders: List<Folder>,
wallpapers: List<Wallpaper>
): String? = withContext(Dispatchers.IO) {
try {
for (folder in folders) {
for (wallpaper in folder.wallpapers) {
try {
if (isValidUri(context, wallpaper.wallpaperUri)) {
return@withContext wallpaper.wallpaperUri
}
} catch (e: Exception) {
Log.w("WallpaperUtil", "Error checking URI validity for folder wallpaper: ${wallpaper.wallpaperUri}", e)
}
}
}
for (wallpaper in wallpapers) {
try {
if (isValidUri(context, wallpaper.wallpaperUri)) {
return@withContext wallpaper.wallpaperUri
}
} catch (e: Exception) {
Log.w("WallpaperUtil", "Error checking URI validity for standalone wallpaper: ${wallpaper.wallpaperUri}", e)
}
}
return@withContext null
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error finding valid URI", e)
return@withContext null
}
}
@@ -440,14 +614,59 @@ fun getFolderNameFromUri(folderUri: String, context: Context): String? {
* Check if a URI is valid
*/
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
if (uriString.isNullOrEmpty()) return false
val decompressedUriString = try {
uriString.decompress("content://com.android.externalstorage.documents/")
} catch (e: Exception) {
Log.w("WallpaperUtil", "Failed to decompress URI string: $uriString", e)
uriString
}
val uri = decompressedUriString.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
DocumentFileCompat.fromSingleUri(context, uri)?.exists() == true
} catch (e: Exception) {
Log.w("WallpaperUtil", "Error checking URI validity with DocumentFileCompat for '$uri': $e, trying DocumentFile")
try {
DocumentFile.fromSingleUri(context, uri)?.exists() == true
} catch (e2: Exception) {
Log.w("WallpaperUtil", "Error checking URI validity with DocumentFile for '$uri': $e2")
false
}
true
} catch (_: Exception) { false }
}
}
/**
* Check if a URI is a directory
*/
fun isDirectory(context: Context, uriString: String?): Boolean {
if (uriString.isNullOrEmpty()) return false
val uri = uriString.toUri()
return try {
DocumentFile.fromSingleUri(context, uri)?.isDirectory == true
} catch (e: Exception) {
Log.w("WallpaperUtil", "Error checking if URI is a directory for '$uri': $e")
try {
DocumentFile.fromTreeUri(context, uri)?.isDirectory == true
} catch (e2: Exception) {
Log.w("WallpaperUtil", "Error checking tree URI directory status for '$uri': $e2")
false
}
}
}
/**
* Compress a string
*/
fun String.compress(prefixToRemove: String, charset: Charset = Charsets.UTF_8): String {
return this
}
/**
* Decompress a string
*/
fun String.decompress(prefixToAdd: String, charset: Charset = Charsets.UTF_8): String {
return this
}
/**
@@ -471,7 +690,12 @@ fun processBitmap(
try {
var processedBitmap = source
// Apply wallpaper scaling effects
// Apply blur first on the original size for better quality
if (blur && blurPercent > 0) {
processedBitmap = blurBitmap(processedBitmap, blurPercent)
}
// Then scale the bitmap
processedBitmap = when (scaling) {
ScalingConstants.FILL -> fillBitmap(processedBitmap, width, height)
ScalingConstants.FIT -> fitBitmap(processedBitmap, width, height)
@@ -479,29 +703,50 @@ fun processBitmap(
ScalingConstants.NONE -> processedBitmap
}
// Apply brightness effect
if (darken && darkenPercent < 100) {
// Ensure mutability for color effects
if (!processedBitmap.isMutable && (darken || vignette || grayscale)) {
Log.w("ProcessBitmap", "Bitmap became immutable. Making a mutable copy.")
processedBitmap = processedBitmap.copy(processedBitmap.config ?: Bitmap.Config.ARGB_8888, true)
}
if (darken && darkenPercent > 0) {
processedBitmap = darkenBitmap(processedBitmap, darkenPercent)
}
// Apply blur effect
if (blur && blurPercent > 0) {
processedBitmap = blurBitmap(processedBitmap, blurPercent)
}
// Apply vignette effect
if (vignette && vignettePercent > 0) {
processedBitmap = vignetteBitmap(processedBitmap, vignettePercent)
}
// Apply gray effect
if (grayscale && grayscalePercent > 0) {
processedBitmap = grayBitmap(processedBitmap, grayscalePercent)
}
return processedBitmap
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error darkening bitmap", e)
}
catch (e: OutOfMemoryError) {
Log.e("PaperizeWallpaperChanger", "Error: Ran out of memory during bitmap processing. Attempting with smaller dimensions.", e)
if (width / 2 > 0 && height / 2 > 0) {
return processBitmap(
width / 2,
height / 2,
source,
darken,
darkenPercent,
scaling,
blur,
blurPercent,
vignette,
vignettePercent,
grayscale,
grayscalePercent
)
} else {
Log.e("PaperizeWallpaperChanger", "Cannot reduce dimensions further for OOM recovery.")
return null
}
}
catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error processing bitmap", e)
return null
}
}
@@ -1,5 +1,7 @@
package com.anthonyla.paperize.data.settings
import kotlinx.coroutines.flow.Flow
/**
* Interface for the data store that handles the settings for application
*/
@@ -10,8 +12,12 @@ interface SettingsDataStore {
suspend fun getBoolean(key: String): Boolean?
suspend fun getString(key: String): String?
suspend fun getInt(key: String): Int?
fun getBooleanFlow(key: String): Flow<Boolean?>
fun getStringFlow(key: String): Flow<String?>
fun getIntFlow(key: String): Flow<Int?>
suspend fun deleteBoolean(key: String)
suspend fun deleteString(key: String)
suspend fun deleteInt(key: String)
suspend fun clear(keys: List<String>)
suspend fun clearPreferences()
}
@@ -5,11 +5,15 @@ import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.anthonyla.paperize.core.SettingsConstants.SETTINGS_DATASTORE
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import javax.inject.Inject
import kotlinx.coroutines.flow.map
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = SETTINGS_DATASTORE)
@@ -29,9 +33,9 @@ class SettingsDataStoreImpl(private val context: Context) : SettingsDataStore {
}
override suspend fun putInt(key: String, value: Int) {
val preferencesKey = stringPreferencesKey(key)
val preferencesKey = intPreferencesKey(key)
context.dataStore.edit {
it[preferencesKey] = value.toString()
it[preferencesKey] = value
}
}
@@ -54,15 +58,56 @@ class SettingsDataStoreImpl(private val context: Context) : SettingsDataStore {
override suspend fun getInt(key: String): Int? {
return try {
val head = context.dataStore.data.first()
val preferencesKey = stringPreferencesKey(key)
head[preferencesKey]?.toInt()
val preferences = context.dataStore.data.first()
val intKey = intPreferencesKey(key)
val stringKey = stringPreferencesKey(key)
preferences[intKey] ?: preferences[stringKey]?.toIntOrNull()
} catch (exception: Exception) {
exception.printStackTrace()
null
}
}
override fun getBooleanFlow(key: String): Flow<Boolean?> = context.dataStore.data
.catch { exception ->
exception.printStackTrace()
emit(emptyPreferences())
}
.map { preferences ->
preferences[booleanPreferencesKey(key)]
}
override fun getStringFlow(key: String): Flow<String?> = context.dataStore.data
.catch { exception ->
exception.printStackTrace()
emit(emptyPreferences())
}
.map { preferences ->
preferences[stringPreferencesKey(key)]
}
override fun getIntFlow(key: String): Flow<Int?> {
val intKey = intPreferencesKey(key)
val stringKey = stringPreferencesKey(key)
return context.dataStore.data
.catch { exception ->
exception.printStackTrace()
emit(emptyPreferences())
}
.map { preferences ->
val valueAsInt = preferences[intKey]
if (valueAsInt != null) {
valueAsInt
} else {
val valueAsString = preferences[stringKey]
valueAsString?.toIntOrNull()
}
}
}
override suspend fun deleteBoolean(key: String) {
val preferencesKey = booleanPreferencesKey(key)
context.dataStore.edit {
@@ -82,7 +127,7 @@ class SettingsDataStoreImpl(private val context: Context) : SettingsDataStore {
}
override suspend fun deleteInt(key: String) {
val preferencesKey = stringPreferencesKey(key)
val preferencesKey = intPreferencesKey(key)
context.dataStore.edit {
if (it.contains(preferencesKey)) {
it.remove(preferencesKey)
@@ -95,4 +140,20 @@ class SettingsDataStoreImpl(private val context: Context) : SettingsDataStore {
it.clear()
}
}
override suspend fun clear(keys: List<String>) {
context.dataStore.edit { preferences ->
keys.forEach { key ->
if (preferences.contains(booleanPreferencesKey(key))) {
preferences.remove(booleanPreferencesKey(key))
}
else if (preferences.contains(stringPreferencesKey(key))) {
preferences.remove(stringPreferencesKey(key))
}
else if (preferences.contains(intPreferencesKey(key))) {
preferences.remove(intPreferencesKey(key))
}
}
}
}
}
@@ -6,11 +6,8 @@ import androidx.room.Room
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.data.settings.SettingsDataStoreImpl
import com.anthonyla.paperize.feature.wallpaper.data.data_source.AlbumDatabase
import com.anthonyla.paperize.feature.wallpaper.data.data_source.SelectedAlbumDatabase
import com.anthonyla.paperize.feature.wallpaper.data.repository.AlbumRepositoryImpl
import com.anthonyla.paperize.feature.wallpaper.data.repository.SelectedAlbumRepositoryImpl
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -28,20 +25,10 @@ object AppModule {
@Singleton
fun provideAlbumDatabase(app: Application): AlbumDatabase {
return Room.databaseBuilder(
app,
AlbumDatabase::class.java,
AlbumDatabase.DATABASE_NAME
).fallbackToDestructiveMigration().addMigrations().build()
}
@Provides
@Singleton
fun provideSelectedAlbumDatabase(app: Application): SelectedAlbumDatabase {
return Room.databaseBuilder(
app,
SelectedAlbumDatabase::class.java,
SelectedAlbumDatabase.DATABASE_NAME
).fallbackToDestructiveMigration().addMigrations().build()
app,
AlbumDatabase::class.java,
AlbumDatabase.DATABASE_NAME
).fallbackToDestructiveMigration(true).build()
}
@Provides
@@ -56,18 +43,6 @@ object AppModule {
return AlbumRepositoryImpl(db.albumDao)
}
@Provides
@Singleton
fun provideSelectedAlbumDao(db: SelectedAlbumDatabase) = db.selectedAlbumDao
@Provides
@Singleton
fun provideSelectedAlbumRepository(
db: SelectedAlbumDatabase
): SelectedAlbumRepository {
return SelectedAlbumRepositoryImpl(db.selectedAlbumDao)
}
@Provides
@Singleton
fun provideSettingsDataStore (
@@ -6,9 +6,16 @@ import android.os.Bundle
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver
class BroadcastActivity : Activity() {
companion object {
const val ACTION_CUSTOM_BROADCAST = "com.anthonyla.paperize.SHORTCUT"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = Intent("WallpaperBootAndChangeReceiver.intent.action.BROADCAST").setClass(this, WallpaperBootAndChangeReceiver::class.java)
val intent = Intent(ACTION_CUSTOM_BROADCAST).apply {
setClass(this@BroadcastActivity, WallpaperBootAndChangeReceiver::class.java)
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
}
sendBroadcast(intent)
finish()
}
@@ -18,11 +18,20 @@ import kotlinx.coroutines.flow.Flow
*/
@Dao
interface AlbumDao {
@Transaction
@Query("SELECT * FROM album")
fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>>
@Transaction
@Query("SELECT * FROM album WHERE selected = 1")
fun getSelectedAlbums(): Flow<List<AlbumWithWallpaperAndFolder>>
@Query("UPDATE album SET selected = :selected WHERE initialAlbumName = :albumName")
suspend fun updateAlbumSelection(albumName: String, selected: Boolean)
@Query("UPDATE album SET selected = 0")
suspend fun deselectAllAlbums()
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAlbum(album: Album)
@@ -13,7 +13,7 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
*/
@Database(
entities = [Album::class, Wallpaper::class, Folder::class],
version = 5
version = 12
)
@TypeConverters(Converters::class)
abstract class AlbumDatabase: RoomDatabase() {
@@ -1,7 +1,9 @@
package com.anthonyla.paperize.feature.wallpaper.data.data_source
import androidx.room.TypeConverter
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* Converters for Room database to convert list of strings to json string and vice versa
@@ -19,5 +21,18 @@ class Converters {
* Convert json string to list of strings
*/
@TypeConverter
fun jsonStringToList(value: String) = gson.fromJson(value, Array<String>::class.java).toList()
fun jsonStringToList(value: String?): List<String> {
if (value == null) return emptyList()
return gson.fromJson(value, Array<String>::class.java).toList()
}
@TypeConverter
fun fromWallpaperList(value: List<Wallpaper>): String? = gson.toJson(value)
@TypeConverter
fun toWallpaperList(value: String?): List<Wallpaper> {
if (value == null) return emptyList()
val listType = object : TypeToken<List<Wallpaper>>() {}.type
return gson.fromJson(value, listType)
}
}
@@ -1,59 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.data.data_source
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import kotlinx.coroutines.flow.Flow
/**
* Data Access Object for selected album for application to keep track of which album is currently selected for changing wallpapers from
*/
@Dao
interface SelectedAlbumDao {
@Transaction
@Query("SELECT * FROM album")
fun getSelectedAlbum(): Flow<List<SelectedAlbum>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAlbum(album: Album)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertWallpaper(wallpaper: Wallpaper)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>)
@Query("DELETE FROM album WHERE initialAlbumName = :initialAlbumName")
suspend fun deleteAlbum(initialAlbumName: String)
@Delete
suspend fun deleteWallpaper(wallpaper: Wallpaper)
@Query("DELETE FROM wallpaper WHERE initialAlbumName = :initialAlbumName")
suspend fun cascadeDeleteWallpaper(initialAlbumName: String)
@Query("DELETE FROM album")
suspend fun deleteAllAlbums()
@Query("DELETE FROM wallpaper")
suspend fun deleteAllWallpapers()
@Transaction
suspend fun deleteAll() {
deleteAllAlbums()
deleteAllWallpapers()
}
@Transaction
suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum) {
upsertAlbum(selectedAlbum.album)
upsertWallpaperList(selectedAlbum.wallpapers)
}
}
@@ -1,23 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.data.data_source
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
/**
* Database for selected album
* Stores [Album] and [Wallpaper] inside SelectedAlbum
*/
@Database(
entities = [Album::class, Wallpaper::class],
version = 5
)
@TypeConverters(Converters::class)
abstract class SelectedAlbumDatabase: RoomDatabase() {
abstract val selectedAlbumDao: SelectedAlbumDao
companion object {
const val DATABASE_NAME = "paperize_selectedAlbum_db"
}
}
@@ -6,88 +6,159 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperA
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
class AlbumRepositoryImpl(
private val dao: AlbumDao
private val dao: AlbumDao,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
): AlbumRepository {
override fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>> {
return dao.getAlbumsWithWallpaperAndFolder()
return dao.getAlbumsWithWallpaperAndFolder().map { albumWithWallpaperAndFolderList ->
albumWithWallpaperAndFolderList.map {
it.copy(
wallpapers = it.sortedWallpapers,
folders = it.sortedFolders,
)
}
}
}
override fun getSelectedAlbums(): Flow<List<AlbumWithWallpaperAndFolder>> {
return dao.getSelectedAlbums().map { albumWithWallpaperAndFolderList ->
albumWithWallpaperAndFolderList.map {
it.copy(
wallpapers = it.sortedWallpapers,
folders = it.sortedFolders,
)
}
}
}
override suspend fun upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder) {
dao.upsertAlbum(albumWithWallpaperAndFolder.album)
dao.upsertWallpaperList(albumWithWallpaperAndFolder.wallpapers)
dao.upsertFolderList(albumWithWallpaperAndFolder.folders)
withContext(dispatcher) {
dao.upsertAlbum(albumWithWallpaperAndFolder.album)
dao.upsertWallpaperList(albumWithWallpaperAndFolder.wallpapers)
dao.upsertFolderList(albumWithWallpaperAndFolder.folders)
}
}
override suspend fun updateAlbumSelection(albumName: String, selected: Boolean) {
withContext(dispatcher) {
dao.updateAlbumSelection(albumName, selected)
}
}
override suspend fun deselectAllAlbums() {
withContext(dispatcher) {
dao.deselectAllAlbums()
}
}
override suspend fun upsertAlbum(album: Album) {
dao.upsertAlbum(album)
withContext(dispatcher) {
dao.upsertAlbum(album)
}
}
override suspend fun upsertWallpaper(wallpaper: Wallpaper) {
dao.upsertWallpaper(wallpaper)
withContext(dispatcher) {
dao.upsertWallpaper(wallpaper)
}
}
override suspend fun upsertFolder(folder: Folder) {
dao.upsertFolder(folder)
withContext(dispatcher) {
dao.upsertFolder(folder)
}
}
override suspend fun upsertFolderList(folders: List<Folder>) {
dao.upsertFolderList(folders)
withContext(dispatcher) {
dao.upsertFolderList(folders)
}
}
override suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>) {
dao.upsertWallpaperList(wallpapers)
withContext(dispatcher) {
dao.upsertWallpaperList(wallpapers)
}
}
override suspend fun deleteAlbum(album: Album) {
dao.deleteAlbum(album)
withContext(dispatcher) {
dao.deleteAlbum(album)
}
}
override suspend fun deleteWallpaper(wallpaper: Wallpaper) {
dao.deleteWallpaper(wallpaper)
withContext(dispatcher) {
dao.deleteWallpaper(wallpaper)
}
}
override suspend fun deleteFolder(folder: Folder) {
dao.deleteFolder(folder)
withContext(dispatcher) {
dao.deleteFolder(folder)
}
}
override suspend fun updateAlbum(album: Album) {
dao.updateAlbum(album)
withContext(dispatcher) {
dao.updateAlbum(album)
}
}
override suspend fun updateFolder(folder: Folder) {
dao.updateFolder(folder)
withContext(dispatcher) {
dao.updateFolder(folder)
}
}
override suspend fun updateWallpaper(wallpaper: Wallpaper) {
dao.updateWallpaper(wallpaper)
withContext(dispatcher) {
dao.updateWallpaper(wallpaper)
}
}
override suspend fun cascadeDeleteAlbum(album: Album) {
dao.deleteAlbum(album)
dao.cascadeDeleteWallpaper(album.initialAlbumName)
dao.cascadeDeleteFolder(album.initialAlbumName)
withContext(dispatcher) {
dao.deleteAlbum(album)
dao.cascadeDeleteWallpaper(album.initialAlbumName)
dao.cascadeDeleteFolder(album.initialAlbumName)
}
}
override suspend fun cascadeDeleteFolder(initialAlbumName: String) {
dao.cascadeDeleteFolder(initialAlbumName)
withContext(dispatcher) {
dao.cascadeDeleteFolder(initialAlbumName)
}
}
override suspend fun cascadeDeleteWallpaper(initialAlbumName: String) {
dao.cascadeDeleteWallpaper(initialAlbumName)
withContext(dispatcher) {
dao.cascadeDeleteWallpaper(initialAlbumName)
}
}
override suspend fun deleteFolderList(folders: List<Folder>) {
dao.deleteFolderList(folders)
withContext(dispatcher) {
dao.deleteFolderList(folders)
}
}
override suspend fun deleteWallpaperList(wallpapers: List<Wallpaper>) {
dao.deleteWallpaperList(wallpapers)
withContext(dispatcher) {
dao.deleteWallpaperList(wallpapers)
}
}
override suspend fun deleteAllData() {
dao.deleteAllData()
withContext(dispatcher) {
dao.deleteAllData()
}
}
}
@@ -1,36 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.data.repository
import com.anthonyla.paperize.feature.wallpaper.data.data_source.SelectedAlbumDao
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import kotlinx.coroutines.flow.Flow
class SelectedAlbumRepositoryImpl(
private val dao: SelectedAlbumDao
): SelectedAlbumRepository {
override fun getSelectedAlbum(): Flow<List<SelectedAlbum>> {
return dao.getSelectedAlbum()
}
override suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum) {
dao.upsertSelectedAlbum(selectedAlbum)
}
override suspend fun deleteAlbum(initialAlbumName: String) {
dao.deleteAlbum(initialAlbumName)
}
override suspend fun deleteWallpaper(wallpaper: Wallpaper) {
dao.deleteWallpaper(wallpaper)
}
override suspend fun cascadeDeleteAlbum(initialAlbumName: String) {
dao.deleteAlbum(initialAlbumName)
dao.cascadeDeleteWallpaper(initialAlbumName)
}
override suspend fun deleteAll() {
dao.deleteAll()
}
}
@@ -9,16 +9,16 @@ import androidx.room.PrimaryKey
* @param initialAlbumName The initial album name -- should not be changed as it is used as the key for database queries
* @param displayedAlbumName The displayed album name
* @param coverUri The cover uri of the album
* @param initialized Whether the album has been initialized
* @param homeWallpapersInQueue The list of home wallpapers in the queue
* @param lockWallpapersInQueue The list of lock wallpapers in the queue
* @param selected Whether the album is selected
*/
@Entity
data class Album(
@PrimaryKey(autoGenerate = false) val initialAlbumName: String,
val displayedAlbumName: String,
val coverUri: String?,
val initialized: Boolean = false,
val homeWallpapersInQueue: List<String> = emptyList(),
val lockWallpapersInQueue: List<String> = emptyList(),
val selected : Boolean = false
)
@@ -8,17 +8,30 @@ import androidx.room.Relation
* @param album The album.
* @param wallpapers The wallpapers.
* @param folders The folders.
*/
* */
data class AlbumWithWallpaperAndFolder(
@Embedded val album: Album,
@Relation(
parentColumn = "initialAlbumName",
entityColumn = "initialAlbumName",
entity = Wallpaper::class,
)
val wallpapers: List<Wallpaper> = emptyList(),
@Relation(
parentColumn = "initialAlbumName",
entityColumn = "initialAlbumName",
entity = Folder::class
)
val folders: List<Folder> = emptyList(),
)
) {
val totalWallpapers: List<Wallpaper>
get() = folders.flatMap { it.wallpapers } + wallpapers
val sortedFolders: List<Folder>
get() = folders.map { folder ->
folder.copy(wallpapers = folder.wallpapers.sortedBy { it.order })
}.sortedBy { it.order }
val sortedWallpapers: List<Wallpaper>
get() = wallpapers.sortedBy { it.order }
val sortedTotalWallpapers: List<Wallpaper>
get() = (folders.flatMap { it.wallpapers } + wallpapers).sortedBy { it.order }
}
@@ -4,20 +4,24 @@ import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Represents a folder directory containing wallpapers.
* Represents a folder directory containing wallpapers
*
* @param initialAlbumName The initial album name.
* @param folderName The folder name.
* @param coverUri The cover URI.
* @param wallpapers The list of wallpaper URI strings in the folder.
* @param folderUri The folder directory URI.
* @param initialAlbumName The initial album name
* @param folderName The folder name
* @param folderUri The folder directory URI
* @param coverUri The cover URI
* @param dateModified The date modified of the folder
* @param wallpapers The list of wallpaper URI strings in the folder
* @param order The order of the folder
*/
@Entity
data class Folder(
val initialAlbumName: String,
val folderName: String?,
val coverUri: String?,
val wallpapers: List<String> = emptyList(),
val folderUri: String,
val coverUri: String?,
val dateModified: Long,
val wallpapers: List<Wallpaper> = emptyList(),
val order: Int,
@PrimaryKey(autoGenerate = false) val key: Int
)
@@ -0,0 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.domain.model
data class Metadata(
val filename: String,
val lastModified: Long
)
@@ -1,18 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.domain.model
import androidx.room.Embedded
import androidx.room.Relation
/**
* Data class that represents a selected album with its wallpapers.
* @param album the selected album.
* @param wallpapers the wallpapers of the selected album. Includes the wallpapers from each folders in album.
*/
data class SelectedAlbum(
@Embedded val album: Album,
@Relation(
parentColumn = "initialAlbumName",
entityColumn = "initialAlbumName",
)
val wallpapers: List<Wallpaper> = emptyList(),
)
@@ -4,14 +4,19 @@ import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Represents a wallpaper object.
* Represents a wallpaper object
*
* @param initialAlbumName The name of the album the wallpaper belongs to.
* @param wallpaperUri The URI of the wallpaper.
* @param initialAlbumName The name of the album the wallpaper belongs to
* @param wallpaperUri The URI of the wallpaper
* @param fileName The name of the file
* @param dateModified The date the wallpaper was last modified
*/
@Entity
data class Wallpaper(
val initialAlbumName: String,
val wallpaperUri: String,
val fileName: String,
val dateModified: Long,
val order: Int,
@PrimaryKey(autoGenerate = false) val key: Int
)
@@ -12,6 +12,21 @@ interface AlbumRepository {
*/
fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>>
/**
* Get all selected albums with wallpaper and folder
*/
fun getSelectedAlbums(): Flow<List<AlbumWithWallpaperAndFolder>>
/**
* Update album selection
*/
suspend fun updateAlbumSelection(albumName: String, selected: Boolean)
/**
* Deselect all albums
*/
suspend fun deselectAllAlbums()
/**
* Insert or update album with wallpaper and folder
*/
@@ -1,37 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.domain.repository
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import kotlinx.coroutines.flow.Flow
interface SelectedAlbumRepository {
/**
* Get selected album from database
*/
fun getSelectedAlbum(): Flow<List<SelectedAlbum>>
/**
* Upsert or insert selectedAlbum to database with its wallpapers
*/
suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum)
/**
* Delete album from database
*/
suspend fun deleteAlbum(initialAlbumName: String)
/**
* Delete wallpaper from database
*/
suspend fun deleteWallpaper(wallpaper: Wallpaper)
/**
* Cascade delete album and its wallpaper and folder. Proper way to delete an AlbumWithWallpaperAndFolder
*/
suspend fun cascadeDeleteAlbum(initialAlbumName: String)
/**
* Delete all data from database
*/
suspend fun deleteAll()
}
@@ -0,0 +1,54 @@
package com.anthonyla.paperize.feature.wallpaper.glance_widget
import android.content.Context
import android.content.Intent
import androidx.compose.runtime.Composable
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.Image
import androidx.glance.ImageProvider
import androidx.glance.action.clickable
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.provideContent
import androidx.glance.layout.Box
import androidx.glance.layout.ContentScale
import androidx.glance.layout.fillMaxSize
import com.anthonyla.paperize.R
import androidx.glance.ColorFilter
import androidx.glance.GlanceTheme
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver
class PaperizeWidget : GlanceAppWidget() {
override suspend fun provideGlance(context: Context, id: GlanceId) {
provideContent {
WidgetContent(context)
}
}
}
@Composable
private fun WidgetContent(context: Context) {
val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.SHORTCUT"
Box(
modifier = GlanceModifier
.fillMaxSize()
.clickable(
{
val intent = Intent(ACTION_CHANGE_WALLPAPER).apply {
setClass(context, WallpaperBootAndChangeReceiver::class.java)
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
}
context.sendBroadcast(intent)
}
)
) {
Image(
provider = ImageProvider(R.drawable.next_wallpaper_icon),
contentDescription = "Paperize Widget",
modifier = GlanceModifier.fillMaxSize(),
contentScale = ContentScale.Fit,
colorFilter = ColorFilter.tint(GlanceTheme.colors.primaryContainer)
)
}
}
@@ -0,0 +1,7 @@
package com.anthonyla.paperize.feature.wallpaper.glance_widget
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
class PaperizeWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = PaperizeWidget()
}
@@ -2,9 +2,10 @@ package com.anthonyla.paperize.feature.wallpaper.presentation
import android.Manifest
import android.animation.ObjectAnimator
import android.app.Activity
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
@@ -17,54 +18,82 @@ import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.annotation.RequiresPermission
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
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.Modifier
import androidx.compose.ui.unit.dp
import androidx.core.animation.doOnEnd
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.themes.PaperizeTheme
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperScreenViewModel
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmItem
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmSchedulerImpl
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val albumsViewModel: AlbumsViewModel by viewModels()
private val settingsViewModel: SettingsViewModel by viewModels()
private val wallpaperScreenViewModel: WallpaperScreenViewModel by viewModels()
private val context = this
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (ContextCompat.checkSelfPermission(context, Manifest.permission.SET_WALLPAPER) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context as Activity, arrayOf(Manifest.permission.SET_WALLPAPER), 0)
private val settingsViewModel: SettingsViewModel by viewModels()
// Launcher for SET_WALLPAPER permission
private val requestSetWallpaperPermission = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (!isGranted) {
// Handle the case where the user denies the permission.
// For wallpaper apps, this permission is critical, so denying it
// means the app won't function as intended.
// Consider showing a dialog explaining why it's needed and
// offering to open app settings.
}
}
// Launcher for SCHEDULE_EXACT_ALARM permission (Android 12+)
private val requestExactAlarmPermission = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
// No specific action needed on result here, as we just want the permission granted.
// The check `am.canScheduleExactAlarms()` will reflect the new state when needed.
}
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT),
navigationBarStyle = SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT)
)
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
// Request SET_WALLPAPER permission immediately if not granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SET_WALLPAPER) != PackageManager.PERMISSION_GRANTED) {
requestSetWallpaperPermission.launch(Manifest.permission.SET_WALLPAPER)
}
// Trigger a refresh of wallpapers when the app is opened.
val refreshIntent = Intent(this, HomeWallpaperService::class.java).apply {
action = HomeWallpaperService.Actions.REFRESH.toString()
}
startForegroundService(refreshIntent)
val splashScreen = installSplashScreen()
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
@@ -79,123 +108,138 @@ class MainActivity : ComponentActivity() {
splashScreen.setKeepOnScreenCondition { settingsViewModel.setKeepOnScreenCondition }
setContent {
val scheduler = WallpaperAlarmSchedulerImpl(context)
// Request SCHEDULE_EXACT_ALARM permission when the Composable is active.
// This will prompt the user to grant the permission if not already granted.
LaunchedEffect(Unit) {
requestExactAlarmPermissionIfNeeded(this@MainActivity)
}
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle()
val isFirstLaunch = runBlocking { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) } ?: true
if (isFirstLaunch) {
scheduler.cancelWallpaperAlarm()
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset())
settingsViewModel.onEvent(SettingsEvent.Reset)
albumsViewModel.onEvent(AlbumsEvent.Reset)
val contentResolver = context.contentResolver
val persistedUris = contentResolver.persistedUriPermissions
for (permission in persistedUris) {
contentResolver.releasePersistableUriPermission(permission.uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
}
LifecycleEventEffect(Lifecycle.Event.ON_CREATE) {
lifecycleScope.launch {
if (settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) == true) {
val homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME)
val lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME)
if (homeAlbumName.isNullOrEmpty() || lockAlbumName.isNullOrEmpty()) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
}
else {
val shouldScheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val shouldScheduleAlarm = if (shouldScheduleSeparately) {
!(isPendingIntentSet(Type.HOME.ordinal) && isPendingIntentSet(Type.LOCK.ordinal))
} else {
!isPendingIntentSet(Type.SINGLE.ordinal)
}
if (shouldScheduleAlarm) {
scheduler.scheduleWallpaperAlarm(
WallpaperAlarmItem(
homeInterval = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
lockInterval = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false,
setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false,
scheduleSeparately = shouldScheduleSeparately,
changeStartTime = settingsDataStoreImpl.getBoolean(SettingsConstants.CHANGE_START_TIME) ?: false,
startTime = Pair(
settingsDataStoreImpl.getInt(SettingsConstants.START_HOUR) ?: 0,
settingsDataStoreImpl.getInt(SettingsConstants.START_MINUTE) ?: 0
),
),
origin = null,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true
)
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
val selectedState = wallpaperScreenViewModel.state.value
val currentHomeAlbum = selectedState.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.homeAlbumName }
val currentLockAlbum = selectedState.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.lockAlbumName }
when {
settingsState.value.scheduleSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
!settingsState.value.scheduleSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
settingsState.value.setHomeWallpaper -> {
if (currentHomeAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = if (settingsState.value.scheduleSeparately) null else currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
settingsState.value.setLockWallpaper -> {
if (currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = if (settingsState.value.scheduleSeparately) null else currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
}
}
}
}
val scheduler = WallpaperAlarmSchedulerImpl(this, settingsDataStoreImpl)
var hasScheduleRun by remember { mutableStateOf(false) }
LaunchedEffect(settingsState.value) {
// Only attempt to schedule once settings are initialized and the scheduling logic hasn't run yet.
if (!hasScheduleRun && settingsState.value.initialized) {
handleWallpaperScheduling(settingsState.value, scheduler)
hasScheduleRun = true
}
}
PaperizeTheme(settingsState.value.darkMode, settingsState.value.amoledTheme, settingsState.value.dynamicTheming) {
Surface(tonalElevation = 5.dp) {
PaperizeTheme(
darkMode = settingsState.value.themeSettings.darkMode,
amoledMode = settingsState.value.themeSettings.amoledTheme,
dynamicTheming = settingsState.value.themeSettings.dynamicTheming
) {
Surface(
modifier = Modifier.fillMaxSize(),
tonalElevation = 5.dp
) {
PaperizeApp(isFirstLaunch, scheduler)
}
}
}
}
override fun onResume() {
super.onResume()
/**
* Requests the SCHEDULE_EXACT_ALARM permission if needed on Android 12 (S) and above.
* This function should be called from a LaunchedEffect or similar lifecycle-aware scope
* within Compose, or directly in onCreate if you prefer.
*/
private fun requestExactAlarmPermissionIfNeeded(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val alarmManager = ContextCompat.getSystemService(context, AlarmManager::class.java)
if (alarmManager?.canScheduleExactAlarms() == false) {
Intent().also { intent ->
intent.action = Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM
context.startActivity(intent)
val am = context.getSystemService(ALARM_SERVICE) as AlarmManager
if (!am.canScheduleExactAlarms()) {
val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).apply {
data = "package:${context.packageName}".toUri()
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
requestExactAlarmPermission.launch(intent)
}
}
}
@SuppressLint("MissingPermission")
private suspend fun handleWallpaperScheduling(
settings: SettingsState,
scheduler: WallpaperAlarmSchedulerImpl
) {
val wallpaperSettings = settings.wallpaperSettings
val scheduleSettings = settings.scheduleSettings
// If changer is not enabled, or essential album names are missing, disable changer and return.
if (!wallpaperSettings.enableChanger || wallpaperSettings.homeAlbumName.isNullOrEmpty() || wallpaperSettings.lockAlbumName.isNullOrEmpty()) {
if (wallpaperSettings.enableChanger) { // Only dispatch event if it was enabled
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
}
return
}
// Check if alarms are already set to avoid redundant scheduling
val shouldScheduleAlarm = if (scheduleSettings.scheduleSeparately) {
!(isPendingIntentSet(Type.HOME.ordinal) && isPendingIntentSet(Type.LOCK.ordinal))
} else {
!isPendingIntentSet(Type.SINGLE.ordinal)
}
if (shouldScheduleAlarm) {
val canScheduleExactAlarms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
alarmManager.canScheduleExactAlarms()
} else {
true
}
if (canScheduleExactAlarms) {
scheduleWallpaperAlarm(settings, scheduler)
} else {
// Optionally prompt user to grant permission
requestExactAlarmPermissionIfNeeded(this)
}
}
}
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
private suspend fun scheduleWallpaperAlarm(
settings: SettingsState,
scheduler: WallpaperAlarmSchedulerImpl
) {
val scheduleSettings = settings.scheduleSettings
val wallpaperSettings = settings.wallpaperSettings
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val am = getSystemService(ALARM_SERVICE) as AlarmManager
if (!am.canScheduleExactAlarms()) {
return
}
}
scheduler.scheduleWallpaperAlarm(
WallpaperAlarmItem(
homeInterval = scheduleSettings.homeInterval,
lockInterval = scheduleSettings.lockInterval,
setLock = wallpaperSettings.setLockWallpaper,
setHome = wallpaperSettings.setHomeWallpaper,
scheduleSeparately = scheduleSettings.scheduleSeparately,
changeStartTime = scheduleSettings.changeStartTime,
startTime = scheduleSettings.startTime,
),
origin = null,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true,
homeNextTime = settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME),
lockNextTime = settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME)
)
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
}
private fun isPendingIntentSet(requestCode: Int): Boolean {
val intent = Intent(context.applicationContext, WallpaperReceiver::class.java)
val intent = Intent(applicationContext, WallpaperReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context.applicationContext,
applicationContext,
requestCode,
intent,
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_NO_CREATE
File diff suppressed because it is too large. Load diff
@@ -1,17 +1,16 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
sealed class AddAlbumEvent {
data object SaveAlbum: AddAlbumEvent()
data object Reset: AddAlbumEvent()
data object DeleteSelected: AddAlbumEvent()
data object SelectAll: AddAlbumEvent()
data object DeselectAll: AddAlbumEvent()
data class SetAlbumName(
data class SaveAlbum(
val initialAlbumName: String
): AddAlbumEvent()
data class ReflectAlbumName(
val newAlbumName: String
): AddAlbumEvent()
data class AddWallpapers(
val wallpaperUris: List<String>
): AddAlbumEvent()
@@ -24,11 +23,17 @@ sealed class AddAlbumEvent {
data class SelectFolder(
val directoryUri: String
): AddAlbumEvent()
data class RemoveFolderFromSelection(
data class DeselectFolder(
val directoryUri: String
): AddAlbumEvent()
data class RemoveWallpaperFromSelection(
data class DeselectWallpaper(
val wallpaperUri: String
): AddAlbumEvent()
data class SetLoading(
val isLoading: Boolean
): AddAlbumEvent()
data class LoadFoldersAndWallpapers(
val folders: List<Folder>,
val wallpapers: List<Wallpaper>
): AddAlbumEvent()
}
@@ -2,6 +2,8 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
@@ -9,53 +11,84 @@ import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumAnimatedFab
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumSmallTopBar
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.FolderItem
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import my.nanihadesuka.compose.LazyVerticalGridScrollbar
import my.nanihadesuka.compose.ScrollbarSettings
@Composable
fun AddAlbumScreen(
addAlbumViewModel: AddAlbumViewModel = hiltViewModel(),
addAlbumViewModel: AddAlbumViewModel,
initialAlbumName: String,
onBackClick: () -> Unit,
onConfirmation: () -> Unit,
onShowWallpaperView: (String) -> Unit,
onShowFolderView: (String?, List<String>) -> Unit,
animate: Boolean
onShowWallpaperView: (String, String) -> Unit,
onShowFolderView: (Folder) -> Unit,
onSortClick: (List<Folder>, List<Wallpaper>) -> Unit,
animate: Boolean // This likely controls item animation, similar to AlbumViewScreen
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val addAlbumState by addAlbumViewModel.state.collectAsStateWithLifecycle() // Use by for direct access
val lazyListState = rememberLazyGridState()
val addAlbumState = addAlbumViewModel.state.collectAsStateWithLifecycle()
var selectionMode by rememberSaveable { mutableStateOf(false) }
var showSpotlight by rememberSaveable { mutableStateOf(false) }
// Remember scrollbar settings for consistency and performance
val colorScheme = MaterialTheme.colorScheme
val scrollbarSettings = remember {
ScrollbarSettings.Default.copy(
thumbUnselectedColor = colorScheme.primary,
thumbSelectedColor = colorScheme.primary,
thumbShape = RoundedCornerShape(16.dp),
scrollbarPadding = 1.dp,
)
}
// Remember common modifier for grid items for consistency and responsiveness
val commonItemModifier = remember {
Modifier
.fillMaxWidth()
.aspectRatio(9f / 16f) // Common aspect ratio for wallpapers/photos
}
BackHandler(
enabled = selectionMode,
onBack = {
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
selectionMode = false
enabled = addAlbumState.selectionState.selectedCount > 0,
onBack = remember(addAlbumState.isLoading, addAlbumViewModel) { // Remember the lambda
{
if (!addAlbumState.isLoading) {
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
}
}
}
)
@@ -63,14 +96,37 @@ fun AddAlbumScreen(
val imagePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenMultipleDocuments(),
onResult = { uris: List<Uri> ->
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
val uriList = uris.mapNotNull { uri ->
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
if (persistedUriPermissions.any { it.uri == uri }) uri.toString() else null
val selectionLimit = 500
if (uris.size > selectionLimit) {
// Inform the user that they selected too many files.
Toast.makeText(
context,
"Please select fewer than $selectionLimit images at a time. For bulk imports, use the 'Add Folder' option.",
Toast.LENGTH_LONG
).show()
}
if (uriList.isNotEmpty()) {
addAlbumViewModel.onEvent(AddAlbumEvent.AddWallpapers(uriList))
else if (uris.isNotEmpty()) {
scope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {
addAlbumViewModel.onEvent(AddAlbumEvent.SetLoading(true))
}
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
val uriList = uris.mapNotNull { uri ->
try {
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
uri.toString()
} catch (e: Exception) {
Log.e("AddAlbumScreen", "Failed to take persistable URI permission for image: ${e.message}")
null
}
}
withContext(Dispatchers.Main) {
if (uriList.isNotEmpty()) {
addAlbumViewModel.onEvent(AddAlbumEvent.AddWallpapers(uriList))
}
addAlbumViewModel.onEvent(AddAlbumEvent.SetLoading(false))
}
}
}
}
)
@@ -79,12 +135,17 @@ fun AddAlbumScreen(
val folderPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocumentTree(),
onResult = { uri: Uri? ->
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
if (uri != null) {
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
if (persistedUriPermissions.any { it.uri == uri }) {
addAlbumViewModel.onEvent(AddAlbumEvent.AddFolder(uri.toString()))
scope.launch(Dispatchers.IO) {
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
if (uri != null) {
try {
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
withContext(Dispatchers.Main) {
addAlbumViewModel.onEvent(AddAlbumEvent.AddFolder(uri.toString()))
}
} catch (e: Exception) {
Log.e("AddAlbumScreen", "Failed to take persistable URI permission: ${e.message}")
}
}
}
}
@@ -92,168 +153,196 @@ fun AddAlbumScreen(
Scaffold(
topBar = {
AddAlbumSmallTopBar(
title = initialAlbumName,
isEmpty = addAlbumState.value.isEmpty,
selectionMode = selectionMode,
albumState = addAlbumViewModel.state,
showSpotlight = showSpotlight,
onBackClick = {
val onBackClickTopBar = remember(addAlbumViewModel, onBackClick) {
{
showSpotlight = false
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
onBackClick()
},
onConfirmationClick = {
showSpotlight = false
addAlbumViewModel.onEvent(AddAlbumEvent.ReflectAlbumName(it))
addAlbumViewModel.onEvent(AddAlbumEvent.SaveAlbum)
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
onConfirmation()
},
onSelectAllClick = {
if (!addAlbumState.value.allSelected) addAlbumViewModel.onEvent(AddAlbumEvent.SelectAll)
else addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
},
onDeleteSelected = {
selectionMode = false
addAlbumViewModel.onEvent(AddAlbumEvent.DeleteSelected)
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
}
}
val onConfirmationClickTopBar = remember(addAlbumState.isLoading, addAlbumViewModel, initialAlbumName, onConfirmation) {
{ text: String ->
if (!addAlbumState.isLoading) {
showSpotlight = false
addAlbumViewModel.onEvent(AddAlbumEvent.SaveAlbum(text))
onConfirmation()
}
}
}
val onSelectAllClickTopBar = remember(addAlbumState.isLoading, addAlbumState.selectionState.allSelected, addAlbumViewModel) {
{
if (!addAlbumState.isLoading) {
if (!addAlbumState.selectionState.allSelected) {
addAlbumViewModel.onEvent(AddAlbumEvent.SelectAll)
} else {
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
}
}
}
}
val onDeleteSelectedTopBar = remember(addAlbumState.isLoading, addAlbumViewModel) {
{
if (!addAlbumState.isLoading) {
addAlbumViewModel.onEvent(AddAlbumEvent.DeleteSelected)
}
}
}
val onSortClickTopBar = remember(addAlbumState.isLoading, addAlbumViewModel, addAlbumState.folders, addAlbumState.wallpapers, onSortClick) {
{
if (!addAlbumState.isLoading) {
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
onSortClick(addAlbumState.folders, addAlbumState.wallpapers)
}
}
}
AddAlbumSmallTopBar(
title = initialAlbumName,
allSelected = addAlbumState.selectionState.allSelected,
selectedCount = addAlbumState.selectionState.selectedCount,
isEmpty = addAlbumState.isEmpty,
selectionMode = addAlbumState.selectionState.selectedCount > 0,
showSpotlight = showSpotlight,
isLoad = addAlbumState.isLoading,
onBackClick = onBackClickTopBar,
onConfirmationClick = onConfirmationClickTopBar,
onSelectAllClick = onSelectAllClickTopBar,
onDeleteSelected = onDeleteSelectedTopBar,
onSortClick = onSortClickTopBar
)
},
floatingActionButton = {
AddAlbumAnimatedFab(
onImageClick = {
selectionMode = false
// Remember FAB callbacks
val onImageClickFab = remember(addAlbumViewModel, imagePickerLauncher) {
{
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
imagePickerLauncher.launch(arrayOf("image/*"))
},
onFolderClick = {
selectionMode = false
}
}
val onFolderClickFab = remember(addAlbumViewModel, folderPickerLauncher) {
{
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
folderPickerLauncher.launch(null)
}
}
AddAlbumAnimatedFab(
isLoading = addAlbumState.isLoading,
animate = animate,
onImageClick = onImageClickFab,
onFolderClick = onFolderClickFab
)
},
content = {
bottomBar = {
if (addAlbumState.isLoading) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
},
content = { paddingValues -> // Use paddingValues from Scaffold
LazyVerticalGridScrollbar(
state = lazyListState,
settings = ScrollbarSettings.Default.copy(
thumbUnselectedColor = MaterialTheme.colorScheme.primary,
thumbSelectedColor = MaterialTheme.colorScheme.primary,
thumbShape = RoundedCornerShape(16.dp),
scrollbarPadding = 1.dp,
),
settings = scrollbarSettings, // Use remembered settings
modifier = Modifier
.fillMaxSize()
.padding(it),
.padding(paddingValues), // Apply Scaffold padding
) {
LazyVerticalGrid(
state = lazyListState,
modifier = Modifier.fillMaxSize(),
columns = GridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp, 4.dp),
horizontalArrangement = Arrangement.Start,
contentPadding = PaddingValues(4.dp), // Apply padding to grid content
horizontalArrangement = Arrangement.spacedBy(4.dp), // Use spacedBy for consistent spacing
verticalArrangement = Arrangement.spacedBy(4.dp), // Use spacedBy for consistent spacing
) {
items(count = addAlbumState.value.folders.size, key = { index -> addAlbumState.value.folders[index].folderUri }) { index ->
if (animate) {
FolderItem(
folder = addAlbumState.value.folders[index],
itemSelected = addAlbumState.value.selectedFolders.contains(addAlbumState.value.folders[index].folderUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
addAlbumViewModel.onEvent(
if (!addAlbumState.value.selectedFolders.contains(addAlbumState.value.folders[index].folderUri))
AddAlbumEvent.SelectFolder(addAlbumState.value.folders[index].folderUri)
else {
AddAlbumEvent.RemoveFolderFromSelection(addAlbumState.value.folders[index].folderUri)
}
)
},
onFolderViewClick = {
if (addAlbumState.value.folders[index].wallpapers.isNotEmpty()) onShowFolderView(addAlbumState.value.folders[index].folderName, addAlbumState.value.folders[index].wallpapers)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
),
)
)
items(
items = addAlbumState.folders,
key = { folder -> folder.folderUri }
) { folder -> // Renamed 'it' to 'folder' for clarity
val isSelected = addAlbumState.selectionState.selectedFolders.contains(folder.folderUri)
val onFolderItemSelection = remember(folder.folderUri, addAlbumState.isLoading, addAlbumViewModel, isSelected) {
{
if (!addAlbumState.isLoading) {
if (!isSelected) {
addAlbumViewModel.onEvent(AddAlbumEvent.SelectFolder(folder.folderUri))
} else {
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectFolder(folder.folderUri))
}
}
}
}
else {
FolderItem(
folder = addAlbumState.value.folders[index],
itemSelected = addAlbumState.value.selectedFolders.contains(addAlbumState.value.folders[index].folderUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
addAlbumViewModel.onEvent(
if (!addAlbumState.value.selectedFolders.contains(addAlbumState.value.folders[index].folderUri))
AddAlbumEvent.SelectFolder(addAlbumState.value.folders[index].folderUri)
else {
AddAlbumEvent.RemoveFolderFromSelection(addAlbumState.value.folders[index].folderUri)
}
)
},
onFolderViewClick = {
if (addAlbumState.value.folders[index].wallpapers.isNotEmpty()) onShowFolderView(addAlbumState.value.folders[index].folderName, addAlbumState.value.folders[index].wallpapers)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
val onFolderViewClickItem = remember(folder, addAlbumState.isLoading, onShowFolderView) {
{
if (!addAlbumState.isLoading) {
onShowFolderView(folder)
}
}
}
}
items(count = addAlbumState.value.wallpapers.size, key = { index -> addAlbumState.value.wallpapers[index].wallpaperUri }) { index ->
if (animate) {
WallpaperItem(
wallpaperUri = addAlbumState.value.wallpapers[index].wallpaperUri,
itemSelected = addAlbumState.value.selectedWallpapers.contains(addAlbumState.value.wallpapers[index].wallpaperUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
addAlbumViewModel.onEvent(
if (!addAlbumState.value.selectedWallpapers.contains(addAlbumState.value.wallpapers[index].wallpaperUri))
AddAlbumEvent.SelectWallpaper(addAlbumState.value.wallpapers[index].wallpaperUri)
else {
AddAlbumEvent.RemoveWallpaperFromSelection(addAlbumState.value.wallpapers[index].wallpaperUri)
}
)
},
onWallpaperViewClick = {
onShowWallpaperView(addAlbumState.value.wallpapers[index].wallpaperUri)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
FolderItem(
folder = folder,
itemSelected = isSelected,
selectionMode = addAlbumState.selectionState.selectedCount > 0,
onItemSelection = onFolderItemSelection,
onFolderViewClick = onFolderViewClickItem,
modifier = commonItemModifier // Use common responsive modifier
.then(
if (animate) Modifier.animateItem( // Add item animation
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
)
)
)
) else Modifier
)
)
}
items(
items = addAlbumState.wallpapers,
key = { wallpaper -> wallpaper.wallpaperUri }
) { wallpaper -> // Renamed 'it' to 'wallpaper' for clarity
val isSelected = addAlbumState.selectionState.selectedWallpapers.contains(wallpaper.wallpaperUri)
val onWallpaperItemSelection = remember(wallpaper.wallpaperUri, addAlbumState.isLoading, addAlbumViewModel, isSelected) {
{
if (!addAlbumState.isLoading) {
if (!isSelected) {
addAlbumViewModel.onEvent(AddAlbumEvent.SelectWallpaper(wallpaper.wallpaperUri))
} else {
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectWallpaper(wallpaper.wallpaperUri))
}
}
}
}
else {
WallpaperItem(
wallpaperUri = addAlbumState.value.wallpapers[index].wallpaperUri,
itemSelected = addAlbumState.value.selectedWallpapers.contains(addAlbumState.value.wallpapers[index].wallpaperUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
},
onWallpaperViewClick = {
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
val onWallpaperViewClickItem = remember(wallpaper, addAlbumState.isLoading, onShowWallpaperView) {
{
if (!addAlbumState.isLoading) {
onShowWallpaperView(wallpaper.wallpaperUri, wallpaper.fileName)
}
}
}
WallpaperItem(
wallpaperUri = wallpaper.wallpaperUri,
itemSelected = isSelected,
selectionMode = addAlbumState.selectionState.selectedCount > 0,
onItemSelection = onWallpaperItemSelection,
onWallpaperViewClick = onWallpaperViewClickItem,
modifier = commonItemModifier // Use common responsive modifier
.then(
if (animate) Modifier.animateItem( // Add item animation
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
)
) else Modifier
)
)
}
}
}
@@ -3,13 +3,15 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
data class AddAlbumState (
val initialAlbumName: String = "",
val displayedAlbumName: String = "",
val coverUri: String = "",
data class AddAlbumState(
val wallpapers: List<Wallpaper> = emptyList(),
val folders: List<Folder> = emptyList(),
val selectionState: SelectionState = SelectionState(),
val isEmpty: Boolean = true,
val isLoading: Boolean = false
)
data class SelectionState(
val selectedWallpapers: List<String> = emptyList(),
val selectedFolders: List<String> = emptyList(),
val allSelected: Boolean = false,
@@ -1,11 +1,12 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.getFolderNameFromUri
import com.anthonyla.paperize.core.compress
import com.anthonyla.paperize.core.getFolderMetadata
import com.anthonyla.paperize.core.getImageMetadata
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
@@ -38,211 +39,240 @@ class AddAlbumViewModel @Inject constructor(
is AddAlbumEvent.SaveAlbum -> {
viewModelScope.launch {
if (_state.value.wallpapers.isEmpty() && _state.value.folders.isEmpty()) { return@launch }
val albumCoverUri = when (_state.value.isEmpty) {
true -> ""
false -> {
if (_state.value.wallpapers.isNotEmpty())
_state.value.wallpapers.random().wallpaperUri
else {
_state.value.folders.random().coverUri
}
}
val wallpapers = _state.value.wallpapers.map {
it.copy(
initialAlbumName = event.initialAlbumName,
key = event.initialAlbumName.hashCode() + it.wallpaperUri.hashCode()
)
}
var totalWallpapers = _state.value.wallpapers.size
val folders = _state.value.folders.map { folder ->
val updatedWallpapers = folder.wallpapers.map {
it.copy(
initialAlbumName = event.initialAlbumName,
key = event.initialAlbumName.hashCode() + folder.folderUri.hashCode() + it.wallpaperUri.hashCode(),
order = it.order + totalWallpapers
)
}
totalWallpapers += folder.wallpapers.size
folder.copy(
initialAlbumName = event.initialAlbumName,
key = event.initialAlbumName.hashCode() + folder.hashCode(),
coverUri = updatedWallpapers.firstOrNull()?.wallpaperUri ?: folder.coverUri,
wallpapers = updatedWallpapers
)
}
val albumWithWallpaperAndFolder = AlbumWithWallpaperAndFolder(
album = Album(
initialAlbumName = _state.value.initialAlbumName,
displayedAlbumName = _state.value.displayedAlbumName,
coverUri = albumCoverUri,
initialized = false,
initialAlbumName = event.initialAlbumName,
displayedAlbumName = event.initialAlbumName,
coverUri = folders.firstOrNull()?.coverUri ?: wallpapers.firstOrNull()?.wallpaperUri ?: "",
homeWallpapersInQueue = emptyList(),
lockWallpapersInQueue = emptyList(),
selected = false
),
wallpapers = _state.value.wallpapers,
folders = _state.value.folders,
wallpapers = wallpapers,
folders = folders
)
repository.upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder)
_state.update { AddAlbumState() }
}
}
is AddAlbumEvent.DeleteSelected -> {
viewModelScope.launch {
val selectedWallpaperUris = _state.value.selectionState.selectedWallpapers.toSet()
val selectedFolderUris = _state.value.selectionState.selectedFolders.toSet()
val wallpapersRemoved = _state.value.wallpapers.filter { wallpaper ->
wallpaper.wallpaperUri !in selectedWallpaperUris
}
val foldersRemoved = _state.value.folders.filter { folder ->
folder.folderUri !in selectedFolderUris
}
_state.update {
val wallpapersRemoved = it.wallpapers.filterNot { it.wallpaperUri in _state.value.selectedWallpapers }
val foldersRemoved = it.folders.filterNot { it.folderUri in _state.value.selectedFolders }
it.copy(
wallpapers = wallpapersRemoved,
folders = foldersRemoved,
isEmpty = wallpapersRemoved.isEmpty() && foldersRemoved.isEmpty()
) }
}
}
is AddAlbumEvent.SetAlbumName -> {
viewModelScope.launch {
_state.update { it.copy(
initialAlbumName = event.initialAlbumName,
displayedAlbumName = event.initialAlbumName,
) }
isEmpty = wallpapersRemoved.isEmpty() && foldersRemoved.isEmpty(),
selectionState = SelectionState()
)
}
}
}
is AddAlbumEvent.ReflectAlbumName -> {
if (event.newAlbumName != _state.value.initialAlbumName) {
viewModelScope.launch {
_state.update {
val wallpapers = it.wallpapers.map { wallpaper ->
wallpaper.copy(initialAlbumName = event.newAlbumName)
}
val folders = it.folders.map { folder ->
folder.copy(initialAlbumName = event.newAlbumName)
}
it.copy(
initialAlbumName = event.newAlbumName,
displayedAlbumName = event.newAlbumName,
coverUri = it.coverUri,
wallpapers = wallpapers,
folders = folders,
isEmpty = wallpapers.isEmpty() && folders.isEmpty()
) }
}
}
}
is AddAlbumEvent.AddWallpapers -> {
viewModelScope.launch {
val newWallpaperUris = event.wallpaperUris.filterNot { it in _state.value.wallpapers.map { wallpaper -> wallpaper.wallpaperUri } }
val newWallpapers = newWallpaperUris.map { uri ->
Wallpaper(
initialAlbumName = _state.value.initialAlbumName,
wallpaperUri = uri,
key = uri.hashCode() + _state.value.initialAlbumName.hashCode() + System.currentTimeMillis().toInt()
)
val existingWallpapers = _state.value.wallpapers.map { it.wallpaperUri }.toSet()
val newWallpapers = event.wallpaperUris.filter { wallpaperUri ->
wallpaperUri !in existingWallpapers
}
val wallpapers = _state.value.wallpapers.plus(
newWallpapers.mapIndexed { index, wallpaperUri ->
val metadata = getImageMetadata(context, wallpaperUri)
Wallpaper(
initialAlbumName = "",
wallpaperUri = wallpaperUri.compress("content://com.android.externalstorage.documents/"),
fileName = metadata.filename,
dateModified = metadata.lastModified,
order = index + _state.value.wallpapers.size,
key = 0
)
}
)
_state.update {
it.copy(
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
allSelected = false,
selectedCount = 0,
wallpapers = it.wallpapers.plus(newWallpapers),
isEmpty = false
wallpapers = wallpapers,
isEmpty = false,
selectionState = SelectionState(),
isLoading = false
)
}
}
}
is AddAlbumEvent.AddFolder -> {
viewModelScope.launch {
if (event.directoryUri !in _state.value.folders.map { it.folderUri }) {
val wallpapers: List<String> = getWallpaperFromFolder(event.directoryUri, context)
if (wallpapers.isEmpty()) { return@launch }
val folderName = getFolderNameFromUri(event.directoryUri, context)
_state.update {
it.copy(
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
allSelected = false,
selectedCount = 0,
isEmpty = false,
folders = it.folders.plus(
Folder(
initialAlbumName = it.initialAlbumName,
folderName = folderName,
folderUri = event.directoryUri,
coverUri = wallpapers.randomOrNull(),
wallpapers = wallpapers,
key = event.directoryUri.hashCode() + it.initialAlbumName.hashCode() + System.currentTimeMillis().toInt()
)
if (event.directoryUri in _state.value.folders.map { it.folderUri }) {
return@launch
}
_state.update { it.copy(isLoading = true) }
val wallpapers = getWallpaperFromFolder(event.directoryUri, context)
val metadata = getFolderMetadata(event.directoryUri, context)
val folder = Folder(
initialAlbumName = "",
folderName = metadata.filename,
folderUri = event.directoryUri,
wallpapers = wallpapers,
coverUri = wallpapers.firstOrNull()?.wallpaperUri ?: "",
dateModified = metadata.lastModified,
order = if (_state.value.folders.isEmpty()) 0 else _state.value.folders.size,
key = 0
)
_state.update {
it.copy(
folders = it.folders.plus(folder),
isEmpty = false,
selectionState = SelectionState(),
isLoading = false
)
}
}
}
is AddAlbumEvent.SelectAll -> {
viewModelScope.launch {
if (!_state.value.selectionState.allSelected) {
_state.update { state ->
state.copy(
selectionState = SelectionState(
selectedFolders = state.folders.map { it.folderUri },
selectedWallpapers = state.wallpapers.map { it.wallpaperUri },
allSelected = true,
selectedCount = state.folders.size + state.wallpapers.size
)
)
}
}
}
}
is AddAlbumEvent.SelectAll -> {
viewModelScope.launch {
if (!_state.value.allSelected) {
_state.update { it.copy(
selectedFolders = _state.value.folders.map { folder -> folder.folderUri },
selectedWallpapers = _state.value.wallpapers.map { wallpaper -> wallpaper.wallpaperUri },
selectedCount = it.folders.size + it.wallpapers.size,
allSelected = true
) }
}
}
}
is AddAlbumEvent.DeselectAll-> {
viewModelScope.launch {
_state.update { it.copy(
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
selectedCount = 0,
allSelected = false
) }
_state.update { it.copy(selectionState = SelectionState()) }
}
}
is AddAlbumEvent.SelectFolder -> {
viewModelScope.launch {
if (!_state.value.selectedFolders.any { it == event.directoryUri }) {
_state.update {
val folders = it.selectedFolders.plus(event.directoryUri)
it.copy(
selectedFolders = folders,
selectedCount = it.selectedCount + 1,
allSelected = folders.size + it.selectedWallpapers.size >= it.wallpapers.size + it.folders.size
) }
val folderUri = (_state.value.folders.find { it.folderUri == event.directoryUri } ?: return@launch).folderUri
_state.update {
val newSelectedFolders = it.selectionState.selectedFolders.plus(folderUri)
it.copy(
selectionState = it.selectionState.copy(
selectedFolders = newSelectedFolders,
selectedCount = newSelectedFolders.size + it.selectionState.selectedWallpapers.size,
allSelected = newSelectedFolders.size + it.selectionState.selectedWallpapers.size >=
it.wallpapers.size + it.folders.size
)
)
}
}
}
is AddAlbumEvent.SelectWallpaper -> {
viewModelScope.launch {
if (!_state.value.selectedWallpapers.any { it == event.wallpaperUri }) {
if (!_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
_state.update {
val wallpapers = it.selectedWallpapers.plus(event.wallpaperUri)
val newSelectedWallpapers = it.selectionState.selectedWallpapers.plus(event.wallpaperUri)
it.copy(
selectedWallpapers = wallpapers,
selectedCount = it.selectedCount + 1,
allSelected = it.selectedFolders.size + wallpapers.size >= it.wallpapers.size + it.folders.size
) }
selectionState = it.selectionState.copy(
selectedWallpapers = newSelectedWallpapers,
selectedCount = newSelectedWallpapers.size + it.selectionState.selectedFolders.size,
allSelected = it.selectionState.selectedFolders.size + newSelectedWallpapers.size >=
it.wallpapers.size + it.folders.size
)
)
}
}
}
}
is AddAlbumEvent.RemoveFolderFromSelection -> {
viewModelScope.launch {
if (_state.value.selectedFolders.find { it == event.directoryUri } != null ) {
_state.update {
val folders = it.selectedFolders.minus(event.directoryUri)
it.copy(
selectedFolders = folders,
selectedCount = it.selectedCount - 1,
allSelected = folders.size + it.selectedWallpapers.size >= it.wallpapers.size + it.folders.size
) }
}
}
}
is AddAlbumEvent.RemoveWallpaperFromSelection -> {
is AddAlbumEvent.DeselectFolder -> {
viewModelScope.launch {
if (_state.value.selectedWallpapers.find { it == event.wallpaperUri } != null ) {
_state.update {
val wallpapers = it.selectedWallpapers.minus(event.wallpaperUri)
it.copy(
selectedWallpapers = wallpapers,
selectedCount = it.selectedCount - 1,
allSelected = it.selectedFolders.size + wallpapers.size >= it.wallpapers.size + it.folders.size
) }
val folderUri = (_state.value.folders.find { it.folderUri == event.directoryUri } ?: return@launch).folderUri
_state.update {
val newSelectedFolders = it.selectionState.selectedFolders.minus(folderUri)
it.copy(
selectionState = it.selectionState.copy(
selectedFolders = newSelectedFolders,
selectedCount = it.selectionState.selectedCount - 1,
allSelected = false
)
)
}
}
}
is AddAlbumEvent.DeselectWallpaper -> {
viewModelScope.launch {
if (_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
_state.update {
val newSelectedWallpapers = it.selectionState.selectedWallpapers.minus(event.wallpaperUri)
it.copy(
selectionState = it.selectionState.copy(
selectedWallpapers = newSelectedWallpapers,
selectedCount = it.selectionState.selectedCount - 1,
allSelected = false
)
)
}
}
}
}
is AddAlbumEvent.LoadFoldersAndWallpapers -> {
viewModelScope.launch {
_state.update {
it.copy(
folders = event.folders,
wallpapers = event.wallpapers,
isEmpty = event.folders.isEmpty() && event.wallpapers.isEmpty(),
selectionState = SelectionState(),
isLoading = false
)
}
}
}
is AddAlbumEvent.SetLoading -> {
viewModelScope.launch {
_state.update { it.copy(isLoading = event.isLoading) }
}
}
is AddAlbumEvent.Reset -> {
viewModelScope.launch {
_state.update { it.copy(
initialAlbumName = "",
displayedAlbumName = "",
coverUri = "",
wallpapers = emptyList(),
folders = emptyList(),
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
isEmpty = false,
allSelected = false,
selectedCount = 0,
) }
_state.update { AddAlbumState() }
}
}
}
@@ -1,223 +1,201 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.togetherWith
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.PhotoLibrary
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FloatingActionButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.LargeFloatingActionButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
/**
* Animated FAB that expands to show two options: Add image and Add folder
* Source: https://github.com/rajaumair7890/AnimatedFABMenu
*/
@Composable
fun AddAlbumAnimatedFab(
isLoading: Boolean,
animate: Boolean,
onImageClick: () -> Unit,
onFolderClick: () -> Unit
) {
val expandedWidth = 165.dp
val itemSize = 2
val collapsedFabSize = 96.dp
val expandedFabHeight = 60.dp
val menuItemHeight = 56.dp
val menuItemCount = 2
val menuColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
val fabColor = MaterialTheme.colorScheme.primaryContainer
var isFabExpanded by remember { mutableStateOf(false) }
BackHandler(isFabExpanded) { isFabExpanded = false }
val fabTransition = updateTransition(targetState = isFabExpanded, label = "fabTransition")
val transition = updateTransition(targetState = isFabExpanded, label = "fabTransition")
val expandFabHorizontally by fabTransition.animateDp(
val fabWidth by transition.animateDp(
label = "fabWidth",
transitionSpec = {
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
},
label = "expandVertically",
targetValueByState = {isExpanded ->
if (isExpanded) expandedWidth else 96.dp
if (animate) {
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
} else {
snap()
}
}
)
) { expanded ->
if (expanded) expandedWidth else collapsedFabSize
}
val shrinkFabVertically by fabTransition.animateDp(
val fabHeight by transition.animateDp(
label = "fabHeight",
transitionSpec = {
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
},
label = "shrinkHorizontally",
targetValueByState = {isExpanded ->
if (isExpanded) 60.dp else 96.dp
if (animate) {
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
} else {
snap()
}
}
)
) { expanded ->
if (expanded) expandedFabHeight else collapsedFabSize
}
val menuHeight by fabTransition.animateDp(
transitionSpec = {
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
},
val menuHeight by transition.animateDp(
label = "menuHeight",
targetValueByState = {isExpanded ->
if (isExpanded) (itemSize * 50).dp else 0.dp
transitionSpec = {
if (animate) {
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
} else {
snap()
}
}
)
) { expanded ->
if (expanded) menuItemHeight * menuItemCount else 0.dp
}
val fabIconTransitionSpec: AnimatedContentTransitionScope<Boolean>.() -> ContentTransform = {
if (animate) {
(scaleIn(tween(100, 300, FastOutSlowInEasing)) + fadeIn(tween(250, 300, LinearEasing)))
.togetherWith(fadeOut(tween(10, 0, LinearEasing)))
} else {
EnterTransition.None.togetherWith(ExitTransition.None)
}
}
ElevatedCard(
modifier = Modifier.padding(4.dp),
shape = RoundedCornerShape(28.dp),
elevation = CardDefaults.elevatedCardElevation(4.dp),
colors = CardDefaults.elevatedCardColors().copy(
colors = CardDefaults.elevatedCardColors(
containerColor = menuColor
)
) {
Column(
modifier = Modifier
.height(menuHeight)
.width(fabWidth),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier.height(menuHeight)
verticalArrangement = Arrangement.SpaceEvenly
) {
AnimatedVisibility(
visible = isFabExpanded,
label = stringResource(R.string.add_images_btn),
enter = fadeIn(tween(300, 150, LinearEasing)),
exit = fadeOut(tween(200, 50, LinearEasing)) + scaleOut(),
enter = if (animate) fadeIn(tween(300, 150, LinearEasing)) else EnterTransition.None,
exit = if (animate) fadeOut(tween(200, 50, LinearEasing)) + scaleOut() else ExitTransition.None
) {
Row(
MenuItemRow(
icon = Icons.Filled.PhotoLibrary,
text = stringResource(R.string.add_images_btn),
onClick = {
onImageClick()
isFabExpanded = false
},
modifier = Modifier
.width(expandFabHorizontally)
.clickable {
onImageClick()
isFabExpanded = false
},
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Filled.PhotoLibrary,
contentDescription = stringResource(R.string.add_images_btn),
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 12.dp)
)
Spacer(modifier = Modifier.weight(1f))
Text(
text = stringResource(R.string.add_images_btn),
modifier = Modifier.padding(end = 16.dp, top = 12.dp, bottom = 12.dp),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
.fillMaxWidth()
.height(menuItemHeight)
)
}
AnimatedVisibility(
visible = isFabExpanded,
label = stringResource(R.string.add_folder_btn),
enter = fadeIn(tween(300, 150, LinearEasing)),
exit = fadeOut(tween(200, 50, LinearEasing)) + scaleOut(),
enter = if (animate) fadeIn(tween(300, 150, LinearEasing)) else EnterTransition.None,
exit = if (animate) fadeOut(tween(200, 50, LinearEasing)) + scaleOut() else ExitTransition.None
) {
Row(
MenuItemRow(
icon = Icons.Filled.Folder,
text = stringResource(R.string.add_folder_btn),
onClick = {
onFolderClick()
isFabExpanded = false
},
modifier = Modifier
.width(expandFabHorizontally)
.clickable {
onFolderClick()
isFabExpanded = false
},
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Filled.Folder,
contentDescription = stringResource(R.string.add_folder_btn),
modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 12.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.weight(1f))
Text(
text = stringResource(R.string.add_folder_btn),
modifier = Modifier.padding(end = 16.dp, top = 12.dp, bottom = 12.dp),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
.fillMaxWidth()
.height(menuItemHeight)
)
}
}
LargeFloatingActionButton(
elevation = FloatingActionButtonDefaults.elevation(4.dp),
shape = RoundedCornerShape(28),
containerColor = fabColor,
onClick = { isFabExpanded = !isFabExpanded },
onClick = { if (!isLoading) isFabExpanded = !isFabExpanded },
modifier = Modifier
.width(expandFabHorizontally)
.height(shrinkFabVertically)
.width(fabWidth)
.height(fabHeight),
shape = RoundedCornerShape(28.dp),
containerColor = fabColor,
elevation = FloatingActionButtonDefaults.elevation(4.dp)
) {
AnimatedContent(
isFabExpanded,
transitionSpec = {
when (targetState) {
true -> {
(
scaleIn(
tween(100, 300, FastOutSlowInEasing)
) + fadeIn(
tween(250, 300, LinearEasing)
)
) .togetherWith(
fadeOut(
tween(10, 0, LinearEasing)
)
)
}
false -> {
fadeIn(
tween(250, 200, FastOutSlowInEasing)
).togetherWith(
fadeOut(
tween(10, 0, LinearEasing),
)
)
}
}
},
targetState = isFabExpanded,
transitionSpec = fabIconTransitionSpec,
label = "FabContent"
) { isExpanded ->
) { expanded ->
Icon(
imageVector = if (isExpanded) Icons.Filled.Remove else Icons.Filled.Add,
contentDescription = stringResource(R.string.add_wallpaper),
imageVector = if (expanded) Icons.Filled.Remove else Icons.Filled.Add,
contentDescription = stringResource(R.string.add_wallpaper)
)
}
}
}
}
/**
* Reusable Composable for a single menu item row.
*/
@Composable
private fun MenuItemRow(
modifier: Modifier = Modifier,
icon: ImageVector,
text: String,
onClick: () -> Unit
) {
Row(
modifier = modifier.clickable(onClick = onClick),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = icon,
contentDescription = text,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 16.dp)
)
Spacer(modifier = Modifier.width(16.dp))
Text(
text = text,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f)
)
}
}
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components
import android.R.attr.contentDescription
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
@@ -19,7 +20,9 @@ import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
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.CheckCircle
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.Delete
@@ -32,6 +35,7 @@ import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -49,10 +53,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumState
import kotlinx.coroutines.flow.StateFlow
/**
* Top bar for the Add Album screen
@@ -60,50 +61,48 @@ import kotlinx.coroutines.flow.StateFlow
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddAlbumSmallTopBar(
albumState: StateFlow<AddAlbumState>,
title: String,
isEmpty: Boolean,
allSelected: Boolean,
selectedCount: Int,
selectionMode: Boolean,
showSpotlight: Boolean,
isLoad: Boolean,
onSelectAllClick: () -> Unit,
onBackClick: () -> Unit,
onDeleteSelected: () -> Unit,
onConfirmationClick: (String) -> Unit
onConfirmationClick: (String) -> Unit,
onSortClick: () -> Unit
) {
val state = albumState.collectAsStateWithLifecycle()
val focusManager = LocalFocusManager.current
var editableTitle by rememberSaveable { mutableStateOf(title) }
var showSelectionDeleteDialog by rememberSaveable { mutableStateOf(false) }
val infiniteTransition = rememberInfiniteTransition(label = stringResource(R.string.spotlight_animation))
val radius1 by infiniteTransition.animateFloat(
initialValue = 25f,
targetValue = 50f,
animationSpec = infiniteRepeatable(
animation = tween(2000, easing = LinearOutSlowInEasing),
repeatMode = RepeatMode.Reverse
), label = stringResource(R.string.circle_1_animation)
)
val radius2 by infiniteTransition.animateFloat(
initialValue = 25f,
targetValue = 60f,
animationSpec = infiniteRepeatable(
animation = tween(2000, easing = LinearOutSlowInEasing),
repeatMode = RepeatMode.Reverse
), label = stringResource(R.string.circle_2_animation)
)
val radiusValues = listOf(50f, 60f, 75f).map { targetValue ->
infiniteTransition.animateFloat(
initialValue = 25f,
targetValue = targetValue,
animationSpec = infiniteRepeatable(
animation = tween(2000, easing = LinearOutSlowInEasing),
repeatMode = RepeatMode.Reverse
),
label = "circle_${targetValue}_animation"
)
}
val radius3 by infiniteTransition.animateFloat(
initialValue = 25f,
targetValue = 75f,
animationSpec = infiniteRepeatable(
animation = tween(2000, easing = LinearOutSlowInEasing),
repeatMode = RepeatMode.Reverse
), label = stringResource(R.string.circle_3_animation)
)
if (showSelectionDeleteDialog) {
DeleteImagesAlertDialog(
onDismissRequest = { showSelectionDeleteDialog = false },
onConfirmation = {
showSelectionDeleteDialog = false
onDeleteSelected()
}
)
}
TopAppBar(
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(containerColor = MaterialTheme.colorScheme.surface),
colors = topAppBarColors(containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)),
title = {
if (!selectionMode) {
TextField(
@@ -111,6 +110,7 @@ fun AddAlbumSmallTopBar(
onValueChange = { editableTitle = it },
placeholder = { Text(stringResource(R.string.enter_the_name_of_the_album)) },
singleLine = true,
readOnly = isLoad,
textStyle = MaterialTheme.typography.titleLarge,
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
@@ -121,7 +121,7 @@ fun AddAlbumSmallTopBar(
isError = editableTitle.isEmpty(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() })
)
@@ -137,90 +137,83 @@ fun AddAlbumSmallTopBar(
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.home_screen),
contentDescription = stringResource(id = R.string.home_screen)
)
}
}
else {
Row (
} else {
Row(
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
IconButton(onClick = onSelectAllClick) {
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
if (state.value.allSelected) {
Icon(
imageVector = Icons.Default.CheckCircle,
contentDescription = stringResource(R.string.all_images_selected_for_deletion),
modifier = Modifier
Icon(
imageVector = if (allSelected) Icons.Default.CheckCircle else Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(
if (allSelected) R.string.all_images_selected_for_deletion
else R.string.select_all_images_for_deletion
),
modifier = if (allSelected) {
Modifier
.padding(4.dp)
.border(2.dp, bgColor, CircleShape)
.clip(CircleShape)
.background(bgColor)
)
} else {
Icon(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.select_all_images_for_deletion),
modifier = Modifier.padding(6.dp)
)
}
} else {
Modifier.padding(6.dp)
}
)
}
Text("${state.value.selectedCount} selected")
Text(stringResource(R.string.selected, selectedCount))
}
}
},
actions = {
if(!selectionMode) {
if (!selectionMode) {
if (!isEmpty && editableTitle.isNotEmpty()) {
Box {
val primaryColor = MaterialTheme.colorScheme.inversePrimary
val secondaryColor = MaterialTheme.colorScheme.secondary
IconButton(onClick = { onConfirmationClick(editableTitle) }) {
Icon(
imageVector = Icons.Outlined.Add,
contentDescription = stringResource(R.string.add_album),
modifier = Modifier.padding(6.dp)
)
Row {
Box {
IconButton(onClick = onSortClick) {
Icon(
imageVector = Icons.AutoMirrored.Default.Sort,
contentDescription = stringResource(R.string.sort_items),
modifier = Modifier.padding(6.dp)
)
}
}
if (!showSpotlight) {
Canvas(modifier = Modifier.matchParentSize()) {
drawCircle(
color = primaryColor,
radius = radius1,
center = Offset(size.width / 2, size.height / 2),
style = Stroke(width = 5f)
)
drawCircle(
color = secondaryColor,
radius = radius2,
center = Offset(size.width / 2, size.height / 2),
style = Stroke(width = 5f)
)
drawCircle(
color = primaryColor,
radius = radius3,
center = Offset(size.width / 2, size.height / 2),
style = Stroke(width = 5f)
Box {
IconButton(onClick = { onConfirmationClick(editableTitle) }) {
Icon(
imageVector = Icons.Outlined.Add,
contentDescription = stringResource(R.string.add_album),
modifier = Modifier.padding(6.dp)
)
}
if (!showSpotlight) {
val primaryColor = MaterialTheme.colorScheme.inversePrimary
val secondaryColor = MaterialTheme.colorScheme.secondary
val colors = listOf(primaryColor, secondaryColor, primaryColor)
val animationValues = radiusValues.map { it.value }
val pairs = animationValues.zip(colors)
Canvas(modifier = Modifier.matchParentSize()) {
pairs.forEach { (radius, color) ->
drawCircle(
color = color,
radius = radius,
center = Offset(size.width / 2, size.height / 2),
style = Stroke(width = 5f)
)
}
}
}
}
}
}
}
else {
if (showSelectionDeleteDialog) DeleteImagesAlertDialog (
onDismissRequest = { showSelectionDeleteDialog = false },
onConfirmation = {
showSelectionDeleteDialog = false
onDeleteSelected()
}
)
IconButton(
onClick = { showSelectionDeleteDialog = true }
) {
} else {
IconButton(onClick = { showSelectionDeleteDialog = true }) {
Icon(
imageVector = Icons.Outlined.Delete,
imageVector = if (showSelectionDeleteDialog) Icons.Filled.Delete else Icons.Outlined.Delete,
contentDescription = stringResource(R.string.select_all_images_for_deletion),
modifier = Modifier.padding(6.dp)
)
@@ -1,20 +1,16 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
sealed class AlbumsEvent {
data object RefreshAlbums: AlbumsEvent()
data object DeselectSelected: AlbumsEvent()
data object Reset: AlbumsEvent()
data object Refresh: AlbumsEvent()
data class DeleteAlbumWithWallpapers(
val albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder
): AlbumsEvent()
data class ChangeAlbumName(
val title: String,
val albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder
): AlbumsEvent()
data class InitializeAlbum(
val albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder
data class AddSelectedAlbum(
val album: AlbumWithWallpaperAndFolder,
val deselectAlbumName: String? = null,
val shuffle: Boolean = true
): AlbumsEvent()
data class RemoveSelectedAlbum(val deselectAlbumName: String): AlbumsEvent()
}
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
data class AlbumsState (
val albumsWithWallpapers: List<AlbumWithWallpaperAndFolder> = emptyList()
)
data class AlbumsState(
val albumsWithWallpapers: List<AlbumWithWallpaperAndFolder> = emptyList(),
val selectedAlbum: List<AlbumWithWallpaperAndFolder> = emptyList()
)
@@ -2,21 +2,22 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album
import android.app.Application
import android.content.Context
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.findFirstValidUri
import com.anthonyla.paperize.core.getFolderMetadata
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.core.isDirectory
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.lazygeniouz.dfc.file.DocumentFileCompat
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -27,227 +28,156 @@ class AlbumsViewModel @Inject constructor (
) : AndroidViewModel(application) {
private val context: Context
get() = getApplication<Application>().applicationContext
private val _state = MutableStateFlow(AlbumsState())
val state = _state.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000), AlbumsState()
private val _state = MutableStateFlow<AlbumsState>(AlbumsState())
val state = combine(
loadAlbumsFlow(),
loadSelectedAlbumFlow(),
_state
) { albums: List<AlbumWithWallpaperAndFolder>, selectedAlbum: List<AlbumWithWallpaperAndFolder>, currentState: AlbumsState ->
currentState.copy(
albumsWithWallpapers = albums,
selectedAlbum = selectedAlbum
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = AlbumsState()
)
init {
updateAlbums()
refreshAlbums()
}
private fun loadAlbumsFlow() = repository.getAlbumsWithWallpaperAndFolder()
private fun loadSelectedAlbumFlow() = repository.getSelectedAlbums()
init {
viewModelScope.launch {
state.collect { newState -> _state.value = newState }
}
}
fun onEvent(event: AlbumsEvent) {
when (event) {
is AlbumsEvent.DeleteAlbumWithWallpapers -> {
viewModelScope.launch(Dispatchers.IO) {
repository.cascadeDeleteAlbum(event.albumWithWallpaperAndFolder.album)
_state.update {
it.copy(
albumsWithWallpapers = it.albumsWithWallpapers.filterNot { albumWithWallpaper ->
albumWithWallpaper.album == event.albumWithWallpaperAndFolder.album
}
)
}
}
}
is AlbumsEvent.ChangeAlbumName -> {
viewModelScope.launch(Dispatchers.IO) {
if (!(_state.value.albumsWithWallpapers.any { it.album.displayedAlbumName == event.title })) {
repository.updateAlbum(
event.albumWithWallpaperAndFolder.album.copy(displayedAlbumName = event.title)
)
_state.update {
it.copy(
albumsWithWallpapers = it.albumsWithWallpapers.map { albumWithWallpaper ->
if (albumWithWallpaper.album == event.albumWithWallpaperAndFolder.album) {
albumWithWallpaper.copy(
album = albumWithWallpaper.album.copy(displayedAlbumName = event.title)
)
} else {
albumWithWallpaper
}
}
)
}
}
}
}
is AlbumsEvent.InitializeAlbum -> {
viewModelScope.launch(Dispatchers.IO) {
is AlbumsEvent.AddSelectedAlbum -> {
viewModelScope.launch {
event.deselectAlbumName?.let { repository.updateAlbumSelection(it, false) }
val homeWallpapers = if (event.shuffle) event.album.totalWallpapers.shuffled().map { it.wallpaperUri }
else event.album.sortedTotalWallpapers.map { it.wallpaperUri }
val lockWallpapers = if (event.shuffle) event.album.totalWallpapers.shuffled().map { it.wallpaperUri }
else event.album.sortedTotalWallpapers.map { it.wallpaperUri }
repository.updateAlbum(
event.albumWithWallpaperAndFolder.album.copy(
initialized = true
event.album.album.copy(
selected = true,
lockWallpapersInQueue = lockWallpapers,
homeWallpapersInQueue = homeWallpapers
)
)
_state.update {
it.copy(
albumsWithWallpapers = it.albumsWithWallpapers.map { albumWithWallpaper ->
if (albumWithWallpaper.album == event.albumWithWallpaperAndFolder.album) {
albumWithWallpaper.copy(
album = albumWithWallpaper.album.copy(
initialized = true
)
)
} else {
albumWithWallpaper
}
}
)
}
_state.value.albumsWithWallpapers
.filter { it.album.initialAlbumName != event.album.album.initialAlbumName }
.forEach { album ->
val otherHomeWallpapers = if (event.shuffle) album.totalWallpapers.shuffled().map { it.wallpaperUri }
else album.sortedTotalWallpapers.map { it.wallpaperUri }
val otherLockWallpapers = if (event.shuffle) album.totalWallpapers.shuffled().map { it.wallpaperUri }
else album.sortedTotalWallpapers.map { it.wallpaperUri }
repository.updateAlbum(
album.album.copy(
lockWallpapersInQueue = otherLockWallpapers,
homeWallpapersInQueue = otherHomeWallpapers
)
)
}
}
}
is AlbumsEvent.RefreshAlbums -> {
updateAlbums()
refreshAlbums()
is AlbumsEvent.RemoveSelectedAlbum -> {
viewModelScope.launch {
repository.updateAlbumSelection(event.deselectAlbumName, false)
}
}
is AlbumsEvent.DeselectSelected -> {
viewModelScope.launch {
repository.deselectAllAlbums()
}
}
is AlbumsEvent.Refresh -> {
viewModelScope.launch {
updateAlbums()
}
}
is AlbumsEvent.Reset -> {
viewModelScope.launch(Dispatchers.IO) {
viewModelScope.launch {
repository.deleteAllData()
_state.update { AlbumsState() }
}
}
}
}
/**
* Verify and remove stale data in Room database
*/
private fun updateAlbums() {
viewModelScope.launch(Dispatchers.IO) {
var albumWithWallpapers = repository.getAlbumsWithWallpaperAndFolder().first()
albumWithWallpapers.forEach { albumWithWallpaper ->
// Delete wallpaper if the URI is invalid
val invalidWallpapers = albumWithWallpaper.wallpapers.filterNot { wallpaper ->
try {
val file = DocumentFileCompat.fromSingleUri(
context,
wallpaper.wallpaperUri.toUri()
)
file?.exists() == true
} catch (e: Exception) {
val file =
DocumentFile.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
file?.exists() == true
}
}
if (invalidWallpapers.isNotEmpty()) {
repository.deleteWallpaperList(invalidWallpapers)
viewModelScope.launch {
_state.value.albumsWithWallpapers.forEach { album ->
// Remove invalid wallpapers
val validWallpapers = async {
album.wallpapers
.asSequence()
.filter { isValidUri(context, it.wallpaperUri) }
.mapIndexed { index, wallpaper -> wallpaper.copy(order = index) }
.toList()
}
// Update folder cover uri and wallpapers uri
albumWithWallpaper.folders.forEach { folder ->
try {
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())
?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
repository.deleteFolder(folder)
} else {
val wallpapers =
// Remove invalid folders and inner wallpapers
val validFolders = async {
album.folders
.asSequence()
.filterNot { isDirectory(context, it.folderUri) }
.map { folder ->
async {
val metadata = getFolderMetadata(folder.folderUri, context)
if (metadata.lastModified != folder.dateModified) {
val existingWallpapers = folder.wallpapers
.asSequence()
.filter { isValidUri(context, it.wallpaperUri) }
.mapIndexed { index, wallpaper -> wallpaper.copy(order = index) }
.toList()
val newWallpapers =
getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let {
DocumentFileCompat.fromSingleUri(
context,
it.toUri()
)
}
val folderCover =
folderCoverFile?.takeIf { it.exists() }?.uri?.toString()
?: wallpapers.randomOrNull()
repository.updateFolder(
folder.copy(
coverUri = folderCover,
wallpapers = wallpapers
)
.asSequence()
.filterNot { new -> existingWallpapers.any { it.wallpaperUri == new.wallpaperUri } }
.mapIndexed { index, wallpaper ->
wallpaper.copy(
initialAlbumName = album.album.initialAlbumName,
order = existingWallpapers.size + 1 + index,
key = album.album.initialAlbumName.hashCode() +
folder.folderUri.hashCode() +
wallpaper.wallpaperUri.hashCode()
)
}.toList()
val combinedWallpapers = existingWallpapers + newWallpapers
folder.copy(
coverUri = combinedWallpapers.firstOrNull()?.wallpaperUri ?: "",
wallpapers = combinedWallpapers,
dateModified = metadata.lastModified,
folderName = metadata.filename
)
}
}
} catch (e: Exception) {
DocumentFile.fromTreeUri(context, folder.folderUri.toUri())
?.let { folderDirectory ->
if (!folderDirectory.isDirectory) {
repository.deleteFolder(folder)
} else {
val wallpapers =
getWallpaperFromFolder(folder.folderUri, context)
try {
val folderCoverFile = folder.coverUri?.let {
DocumentFileCompat.fromSingleUri(
context,
it.toUri()
)
}
val folderCover =
folderCoverFile?.takeIf { it.exists() }?.uri?.toString()
?: wallpapers.randomOrNull()
repository.updateFolder(
folder.copy(
coverUri = folderCover,
wallpapers = wallpapers
)
)
} catch (e: Exception) {
val folderCoverFile = folder.coverUri?.let {
DocumentFile.fromSingleUri(
context,
it.toUri()
)
}
val folderCover =
folderCoverFile?.takeIf { it.exists() }?.uri?.toString()
?: wallpapers.randomOrNull()
repository.updateFolder(
folder.copy(
coverUri = folderCover,
wallpapers = wallpapers
)
)
}
}
}
}
}
albumWithWallpapers = repository.getAlbumsWithWallpaperAndFolder().first()
albumWithWallpapers.forEach { album ->
// Delete empty albums
if (album.wallpapers.isEmpty() && album.folders.all { it.wallpapers.isEmpty() }) {
repository.deleteAlbum(album.album)
} else {
// Update album cover uri if null or invalid
try {
val albumCoverFile = album.album.coverUri?.toUri()
?.let { DocumentFileCompat.fromSingleUri(context, it) }
if (albumCoverFile == null || !albumCoverFile.exists()) {
val newCoverUri =
findFirstValidUri(context, album.wallpapers, album.folders)
repository.updateAlbum(album.album.copy(coverUri = newCoverUri))
}
} catch (e: Exception) {
val albumCoverFile = album.album.coverUri?.toUri()
?.let { DocumentFile.fromSingleUri(context, it) }
if (albumCoverFile == null || !albumCoverFile.exists()) {
val newCoverUri =
findFirstValidUri(context, album.wallpapers, album.folders)
repository.updateAlbum(album.album.copy(coverUri = newCoverUri))
else { folder }
}
}
}
.toList()
.awaitAll()
}
}
}
}
/**
* Retrieve albums from database into viewModel
*/
private fun refreshAlbums() {
viewModelScope.launch(Dispatchers.IO) {
repository.getAlbumsWithWallpaperAndFolder().collect { albumWithWallpapers ->
_state.update { it.copy(
albumsWithWallpapers = albumWithWallpapers
) }
val folders = validFolders.await()
val wallpapers = validWallpapers.await()
val coverUri = findFirstValidUri(context, folders, wallpapers)
repository.upsertAlbumWithWallpaperAndFolder(
album.copy(
album = album.album.copy(coverUri = coverUri),
wallpapers = wallpapers,
folders = folders
)
)
}
}
}
@@ -1,11 +1,14 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
@@ -21,9 +24,11 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.skydoves.landscapist.ImageOptions
@@ -39,7 +44,9 @@ fun AlbumItem(
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val showCoverUri by remember { mutableStateOf(album.coverUri != null && isValidUri(context, album.coverUri)) }
val showCoverUri by remember(album.coverUri) {
mutableStateOf(!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri))
}
Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
@@ -48,35 +55,45 @@ fun AlbumItem(
onClick = onAlbumViewClick
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
horizontalAlignment = Alignment.Start
) {
Box {
Box(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.border(
width = 1.dp,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.1f),
shape = RoundedCornerShape(12.dp)
)
.clip(RoundedCornerShape(12.dp)),
contentAlignment = Alignment.Center
) {
if (showCoverUri) {
GlideImage(
imageModel = { album.coverUri },
imageModel = {
album.coverUri?.decompress("content://com.android.externalstorage.documents/")?.toUri()
},
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(300, 300),
),
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
modifier = Modifier.fillMaxSize()
)
}
}
Spacer(modifier = Modifier.padding(6.dp))
Spacer(modifier = Modifier.height(12.dp))
Text(
text = album.displayedAlbumName,
modifier = Modifier
.padding(horizontal = 24.dp)
.align(Alignment.Start),
fontSize = 16.sp,
style = MaterialTheme.typography.titleSmall
style = MaterialTheme.typography.titleSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.padding(8.dp))
}
}
}
@@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.CircleShape
@@ -18,6 +19,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.rounded.Block
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
@@ -42,6 +44,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.skydoves.landscapist.ImageOptions
@@ -56,31 +59,30 @@ fun FolderItem(
folder: Folder,
itemSelected: Boolean,
selectionMode: Boolean,
onActivateSelectionMode: (Boolean) -> Unit,
onItemSelection: () -> Unit,
onFolderViewClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val haptics = LocalHapticFeedback.current
val transition = updateTransition(itemSelected, label = "")
val transition = updateTransition(itemSelected, label = "FolderSelectionTransition")
val iconSelectionColor = MaterialTheme.colorScheme.surfaceColorAtElevation(10.dp)
val paddingTransition by transition.animateDp(label = "") { selected ->
if (selected) 5.dp else 0.dp
val paddingTransition by transition.animateDp(label = "FolderPaddingTransition") { selected ->
if (selected) 4.dp else 0.dp
}
val roundedCornerShapeTransition by transition.animateDp(label = "") { selected ->
val roundedCornerShapeTransition by transition.animateDp(label = "FolderRoundedCornerTransition") { selected ->
if (selected) 24.dp else 16.dp
}
val showCoverUri by remember { mutableStateOf(folder.coverUri != null && isValidUri(context, folder.coverUri)) }
val showCoverUri by remember(folder.coverUri) { mutableStateOf(!folder.coverUri.isNullOrEmpty() && isValidUri(context, folder.coverUri)) }
Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
shape = RoundedCornerShape(roundedCornerShapeTransition),
modifier = modifier
.fillMaxSize()
.padding(paddingTransition)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.combinedClickable(
onClick = {
if (!selectionMode) {
@@ -92,50 +94,72 @@ fun FolderItem(
onLongClick = {
if (!selectionMode) {
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
onActivateSelectionMode(true)
onItemSelection()
}
}
),
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
Box (
modifier = Modifier.fillMaxHeight(0.8f)
Box(
modifier = Modifier
.fillMaxHeight(0.8f)
.fillMaxWidth()
.border(
width = 1.dp,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.1f),
shape = RoundedCornerShape(12.dp)
)
.clip(RoundedCornerShape(12.dp))
) {
if (showCoverUri) {
GlideImage(
imageModel = { folder.coverUri?.toUri() },
imageModel = { folder.coverUri?.decompress("content://com.android.externalstorage.documents/")?.toUri() },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(300, 300),
),
modifier = Modifier
.fillMaxSize()
.clip(RoundedCornerShape(16.dp))
modifier = Modifier.fillMaxSize()
)
} else {
Box(modifier = Modifier.fillMaxSize()) {
Icon(
imageVector = Icons.Rounded.Block,
contentDescription = stringResource(R.string.image_is_not_selected),
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
)
}
}
if (selectionMode) {
if (itemSelected) {
Icon(
imageVector = Icons.Default.CheckCircle,
contentDescription = stringResource(R.string.image_is_selected),
modifier = Modifier
.padding(9.dp)
.border(2.dp, iconSelectionColor, CircleShape)
.clip(CircleShape)
.background(iconSelectionColor)
)
} else {
Icon(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.image_is_not_selected),
tint = Color.White.copy(alpha = 0.7f),
modifier = Modifier.padding(6.dp)
)
Box(modifier = Modifier.fillMaxSize()) {
if (itemSelected) {
Icon(
imageVector = Icons.Default.CheckCircle,
contentDescription = stringResource(R.string.image_is_selected),
modifier = Modifier
.align(Alignment.TopStart)
.padding(9.dp)
.border(2.dp, iconSelectionColor, CircleShape)
.clip(CircleShape)
.background(iconSelectionColor)
)
} else {
Icon(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.image_is_not_selected),
tint = Color.White.copy(alpha = 0.7f),
modifier = Modifier
.align(Alignment.TopStart)
.padding(6.dp)
)
}
}
}
}
@@ -143,7 +167,6 @@ fun FolderItem(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(horizontal = 16.dp)
.align(Alignment.Start)
.fillMaxHeight()
.wrapContentHeight(Alignment.CenterVertically),
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
import android.content.Context
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.ExperimentalFoundationApi
@@ -21,7 +20,7 @@ import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.remember // Added
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -34,6 +33,8 @@ import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.isValidUri
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -48,61 +49,57 @@ fun WallpaperItem(
selectionMode: Boolean,
modifier: Modifier = Modifier,
allowHapticFeedback: Boolean = true,
onActivateSelectionMode: (Boolean) -> Unit,
onItemSelection: () -> Unit,
onWallpaperViewClick: () -> Unit,
) {
val context = LocalContext.current
val haptics = LocalHapticFeedback.current
val transition = updateTransition(itemSelected, label = "")
val paddingTransition by transition.animateDp(label = "") { selected ->
val showUri by remember(wallpaperUri) { mutableStateOf(isValidUri(context, wallpaperUri)) }
val decompressedUri by remember(wallpaperUri) {
mutableStateOf(wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri())
}
val imageOptions = remember {
ImageOptions(
requestSize = IntSize(200, 200),
alignment = Alignment.Center,
)
}
val transition = updateTransition(itemSelected, label = "WallpaperItemSelection")
val paddingTransition by transition.animateDp(label = "padding") { selected ->
if (selected) 5.dp else 0.dp
}
val roundedCornerShapeTransition by transition.animateDp(label = "") { selected ->
val roundedCornerShapeTransition by transition.animateDp(label = "roundedCornerShape") { selected ->
if (selected) 24.dp else 16.dp
}
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
}
true
} catch (e: Exception) { false }
}
val showUri by remember { mutableStateOf(isValidUri(context, wallpaperUri)) }
Box(
modifier = modifier
.padding(paddingTransition)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.combinedClickable(
onClick = {
if (!selectionMode) {
onWallpaperViewClick()
} else {
onItemSelection()
.padding(paddingTransition)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.combinedClickable(
onClick = {
if (!selectionMode) {
onWallpaperViewClick()
} else {
onItemSelection()
}
},
onLongClick = {
if (!selectionMode) {
if (allowHapticFeedback) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
onItemSelection()
}
}
},
onLongClick = {
if (!selectionMode) {
if (allowHapticFeedback) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
onActivateSelectionMode(true)
onItemSelection()
}
}
)
)
) {
if (showUri) {
GlideImage(
imageModel = { wallpaperUri },
imageOptions = ImageOptions(
requestSize = IntSize(200, 200),
alignment = Alignment.Center,
),
imageModel = { decompressedUri },
imageOptions = imageOptions,
modifier = Modifier
.fillMaxSize()
.clip(RoundedCornerShape(roundedCornerShapeTransition))
@@ -114,18 +111,22 @@ fun WallpaperItem(
Icon(
imageVector = Icons.Default.CheckCircle,
contentDescription = stringResource(R.string.image_is_selected),
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier
.padding(9.dp)
.clip(CircleShape)
.background(bgColor)
.border(2.dp, bgColor, CircleShape)
.align(Alignment.TopEnd)
)
} else {
Icon(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.image_is_not_selected),
tint = Color.White.copy(alpha = 0.7f),
modifier = Modifier.padding(6.dp)
modifier = Modifier
.padding(6.dp)
.align(Alignment.TopEnd)
)
}
}
@@ -0,0 +1,354 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.compress
import com.anthonyla.paperize.core.getFolderMetadata
import com.anthonyla.paperize.core.getImageMetadata
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.SelectionState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.collections.plus
@HiltViewModel
class AlbumScreenViewModel @Inject constructor(
application: Application,
private val repository: AlbumRepository,
) : AndroidViewModel(application) {
private val context: Context
get() = getApplication<Application>().applicationContext
private val _state = MutableStateFlow<AlbumViewState>(AlbumViewState())
val state = combine(
loadAlbumsFlow(),
_state
) { albums: List<AlbumWithWallpaperAndFolder>, currentState: AlbumViewState ->
currentState.copy(albums = albums)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = AlbumViewState()
)
private fun loadAlbumsFlow() = repository.getAlbumsWithWallpaperAndFolder()
init {
viewModelScope.launch {
state.collect { newState -> _state.value = newState }
}
}
fun onEvent(event: AlbumViewEvent) {
when (event) {
is AlbumViewEvent.LoadAlbum -> {
viewModelScope.launch {
_state.update {
it.copy(initialAlbumName = event.initialAlbumName)
}
}
}
is AlbumViewEvent.AddWallpapers -> {
viewModelScope.launch {
if (event.wallpaperUris.isEmpty()) { return@launch }
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
val existingUris = album.wallpapers.map { it.wallpaperUri }
val newUris = event.wallpaperUris.filter { it !in existingUris }
if (newUris.isEmpty()) { return@launch }
val wallpapers = newUris.mapIndexed { index, uri ->
val metadata = getImageMetadata(context, uri)
Wallpaper(
initialAlbumName = _state.value.initialAlbumName,
wallpaperUri = uri.compress("content://com.android.externalstorage.documents/"),
fileName = metadata.filename,
dateModified = metadata.lastModified,
order = if (album.wallpapers.isEmpty()) 0 else album.wallpapers.size + index,
key = _state.value.initialAlbumName.hashCode() + uri.hashCode()
)
}
var totalWallpapers = album.wallpapers.size + wallpapers.size
val folders = album.folders.map { folder ->
val updatedWallpapers = folder.wallpapers.mapIndexed { index, wallpaper ->
wallpaper.copy(
order = index + totalWallpapers
)
}
totalWallpapers += folder.wallpapers.size
folder.copy(
wallpapers = updatedWallpapers
)
}
val albumWithWallpaperAndFolder = album.copy(
wallpapers = album.wallpapers + wallpapers,
folders = folders
)
repository.upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder)
_state.update {
it.copy(
isEmpty = false,
selectionState = SelectionState(),
isLoading = false
)
}
}
}
is AlbumViewEvent.AddFolder -> {
viewModelScope.launch {
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null || album.folders.any { it.folderUri == event.directoryUri }) { return@launch }
_state.update { it.copy(isLoading = true) }
val wallpapers = getWallpaperFromFolder(event.directoryUri, context).mapIndexed { index, wallpaper ->
wallpaper.copy(
initialAlbumName = _state.value.initialAlbumName,
key = _state.value.initialAlbumName.hashCode() + event.directoryUri.hashCode() + wallpaper.wallpaperUri.hashCode(),
order = index + album.wallpapers.size + album.folders.sumOf { it.wallpapers.size }
)
}
val metadata = getFolderMetadata(event.directoryUri, context)
val folder = Folder(
initialAlbumName = _state.value.initialAlbumName,
folderUri = event.directoryUri,
folderName = metadata.filename,
coverUri = wallpapers.map { it.wallpaperUri }.firstOrNull() ?: "",
dateModified = metadata.lastModified,
wallpapers = wallpapers,
order = album.folders.size,
key = _state.value.initialAlbumName.hashCode() + event.directoryUri.hashCode()
)
repository.upsertFolder(folder)
_state.update {
it.copy(
isEmpty = false,
selectionState = SelectionState(),
isLoading = false
)
}
}
}
is AlbumViewEvent.ChangeAlbumName -> {
viewModelScope.launch {
if (!_state.value.albums.any { it.album.displayedAlbumName == event.displayName }) {
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
repository.updateAlbum(
album.album.copy(displayedAlbumName = event.displayName)
)
}
}
}
is AlbumViewEvent.SelectWallpaper -> {
viewModelScope.launch {
if (!_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
_state.update {
val newSelectedWallpapers = it.selectionState.selectedWallpapers.plus(event.wallpaperUri)
it.copy(
selectionState = it.selectionState.copy(
selectedWallpapers = newSelectedWallpapers,
selectedCount = newSelectedWallpapers.size + it.selectionState.selectedFolders.size,
allSelected = it.selectionState.selectedFolders.size + newSelectedWallpapers.size >=
album.folders.size + album.wallpapers.size
)
)
}
}
}
}
is AlbumViewEvent.SelectFolder -> {
viewModelScope.launch {
if (!_state.value.selectionState.selectedFolders.contains(event.directoryUri)) {
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
_state.update {
val newSelectedFolders = it.selectionState.selectedFolders.plus(event.directoryUri)
it.copy(
selectionState = it.selectionState.copy(
selectedFolders = newSelectedFolders,
selectedCount = newSelectedFolders.size + it.selectionState.selectedWallpapers.size,
allSelected = newSelectedFolders.size + it.selectionState.selectedWallpapers.size >=
album.folders.size + album.wallpapers.size
)
)
}
}
}
}
is AlbumViewEvent.DeselectFolder -> {
viewModelScope.launch {
if (_state.value.selectionState.selectedFolders.contains(event.directoryUri)) {
_state.update {
it.copy(
selectionState = it.selectionState.copy(
selectedFolders = it.selectionState.selectedFolders.minus(event.directoryUri),
selectedCount = it.selectionState.selectedCount - 1,
allSelected = false
)
)
}
}
}
}
is AlbumViewEvent.DeselectWallpaper -> {
viewModelScope.launch {
if (_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
_state.update {
it.copy(
selectionState = it.selectionState.copy(
selectedWallpapers = it.selectionState.selectedWallpapers.minus(event.wallpaperUri),
selectedCount = it.selectionState.selectedCount - 1,
allSelected = false
)
)
}
}
}
}
is AlbumViewEvent.DeleteSelected -> {
viewModelScope.launch {
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
val selectedFolders = _state.value.selectionState.selectedFolders
val selectedWallpapers = _state.value.selectionState.selectedWallpapers
val foldersToDelete = album.folders.filter { selectedFolders.contains(it.folderUri) }
val wallpapersToDelete = album.wallpapers.filter { selectedWallpapers.contains(it.wallpaperUri) }
if (foldersToDelete.size + wallpapersToDelete.size == album.folders.size + album.wallpapers.size) {
repository.cascadeDeleteAlbum(album.album)
}
else {
repository.deleteFolderList(foldersToDelete)
repository.deleteWallpaperList(wallpapersToDelete)
if (album.album.coverUri in (foldersToDelete.map { it.folderUri } + wallpapersToDelete.map { it.wallpaperUri })) {
val newCover = album.folders.minus(foldersToDelete.toSet()).firstOrNull()?.coverUri ?: album.wallpapers.minus(wallpapersToDelete.toSet()
).firstOrNull()?.wallpaperUri ?: ""
repository.updateAlbum(album.album.copy(coverUri = newCover))
}
val remainingWallpapers = album.wallpapers.minus(wallpapersToDelete.toSet())
val newWallpapers = remainingWallpapers.sortedBy { it.order }.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
val remainingFolders = album.folders.minus(foldersToDelete.toSet())
var totalWallpaper = newWallpapers.size
val newFolders = remainingFolders.sortedBy { it.order }.mapIndexed { folderIndex, folder ->
val updatedWallpapers = folder.wallpapers.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index + totalWallpaper)
}
totalWallpaper += folder.wallpapers.size
folder.copy(
wallpapers = updatedWallpapers,
order = folderIndex
)
}
repository.upsertAlbumWithWallpaperAndFolder(
album.copy(
folders = newFolders,
wallpapers = newWallpapers
)
)
}
_state.update {
it.copy(
selectionState = SelectionState(),
isLoading = false
)
}
}
}
is AlbumViewEvent.Reset -> {
viewModelScope.launch {
_state.update { AlbumViewState() }
}
}
is AlbumViewEvent.SelectAll -> {
viewModelScope.launch {
if (!_state.value.selectionState.allSelected) {
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
_state.update {
it.copy(
selectionState = SelectionState(
selectedFolders = album.folders.map { it.folderUri },
selectedWallpapers = album.wallpapers.map { it.wallpaperUri },
allSelected = true,
selectedCount = album.folders.size + album.wallpapers.size
)
)
}
}
}
}
is AlbumViewEvent.DeselectAll -> {
viewModelScope.launch {
_state.update { it.copy(selectionState = SelectionState()) }
}
}
is AlbumViewEvent.SetLoading -> {
viewModelScope.launch {
_state.update { it.copy(isLoading = event.isLoading) }
}
}
is AlbumViewEvent.LoadFoldersAndWallpapers -> {
viewModelScope.launch {
_state.update { state ->
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
repository.upsertAlbumWithWallpaperAndFolder(
AlbumWithWallpaperAndFolder(
album = album.album.copy(
coverUri = event.folders.firstOrNull()?.coverUri ?: event.wallpapers.firstOrNull()?.wallpaperUri ?: ""
),
folders = event.folders.map {
it.copy(coverUri = it.wallpapers.firstOrNull()?.wallpaperUri ?: "")
},
wallpapers = event.wallpapers
)
)
state.copy(
selectionState = SelectionState(),
isLoading = false
)
}
}
}
is AlbumViewEvent.DeleteAlbum -> {
viewModelScope.launch {
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
repository.cascadeDeleteAlbum(album.album)
_state.update { AlbumViewState() }
}
}
}
}
}
@@ -1,41 +1,45 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumEvent
sealed class AlbumViewEvent {
data object ClearState: AlbumViewEvent()
data class SelectAll(
val albumsWithWallpaper: AlbumWithWallpaperAndFolder
): AlbumViewEvent()
data object Reset: AlbumViewEvent()
data object SelectAll: AlbumViewEvent()
data object DeselectAll: AlbumViewEvent()
data class DeleteSelected(
val albumsWithWallpaper: AlbumWithWallpaperAndFolder
): AlbumViewEvent()
data object DeleteSelected: AlbumViewEvent()
data object DeleteAlbum: AlbumViewEvent()
data class LoadAlbum(
val initialAlbumName: String
): AlbumViewEvent()
data class AddWallpapers(
val album: AlbumWithWallpaperAndFolder,
val wallpaperUris: List<String>
): AlbumViewEvent()
data class AddFolder(
val album: AlbumWithWallpaperAndFolder,
val directoryUri: String
): AlbumViewEvent()
data class SelectWallpaper(
val wallpaperUri: String
): AlbumViewEvent()
data class SelectFolder(
val directoryUri: String
): AlbumViewEvent()
data class RemoveFolderFromSelection(
data class DeselectFolder(
val directoryUri: String
): AlbumViewEvent()
data class RemoveWallpaperFromSelection(
data class DeselectWallpaper(
val wallpaperUri: String
): AlbumViewEvent()
data class SetSize(
val size: Int
data class ChangeAlbumName(
val displayName: String
): AlbumViewEvent()
data class SetLoading(
val isLoading: Boolean
): AlbumViewEvent()
data class LoadFoldersAndWallpapers(
val folders: List<Folder>,
val wallpapers: List<Wallpaper>
): AlbumViewEvent()
}
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
@@ -9,63 +10,123 @@ import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumAnimatedFab
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.FolderItem
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
import com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.components.AlbumViewTopBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import my.nanihadesuka.compose.LazyVerticalGridScrollbar
import my.nanihadesuka.compose.ScrollbarSettings
@Composable
fun AlbumViewScreen(
albumViewScreenViewModel: AlbumViewScreenViewModel = hiltViewModel(),
album: AlbumWithWallpaperAndFolder,
albumScreenViewModel: AlbumScreenViewModel,
animate: Boolean,
onBackClick: () -> Unit,
onShowWallpaperView: (String) -> Unit,
onShowFolderView: (String?, List<String>) -> Unit,
onShowWallpaperView: (String, String) -> Unit,
onShowFolderView: (Folder) -> Unit,
onDeleteAlbum: () -> Unit,
onAlbumNameChange: (String, AlbumWithWallpaperAndFolder) -> Unit,
onSelectionDeleted: () -> Unit,
onSortClick: (List<Folder>, List<Wallpaper>) -> Unit,
) {
albumViewScreenViewModel.onEvent(AlbumViewEvent.SetSize(album.wallpapers.size + album.folders.size)) // For selectedAll state
val lazyListState = rememberLazyGridState()
val albumState = albumViewScreenViewModel.state.collectAsStateWithLifecycle()
var selectionMode by rememberSaveable { mutableStateOf(false) }
val context = LocalContext.current
val scope = rememberCoroutineScope()
val lazyListState = rememberLazyGridState()
val albumViewState by albumScreenViewModel.state.collectAsStateWithLifecycle()
val album = remember(albumViewState.albums, albumViewState.initialAlbumName) {
albumViewState.albums.find { it.album.initialAlbumName == albumViewState.initialAlbumName }
}
val colorScheme = MaterialTheme.colorScheme
val scrollbarSettings = remember {
ScrollbarSettings.Default.copy(
thumbUnselectedColor = colorScheme.primary,
thumbSelectedColor = colorScheme.primary,
thumbShape = RoundedCornerShape(16.dp),
scrollbarPadding = 1.dp,
)
}
val commonItemModifier = remember {
Modifier
.fillMaxWidth()
.aspectRatio(9f / 16f)
}
BackHandler(
enabled = albumViewState.selectionState.selectedCount > 0,
onBack = remember(albumViewState.isLoading, albumScreenViewModel) {
{
if (!albumViewState.isLoading) {
albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
}
}
}
)
/** Image picker **/
val imagePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenMultipleDocuments(),
onResult = { uris: List<Uri> ->
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
val uriList = uris.mapNotNull { uri ->
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
if (persistedUriPermissions.any { it.uri == uri }) uri.toString() else null
}
if (uriList.isNotEmpty()) {
albumViewScreenViewModel.onEvent(AlbumViewEvent.AddWallpapers(album, uriList))
onResult = remember(albumScreenViewModel, scope, context) {
{ uris: List<Uri> ->
val selectionLimit = 500
if (uris.size > selectionLimit) {
Toast.makeText(
context,
"Please select fewer than $selectionLimit images at a time. For bulk imports, use the 'Add Folder' option.",
Toast.LENGTH_LONG
).show()
}
else if (uris.isNotEmpty()) {
scope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {
albumScreenViewModel.onEvent(AlbumViewEvent.SetLoading(true))
}
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
val uriList = uris.mapNotNull { uri ->
try {
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
if (persistedUriPermissions.any { it.uri == uri }) uri.toString() else null
} catch (e: Exception) {
android.util.Log.e("AlbumViewScreen", "Failed to take persistable URI permission for image: ${e.message}")
null
}
}
withContext(Dispatchers.Main) {
if (uriList.isNotEmpty()) {
albumScreenViewModel.onEvent(AlbumViewEvent.AddWallpapers(uriList))
}
albumScreenViewModel.onEvent(AlbumViewEvent.SetLoading(false))
}
}
}
}
}
)
@@ -73,194 +134,260 @@ fun AlbumViewScreen(
/** Folder picker **/
val folderPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocumentTree(),
onResult = { uri: Uri? ->
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
if (uri != null) {
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
if (persistedUriPermissions.any { it.uri == uri }) {
albumViewScreenViewModel.onEvent(AlbumViewEvent.AddFolder(album, uri.toString()))
onResult = remember(albumScreenViewModel, scope, context) {
{ uri: Uri? ->
scope.launch(Dispatchers.IO) {
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
if (uri != null) {
try {
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
if (persistedUriPermissions.any { it.uri == uri }) {
withContext(Dispatchers.Main) {
albumScreenViewModel.onEvent(AlbumViewEvent.AddFolder(uri.toString()))
}
}
} catch (e: Exception) {
android.util.Log.e("AlbumViewScreen", "Failed to take persistable URI permission for folder: ${e.message}")
}
}
}
}
}
)
BackHandler(
enabled = selectionMode,
onBack = {
albumViewScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
selectionMode = false
}
)
Scaffold(
topBar = {
AlbumViewTopBar(
title = album.album.displayedAlbumName,
selectionMode = selectionMode,
albumState = albumViewScreenViewModel.state,
onBackClick = {
albumViewScreenViewModel.onEvent(AlbumViewEvent.ClearState)
onBackClick()
},
onDeleteAlbum = onDeleteAlbum,
onTitleChange = { onAlbumNameChange(it, album) },
onSelectAllClick = {
if (!albumState.value.allSelected) albumViewScreenViewModel.onEvent(AlbumViewEvent.SelectAll(album))
else albumViewScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
},
onDeleteSelected = {
selectionMode = false
albumViewScreenViewModel.onEvent(AlbumViewEvent.DeleteSelected(album))
albumViewScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
onSelectionDeleted()
val onSelectAllClick = remember(
albumViewState.isLoading,
albumViewState.selectionState.allSelected,
albumScreenViewModel
) {
{
if (!albumViewState.isLoading) {
if (!albumViewState.selectionState.allSelected) albumScreenViewModel.onEvent(
AlbumViewEvent.SelectAll
)
else albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
}
}
}
val onBackClickTopBar = remember(albumScreenViewModel, onBackClick) {
{
albumScreenViewModel.onEvent(AlbumViewEvent.Reset)
onBackClick()
}
}
val onDeleteSelected = remember(
albumViewState.isLoading,
album,
albumViewState.selectionState.selectedCount,
albumScreenViewModel,
onBackClick
) {
{
if (!albumViewState.isLoading) {
if (album != null) {
if (album.folders.size + album.wallpapers.size == albumViewState.selectionState.selectedCount) {
onBackClick()
}
albumScreenViewModel.onEvent(AlbumViewEvent.DeleteSelected)
}
}
}
}
val onDeleteAlbumTopBar = remember(
albumViewState.isLoading,
album,
albumScreenViewModel,
onDeleteAlbum
) {
{
if (!albumViewState.isLoading && album != null) {
albumScreenViewModel.onEvent(AlbumViewEvent.DeleteAlbum)
onDeleteAlbum()
}
}
}
val onTitleChangeTopBar: (String) -> Unit = remember(
albumViewState.isLoading,
album,
albumScreenViewModel
) {
{ newTitle ->
if (!albumViewState.isLoading && album != null) {
albumScreenViewModel.onEvent(AlbumViewEvent.ChangeAlbumName(newTitle))
}
}
}
val onSortClickTopBar = remember(
albumViewState.isLoading,
album,
onSortClick
) {
{
if (!albumViewState.isLoading && album != null) {
onSortClick(album.folders, album.wallpapers)
}
}
}
AlbumViewTopBar(
title = album?.album?.displayedAlbumName ?: "",
allSelected = albumViewState.selectionState.allSelected,
selectedCount = albumViewState.selectionState.selectedCount,
selectionMode = albumViewState.selectionState.selectedCount > 0,
isLoad = albumViewState.isLoading,
onSelectAllClick = onSelectAllClick,
onBackClick = onBackClickTopBar,
onDeleteSelected = onDeleteSelected,
onDeleteAlbum = onDeleteAlbumTopBar,
onTitleChange = onTitleChangeTopBar,
onSortClick = onSortClickTopBar
)
},
floatingActionButton = {
AddAlbumAnimatedFab(
onImageClick = {
selectionMode = false
val onImageClickFab = remember(albumScreenViewModel, imagePickerLauncher) {
{
albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
imagePickerLauncher.launch(arrayOf("image/*"))
},
onFolderClick = {
selectionMode = false
}
}
val onFolderClickFab = remember(albumScreenViewModel, folderPickerLauncher) {
{
albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
folderPickerLauncher.launch(null)
}
}
AddAlbumAnimatedFab(
isLoading = albumViewState.isLoading,
animate = animate,
onImageClick = onImageClickFab,
onFolderClick = onFolderClickFab
)
},
content = { it ->
LazyVerticalGridScrollbar(
state = lazyListState,
settings = ScrollbarSettings.Default.copy(
thumbUnselectedColor = MaterialTheme.colorScheme.primary,
thumbSelectedColor = MaterialTheme.colorScheme.primary,
thumbShape = RoundedCornerShape(16.dp),
scrollbarPadding = 1.dp,
),
modifier = Modifier
.fillMaxSize()
.padding(it),
) {
LazyVerticalGrid(
bottomBar = {
if (albumViewState.isLoading) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
},
content = { paddingValues ->
if (album != null) {
LazyVerticalGridScrollbar(
state = lazyListState,
modifier = Modifier.fillMaxSize(),
columns = GridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp, 4.dp),
horizontalArrangement = Arrangement.Start,
settings = scrollbarSettings,
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
) {
items(count = album.folders.size, key = { index -> album.folders[index].folderUri }) { index ->
if (animate) {
FolderItem(
folder = album.folders[index],
itemSelected = albumState.value.selectedFolders.contains(album.folders[index].folderUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
albumViewScreenViewModel.onEvent(
if (!albumState.value.selectedFolders.contains(album.folders[index].folderUri))
AlbumViewEvent.SelectFolder(album.folders[index].folderUri)
else {
AlbumViewEvent.RemoveFolderFromSelection(album.folders[index].folderUri)
}
)
},
onFolderViewClick = {
if (album.folders[index].wallpapers.isNotEmpty()) onShowFolderView(album.folders[index].folderName, album.folders[index].wallpapers)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
),
)
)
}
else {
FolderItem(
folder = album.folders[index],
itemSelected = albumState.value.selectedFolders.contains(album.folders[index].folderUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
albumViewScreenViewModel.onEvent(
if (!albumState.value.selectedFolders.contains(album.folders[index].folderUri))
AlbumViewEvent.SelectFolder(album.folders[index].folderUri)
else {
AlbumViewEvent.RemoveFolderFromSelection(album.folders[index].folderUri)
}
)
},
onFolderViewClick = {
if (album.folders[index].wallpapers.isNotEmpty()) onShowFolderView(album.folders[index].folderName, album.folders[index].wallpapers)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
}
}
items(count = album.wallpapers.size, key = { index -> album.wallpapers[index].wallpaperUri }) { index ->
if (animate) {
WallpaperItem(
wallpaperUri = album.wallpapers[index].wallpaperUri,
itemSelected = albumState.value.selectedWallpapers.contains(album.wallpapers[index].wallpaperUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
albumViewScreenViewModel.onEvent(
if (!albumState.value.selectedWallpapers.contains(album.wallpapers[index].wallpaperUri))
AlbumViewEvent.SelectWallpaper(album.wallpapers[index].wallpaperUri)
else {
AlbumViewEvent.RemoveWallpaperFromSelection(album.wallpapers[index].wallpaperUri)
}
)
},
onWallpaperViewClick = {
onShowWallpaperView(album.wallpapers[index].wallpaperUri)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
LazyVerticalGrid(
state = lazyListState,
modifier = Modifier.fillMaxSize(),
columns = GridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
items(
items = album.folders,
key = { folder -> folder.folderUri }
) { folder ->
val isSelected = albumViewState.selectionState.selectedFolders.contains(folder.folderUri)
val onFolderItemSelection = remember(
folder.folderUri,
albumViewState.isLoading,
albumViewState.selectionState.selectedFolders
) {
{
if (!albumViewState.isLoading) {
albumScreenViewModel.onEvent(
if (!isSelected) AlbumViewEvent.SelectFolder(folder.folderUri)
else AlbumViewEvent.DeselectFolder(folder.folderUri)
)
}
}
}
val onFolderViewClickItem = remember(folder, albumViewState.isLoading, onShowFolderView) {
{
if (!albumViewState.isLoading) {
onShowFolderView(folder)
}
}
}
FolderItem(
folder = folder,
itemSelected = isSelected,
selectionMode = albumViewState.selectionState.selectedCount > 0,
onItemSelection = onFolderItemSelection,
onFolderViewClick = onFolderViewClickItem,
modifier = commonItemModifier
.then(
if (animate) Modifier.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
)
) else Modifier
)
)
}
else {
items(
items = album.wallpapers,
key = { wallpaper -> wallpaper.wallpaperUri }
) { wallpaper ->
val isSelected = albumViewState.selectionState.selectedWallpapers.contains(wallpaper.wallpaperUri)
val onWallpaperItemSelection = remember(
wallpaper.wallpaperUri,
albumViewState.isLoading,
albumViewState.selectionState.selectedWallpapers
) {
{
if (!albumViewState.isLoading) {
albumScreenViewModel.onEvent(
if (!isSelected) AlbumViewEvent.SelectWallpaper(wallpaper.wallpaperUri)
else AlbumViewEvent.DeselectWallpaper(wallpaper.wallpaperUri)
)
}
}
}
val onWallpaperViewClickItem = remember(wallpaper, albumViewState.isLoading, onShowWallpaperView) {
{
if (!albumViewState.isLoading)
onShowWallpaperView(wallpaper.wallpaperUri, wallpaper.fileName)
}
}
WallpaperItem(
wallpaperUri = album.wallpapers[index].wallpaperUri,
itemSelected = albumState.value.selectedWallpapers.contains(album.wallpapers[index].wallpaperUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
albumViewScreenViewModel.onEvent(
if (!albumState.value.selectedWallpapers.contains(album.wallpapers[index].wallpaperUri))
AlbumViewEvent.SelectWallpaper(album.wallpapers[index].wallpaperUri)
else {
AlbumViewEvent.RemoveWallpaperFromSelection(album.wallpapers[index].wallpaperUri)
}
wallpaperUri = wallpaper.wallpaperUri,
itemSelected = isSelected,
selectionMode = albumViewState.selectionState.selectedCount > 0,
onItemSelection = onWallpaperItemSelection,
onWallpaperViewClick = onWallpaperViewClickItem,
modifier = commonItemModifier
.then(
if (animate) Modifier.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
)
) else Modifier
)
},
onWallpaperViewClick = {
onShowWallpaperView(album.wallpapers[index].wallpaperUri)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
}
}
}
}
}
)
@@ -1,219 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.getFolderNameFromUri
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AlbumViewScreenViewModel @Inject constructor(
application: Application,
private val repository: AlbumRepository,
) : AndroidViewModel(application) {
private val context: Context
get() = getApplication<Application>().applicationContext
private val _state = MutableStateFlow(AlbumViewState())
val state = _state.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000), AlbumViewState()
)
fun onEvent(event: AlbumViewEvent) {
when (event) {
is AlbumViewEvent.DeleteSelected -> {
viewModelScope.launch {
event.albumsWithWallpaper.let { album ->
val folders = album.folders.filter { _state.value.selectedFolders.contains(it.folderUri)}
val wallpapers = album.wallpapers.filter { _state.value.selectedWallpapers.contains(it.wallpaperUri)}
val containsCoverUri = wallpapers.any { it.wallpaperUri == album.album.coverUri }
repository.deleteFolderList(folders)
repository.deleteWallpaperList(wallpapers)
if (containsCoverUri) {
repository.updateAlbum(album.album.copy(coverUri = null))
}
}
}
}
is AlbumViewEvent.SelectAll -> {
viewModelScope.launch {
event.albumsWithWallpaper.let { album ->
if (!_state.value.allSelected) {
_state.update { it ->
it.copy(
selectedFolders = album.folders.map { it.folderUri },
selectedWallpapers = album.wallpapers.map { it.wallpaperUri },
selectedCount = album.folders.size + album.wallpapers.size,
maxSize = album.folders.size + album.wallpapers.size,
allSelected = true
)
}
}
}
}
}
is AlbumViewEvent.DeselectAll -> {
viewModelScope.launch {
_state.update {
it.copy(
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
selectedCount = 0,
allSelected = false
)
}
}
}
is AlbumViewEvent.SelectFolder -> {
viewModelScope.launch {
if (!_state.value.selectedFolders.any { it == event.directoryUri }) {
_state.update {
val folders = it.selectedFolders.plus(event.directoryUri)
it.copy(
selectedFolders = folders,
selectedCount = it.selectedCount + 1,
allSelected = folders.size + it.selectedWallpapers.size >= it.maxSize
)
}
}
}
}
is AlbumViewEvent.SelectWallpaper -> {
viewModelScope.launch {
if (!_state.value.selectedWallpapers.any { it == event.wallpaperUri }) {
_state.update {
val wallpapers = it.selectedWallpapers.plus(event.wallpaperUri)
it.copy(
selectedWallpapers = it.selectedWallpapers.plus(event.wallpaperUri),
selectedCount = it.selectedCount + 1,
allSelected = it.selectedFolders.size + wallpapers.size >= it.maxSize
)
}
}
}
}
is AlbumViewEvent.RemoveFolderFromSelection -> {
viewModelScope.launch {
if (_state.value.selectedFolders.find { it == event.directoryUri } != null) {
_state.update {
val folders = it.selectedFolders.minus(event.directoryUri)
it.copy(
selectedFolders = folders,
selectedCount = it.selectedCount - 1,
allSelected = folders.size + it.selectedWallpapers.size >= it.maxSize
)
}
}
}
}
is AlbumViewEvent.RemoveWallpaperFromSelection -> {
viewModelScope.launch {
if (_state.value.selectedWallpapers.find { it == event.wallpaperUri } != null) {
_state.update {
val wallpapers = it.selectedWallpapers.minus(event.wallpaperUri)
it.copy(
selectedWallpapers = wallpapers,
selectedCount = it.selectedCount - 1,
allSelected = it.selectedFolders.size + wallpapers.size >= it.maxSize
)
}
}
}
}
is AlbumViewEvent.ClearState -> {
viewModelScope.launch {
_state.update {
it.copy(
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
allSelected = false,
selectedCount = 0,
maxSize = 0
)
}
}
}
is AlbumViewEvent.SetSize -> {
viewModelScope.launch {
_state.update {
it.copy(
maxSize = event.size
)
}
}
}
is AlbumViewEvent.AddWallpapers -> {
viewModelScope.launch {
val wallpaperUris = event.wallpaperUris.filterNot { it in event.album.wallpapers.map { wallpaper -> wallpaper.wallpaperUri } }
val wallpapers = wallpaperUris.map { uri ->
Wallpaper(
initialAlbumName = event.album.album.initialAlbumName,
wallpaperUri = uri,
key = uri.hashCode() + event.album.album.initialAlbumName.hashCode(),
)
}
repository.upsertWallpaperList(wallpapers)
_state.update {
it.copy(
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
allSelected = false,
selectedCount = 0,
maxSize = it.maxSize + wallpapers.size
)
}
}
}
is AlbumViewEvent.AddFolder -> {
viewModelScope.launch {
if (event.directoryUri !in event.album.folders.map { it.folderUri }) {
val wallpapers: List<String> = getWallpaperFromFolder(event.directoryUri, context)
if (wallpapers.isEmpty()) { return@launch }
val folderName = getFolderNameFromUri(event.directoryUri, context)
repository.upsertFolder(
Folder(
folderUri = event.directoryUri,
folderName = folderName,
initialAlbumName = event.album.album.initialAlbumName,
key = event.directoryUri.hashCode() + event.album.album.initialAlbumName.hashCode(),
coverUri = wallpapers.randomOrNull(),
wallpapers = wallpapers
)
)
_state.update {
it.copy(
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
allSelected = false,
selectedCount = 0,
maxSize = it.maxSize + 1
)
}
}
}
}
}
}
}
@@ -1,9 +1,11 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.SelectionState
data class AlbumViewState (
val selectedWallpapers: List<String> = emptyList(),
val selectedFolders: List<String> = emptyList(),
val allSelected: Boolean = false,
val selectedCount: Int = 0,
val maxSize: Int = 0
val albums: List<AlbumWithWallpaperAndFolder> = emptyList(),
val initialAlbumName: String = "",
val selectionState: SelectionState = SelectionState(),
val isEmpty: Boolean = true,
val isLoading: Boolean = false
)
@@ -3,6 +3,7 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
@@ -10,7 +11,9 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
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.CheckCircle
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.outlined.Delete
@@ -23,6 +26,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -47,23 +51,25 @@ import kotlinx.coroutines.flow.StateFlow
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlbumViewTopBar(
albumState: StateFlow<AlbumViewState>,
title: String,
onBackClick: () -> Unit,
allSelected: Boolean,
selectedCount: Int,
selectionMode: Boolean,
isLoad: Boolean,
onBackClick: () -> Unit,
onSortClick: () -> Unit,
onSelectAllClick: () -> Unit,
onDeleteAlbum: () -> Unit,
onDeleteSelected: () -> Unit,
onTitleChange: (String) -> Unit,
) {
val state = albumState.collectAsStateWithLifecycle()
var showDeleteAlertDialog by rememberSaveable { mutableStateOf(false) }
var showNameChangeDialog by rememberSaveable { mutableStateOf(false) }
var menuExpanded by rememberSaveable { mutableStateOf(false) }
var showSelectionDeleteDialog by rememberSaveable { mutableStateOf(false) }
TopAppBar(
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(containerColor = MaterialTheme.colorScheme.surface),
colors = topAppBarColors(containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)),
title = { if (!selectionMode) Text(title) },
navigationIcon = {
if (!selectionMode) {
@@ -75,38 +81,34 @@ fun AlbumViewTopBar(
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.home_screen),
contentDescription = stringResource(id = R.string.home_screen)
)
}
}
else {
Row (
} else {
Row(
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = onSelectAllClick
) {
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
if (state.value.allSelected) {
Icon(
imageVector = Icons.Default.CheckCircle,
contentDescription = stringResource(R.string.all_images_selected_for_deletion),
modifier = Modifier
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
IconButton(onClick = onSelectAllClick) {
Icon(
imageVector = if (allSelected) Icons.Default.CheckCircle else Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(
if (allSelected) R.string.all_images_selected_for_deletion
else R.string.select_all_images_for_deletion
),
modifier = if (allSelected) {
Modifier
.padding(4.dp)
.border(2.dp, bgColor, CircleShape)
.clip(CircleShape)
.background(bgColor)
)
} else {
Icon(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.select_all_images_for_deletion),
modifier = Modifier.padding(6.dp)
)
}
} else {
Modifier.padding(6.dp)
}
)
}
Text(stringResource(R.string.selected_count, state.value.selectedCount))
Text(stringResource(R.string.selected, selectedCount))
}
}
},
@@ -116,17 +118,32 @@ fun AlbumViewTopBar(
onDismissRequest = { showDeleteAlertDialog = false },
onConfirmation = {
showDeleteAlertDialog = false
onDeleteAlbum()
if (!isLoad) { onDeleteAlbum() }
}
)
if (showNameChangeDialog) AlbumNameDialog (
onDismissRequest = { showNameChangeDialog = false },
onConfirmation = {
showNameChangeDialog = false
onTitleChange(it)
if (!isLoad) { onTitleChange(it) }
}
)
IconButton(onClick = { menuExpanded = true }) {
Row {
Box {
IconButton(
onClick = { if (!isLoad) { onSortClick() } }
) {
Icon(
imageVector = Icons.AutoMirrored.Default.Sort,
contentDescription = stringResource(R.string.sort_items),
modifier = Modifier.padding(6.dp)
)
}
}
}
IconButton(onClick = {
if (!isLoad) { menuExpanded = true }
}) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = stringResource(R.string.more_options),
@@ -138,19 +155,24 @@ fun AlbumViewTopBar(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false },
offset = DpOffset(0.dp, 5.dp),
modifier = Modifier.padding(8.dp)
modifier = Modifier.padding(8.dp),
containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.delete_album)) },
onClick = {
showDeleteAlertDialog = true
menuExpanded = false
if (!isLoad) {
showDeleteAlertDialog = true
}
menuExpanded = false
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.change_name)) },
onClick = {
showNameChangeDialog = true
if (!isLoad) {
showNameChangeDialog = true
}
menuExpanded = false
}
)
@@ -162,14 +184,16 @@ fun AlbumViewTopBar(
onDismissRequest = { showSelectionDeleteDialog = false },
onConfirmation = {
showSelectionDeleteDialog = false
onDeleteSelected()
if (!isLoad) {
onDeleteSelected()
}
}
)
IconButton(
onClick = { showSelectionDeleteDialog = true }
) {
Icon(
imageVector = Icons.Outlined.Delete,
imageVector = if (showSelectionDeleteDialog) Icons.Filled.Delete else Icons.Outlined.Delete,
contentDescription = stringResource(R.string.select_all_images_for_deletion),
modifier = Modifier.padding(6.dp)
)
@@ -0,0 +1,11 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
sealed class FolderEvent {
data object Reset: FolderEvent()
data class LoadFolderView(
val folder: Folder? = null
): FolderEvent()
}
@@ -0,0 +1,8 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
data class FolderState(
val folder: Folder? = null,
)
@@ -2,12 +2,36 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
/**
* ViewModel for the folder view screen to hold the folder name and the list of wallpapers
*/
class FolderViewModel @Inject constructor (): ViewModel() {
var folderName = mutableStateOf<String?>(null)
var wallpapers = mutableStateOf<List<String>?>(null)
private val _state = MutableStateFlow<FolderState>(FolderState())
val state = _state.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = FolderState()
)
fun onEvent(event: FolderEvent) {
when (event) {
is FolderEvent.LoadFolderView -> {
_state.value = state.value.copy(
folder = event.folder
)
}
is FolderEvent.Reset -> {
_state.value = FolderState()
}
}
}
}
@@ -5,18 +5,22 @@ import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember // Added remember import
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
import com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen.components.FolderViewTopBar
import my.nanihadesuka.compose.LazyVerticalGridScrollbar
@@ -24,82 +28,77 @@ import my.nanihadesuka.compose.ScrollbarSettings
@Composable
fun FolderViewScreen(
folderName: String?,
wallpapers: List<String>,
folder: Folder,
onBackClick: () -> Unit,
onShowWallpaperView: (String) -> Unit,
onShowWallpaperView: (String, String) -> Unit,
animate: Boolean
) {
val lazyListState = rememberLazyGridState()
val colorScheme = MaterialTheme.colorScheme
val scrollbarSettings = remember {
ScrollbarSettings.Default.copy(
thumbUnselectedColor = colorScheme.primary,
thumbSelectedColor = colorScheme.primary,
thumbShape = RoundedCornerShape(16.dp),
scrollbarPadding = 1.dp,
)
}
val noOpItemSelection: () -> Unit = remember { { /* Do nothing */ } }
BackHandler { onBackClick() }
Scaffold(
topBar = {
FolderViewTopBar(
title = folderName ?: "",
title = folder.folderName ?: "",
onBackClick = onBackClick
)
},
content = {
content = { paddingValues ->
LazyVerticalGridScrollbar(
state = lazyListState,
settings = ScrollbarSettings.Default.copy(
thumbUnselectedColor = MaterialTheme.colorScheme.primary,
thumbSelectedColor = MaterialTheme.colorScheme.primary,
thumbShape = RoundedCornerShape(16.dp),
scrollbarPadding = 1.dp,
),
settings = scrollbarSettings,
modifier = Modifier
.fillMaxSize()
.padding(it)
.padding(paddingValues)
) {
LazyVerticalGrid(
state = lazyListState,
modifier = Modifier.fillMaxSize(),
columns = GridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp, 4.dp),
horizontalArrangement = Arrangement.Start,
contentPadding = PaddingValues(4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(count = wallpapers.size, key = { index -> wallpapers[index] }) { index ->
if (animate) {
WallpaperItem(
wallpaperUri = wallpapers[index],
itemSelected = false,
selectionMode = false,
allowHapticFeedback = false,
onActivateSelectionMode = {},
onItemSelection = {},
onWallpaperViewClick = {
onShowWallpaperView(wallpapers[index])
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
items(items = folder.wallpapers, key = { wallpaper -> wallpaper.wallpaperUri }) { wallpaper ->
val itemModifier = remember(animate) {
Modifier
.fillMaxWidth()
.aspectRatio(9f / 16f)
.then(
if (animate) Modifier.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
),
)
)
}
else {
WallpaperItem(
wallpaperUri = wallpapers[index],
itemSelected = false,
selectionMode = false,
allowHapticFeedback = false,
onActivateSelectionMode = {},
onItemSelection = {},
onWallpaperViewClick = {
onShowWallpaperView(wallpapers[index])
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
)
) else Modifier
)
}
WallpaperItem(
wallpaperUri = wallpaper.wallpaperUri,
itemSelected = false,
selectionMode = false,
allowHapticFeedback = false,
onItemSelection = noOpItemSelection,
onWallpaperViewClick = {
onShowWallpaperView(wallpaper.wallpaperUri, wallpaper.fileName)
},
modifier = itemModifier
)
}
}
}
@@ -11,6 +11,8 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
@@ -27,7 +29,7 @@ fun FolderViewTopBar(
onBackClick: () -> Unit
) {
TopAppBar(
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(containerColor = MaterialTheme.colorScheme.surface),
colors = topAppBarColors(containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)),
title = { Text(title) },
navigationIcon = {
IconButton(
@@ -4,14 +4,11 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.TimePickerState
import androidx.compose.runtime.Composable
@@ -21,76 +18,55 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumDialog
import com.anthonyla.paperize.feature.wallpaper.presentation.home_screen.components.HomeTopBar
import com.anthonyla.paperize.feature.wallpaper.presentation.home_screen.components.getTabItems
import com.anthonyla.paperize.feature.wallpaper.presentation.library_screen.LibraryScreen
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.EffectSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.ScheduleSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.ThemeSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.WallpaperSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperScreen
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
albums: List<AlbumWithWallpaperAndFolder>,
animate : Boolean,
darken: Boolean,
homeDarkenPercentage: Int,
lockDarkenPercentage: Int,
enableChanger: Boolean,
homeEnabled : Boolean,
homeInterval: Int,
lockInterval: Int,
lastSetTime: String?,
lockEnabled : Boolean,
navigateToAddWallpaperScreen: (String) -> Unit,
nextSetTime: String?,
homeSelectedAlbum: AlbumWithWallpaperAndFolder?,
lockSelectedAlbum: AlbumWithWallpaperAndFolder?,
themeSettings: ThemeSettings,
wallpaperSettings: WallpaperSettings,
scheduleSettings: ScheduleSettings,
effectSettings: EffectSettings,
onNavigateAddWallpaper: (String) -> Unit,
onViewAlbum: (String) -> Unit,
onDarkCheck: (Boolean) -> Unit,
onDarkenPercentage: (Int, Int) -> Unit,
onHomeCheckedChange: (Boolean) -> Unit,
onLockCheckedChange: (Boolean) -> Unit,
onScalingChange: (ScalingConstants) -> Unit,
onScheduleWallpaperChanger: () -> Unit,
onSelectAlbum: (AlbumWithWallpaperAndFolder, Boolean, Boolean) -> Unit,
onScheduleSeparatelyChange: (Boolean) -> Unit,
onHomeTimeChange: (Int) -> Unit,
onLockTimeChange: (Int) -> Unit,
onSettingsClick: () -> Unit,
onStop: (Boolean, Boolean) -> Unit,
onDeselect: (Boolean, Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
scaling: ScalingConstants,
scheduleSeparately: Boolean,
blur: Boolean,
onBlurPercentageChange: (Int, Int) -> Unit,
onBlurChange: (Boolean) -> Unit,
homeBlurPercentage: Int,
lockBlurPercentage: Int,
currentHomeWallpaper: String?,
currentLockWallpaper: String?,
homeSelectedAlbum: SelectedAlbum?,
lockSelectedAlbum: SelectedAlbum?,
homeVignettePercentage: Int,
lockVignettePercentage: Int,
onVignettePercentageChange: (Int, Int) -> Unit,
onVignetteChange: (Boolean) -> Unit,
vignette: Boolean,
homeGrayscalePercentage: Int,
lockGrayscalePercentage: Int,
onGrayscalePercentageChange: (Int, Int) -> Unit,
onGrayscaleChange: (Boolean) -> Unit,
grayscale: Boolean,
changeStartTime: Boolean,
onChangeStartTimeToggle: (Boolean) -> Unit,
onStartTimeChange: (TimePickerState) -> Unit,
startingTime: Pair<Int, Int>
onShuffleCheck: (Boolean) -> Unit,
onRefreshChange: (Boolean) -> Unit,
onSkipLandscapeChange: (Boolean) -> Unit,
onSkipNonInteractiveChange: (Boolean) -> Unit,
) {
val tabItems = getTabItems()
val pagerState = rememberPagerState(0) { tabItems.size }
@@ -98,7 +74,7 @@ fun HomeScreen(
var addAlbumDialog by rememberSaveable { mutableStateOf(false) }
if (addAlbumDialog) AddAlbumDialog(
onDismissRequest = { addAlbumDialog = false },
onConfirmation = { navigateToAddWallpaperScreen(it) }
onConfirmation = { onNavigateAddWallpaper(it) }
)
LaunchedEffect(tabIndex) {
@@ -109,9 +85,6 @@ fun HomeScreen(
}
Scaffold (
modifier = Modifier.semantics {
testTagsAsResourceId = true
},
topBar = {
HomeTopBar(
showSelectionModeAppBar = false,
@@ -121,22 +94,8 @@ fun HomeScreen(
}
) {
Column(modifier = Modifier.padding(it)) {
TabRow(
PrimaryTabRow(
selectedTabIndex = tabIndex,
indicator = { tabPositions ->
if (tabIndex in tabPositions.indices) {
TabRowDefaults.PrimaryIndicator(
modifier = Modifier.tabIndicatorOffset(tabPositions[tabIndex]),
shape = RoundedCornerShape(
topStart = 6.dp,
topEnd = 6.dp,
bottomEnd = 0.dp,
bottomStart = 0.dp,
),
width = 60.dp
)
}
}
) {
tabItems.forEachIndexed { index, item ->
Tab(
@@ -148,8 +107,7 @@ fun HomeScreen(
imageVector = if (index == tabIndex) item.filledIcon else item.unfilledIcon,
contentDescription = item.title
)
},
modifier = Modifier.testTag("paperize:${item.title}_button"),
}
)
}
}
@@ -160,54 +118,35 @@ fun HomeScreen(
when (index.coerceIn(tabItems.indices)) {
0 -> WallpaperScreen(
albums = albums,
animate = animate,
darken = darken,
homeDarkenPercentage = homeDarkenPercentage,
lockDarkenPercentage = lockDarkenPercentage,
enableChanger = enableChanger,
homeEnabled = homeEnabled,
homeInterval = homeInterval,
lockInterval = lockInterval,
lastSetTime = lastSetTime,
lockEnabled = lockEnabled,
nextSetTime = nextSetTime,
homeSelectedAlbum = homeSelectedAlbum,
lockSelectedAlbum = lockSelectedAlbum,
themeSettings = themeSettings,
wallpaperSettings = wallpaperSettings,
scheduleSettings = scheduleSettings,
effectSettings = effectSettings,
onDarkCheck = onDarkCheck,
onDarkenPercentage = onDarkenPercentage,
onHomeCheckedChange = onHomeCheckedChange,
onLockCheckedChange = onLockCheckedChange,
scheduleSeparately = scheduleSeparately,
onScheduleSeparatelyChange = onScheduleSeparatelyChange,
onScheduleWallpaperChanger = onScheduleWallpaperChanger,
onScalingChange = onScalingChange,
onScheduleSeparatelyChange = onScheduleSeparatelyChange,
onSelectAlbum = onSelectAlbum,
onHomeTimeChange = onHomeTimeChange,
onLockTimeChange = onLockTimeChange,
onStop = onStop,
onDeselect = onDeselect,
onToggleChanger = onToggleChanger,
scaling = scaling,
homeSelectedAlbum = homeSelectedAlbum,
lockSelectedAlbum = lockSelectedAlbum,
blur = blur,
onBlurPercentageChange = onBlurPercentageChange,
onBlurChange = onBlurChange,
homeBlurPercentage = homeBlurPercentage,
lockBlurPercentage = lockBlurPercentage,
currentHomeWallpaper = currentHomeWallpaper,
currentLockWallpaper = currentLockWallpaper,
homeVignettePercentage = homeVignettePercentage,
lockVignettePercentage = lockVignettePercentage,
onVignettePercentageChange = onVignettePercentageChange,
onVignetteChange = onVignetteChange,
vignette = vignette,
homeGrayscalePercentage = homeGrayscalePercentage,
lockGrayscalePercentage = lockGrayscalePercentage,
onGrayscalePercentageChange = onGrayscalePercentageChange,
onGrayscaleChange = onGrayscaleChange,
grayscale = grayscale,
changeStartTime = changeStartTime,
onChangeStartTimeToggle = onChangeStartTimeToggle,
onStartTimeChange = onStartTimeChange,
startingTime = startingTime
onShuffleCheck = onShuffleCheck,
onRefreshChange = onRefreshChange,
onSkipLandscapeChange = onSkipLandscapeChange,
onSkipNonInteractiveChange = onSkipNonInteractiveChange
)
else -> LibraryScreen(
albums = albums,
@@ -91,8 +91,7 @@ fun HomeTopBar (
}
} else {
IconButton(
onClick = { onSettingsClick() },
modifier = Modifier.testTag("paperize:home_to_settings_button"),
onClick = { onSettingsClick() }
) {
Icon(
imageVector = Icons.Outlined.Settings,
@@ -17,10 +17,7 @@ import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
@@ -35,17 +32,12 @@ fun LibraryScreen(
) {
val lazyListState = rememberLazyGridState()
Scaffold(
modifier = Modifier
.fillMaxSize()
.semantics {
testTagsAsResourceId = true
},
modifier = Modifier.fillMaxSize(),
floatingActionButton = {
LargeFloatingActionButton(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
onClick = onAddNewAlbumClick,
modifier = Modifier.testTag("paperize:library_floating_button")
) {
Icon(
Icons.Filled.Add,
@@ -1,115 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.licenses_screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.lerp
import androidx.compose.ui.unit.sp
import com.anthonyla.paperize.R
import com.mikepenz.aboutlibraries.ui.compose.m3.LibrariesContainer
import com.mikepenz.aboutlibraries.ui.compose.m3.LibraryDefaults
import me.onebone.toolbar.CollapsingToolbarScaffold
import me.onebone.toolbar.ScrollStrategy
import me.onebone.toolbar.rememberCollapsingToolbarScaffoldState
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LicensesScreen(
onBackClick: () -> Unit,
) {
val lazyListState = rememberLazyListState()
val topBarState = rememberCollapsingToolbarScaffoldState()
// Collapsing top bar
val largeTopAppBarHeight = TopAppBarDefaults.LargeAppBarExpandedHeight
val startPadding = 64.dp
val endPadding = 16.dp
val titleFontScaleStart = 30
val titleFontScaleEnd = 21
val titleExtraStartPadding = 32.dp
val collapseFraction = topBarState.toolbarState.progress
val firstPaddingInterpolation = lerp((endPadding * 5 / 4), endPadding, collapseFraction) + titleExtraStartPadding
val secondPaddingInterpolation = lerp(startPadding, (endPadding * 5 / 4), collapseFraction)
val dynamicPaddingStart = lerp(firstPaddingInterpolation, secondPaddingInterpolation, collapseFraction)
val textSize = (titleFontScaleEnd + (titleFontScaleStart - titleFontScaleEnd) * collapseFraction).sp
Scaffold {
CollapsingToolbarScaffold(
state = topBarState,
modifier = Modifier.fillMaxSize().padding(it),
scrollStrategy = ScrollStrategy.ExitUntilCollapsed,
toolbar = {
Box(
modifier = Modifier
.fillMaxWidth()
.height(largeTopAppBarHeight)
.background(MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp))
.pin()
)
IconButton(
onClick = onBackClick,
modifier = Modifier
.padding(16.dp)
.size(24.dp)
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.home_screen)
)
}
Text(
text = stringResource(R.string.licenses),
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onSurface,
fontSize = textSize,
modifier = Modifier
.road(Alignment.CenterStart, Alignment.BottomStart)
.padding(dynamicPaddingStart, 16.dp, 16.dp, 16.dp),
)
}
) {
Column(
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top,
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 24.dp),
) {
LibrariesContainer(
modifier = Modifier.fillMaxSize(),
lazyListState = lazyListState,
showVersion = false,
colors = LibraryDefaults.libraryColors(
backgroundColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp),
contentColor = MaterialTheme.colorScheme.onSurface,
badgeBackgroundColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp),
badgeContentColor = MaterialTheme.colorScheme.primary,
dialogConfirmButtonColor = MaterialTheme.colorScheme.onSurface
)
)
}
}
}
}
@@ -28,11 +28,9 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.airbnb.lottie.compose.LottieAnimation
@@ -78,9 +76,6 @@ fun NotificationScreen(
}
Scaffold(
modifier = Modifier.semantics {
testTagsAsResourceId = true
},
content = { it
Column (modifier = Modifier.padding(32.dp)) {
Spacer(modifier = Modifier.height(120.dp))
@@ -109,9 +104,7 @@ fun NotificationScreen(
},
floatingActionButton = {
ExtendedFloatingActionButton(
modifier = Modifier
.padding(8.dp)
.testTag("paperize:floating_notification_button"),
modifier = Modifier.padding(8.dp),
onClick = { askPermission.value = true },
icon = {
Icon(
@@ -4,7 +4,6 @@ import com.anthonyla.paperize.core.ScalingConstants
sealed class SettingsEvent {
data object Refresh: SettingsEvent()
data object Reset: SettingsEvent()
data object SetFirstLaunch: SettingsEvent()
data object RefreshNextSetTime: SettingsEvent()
@@ -19,10 +18,8 @@ sealed class SettingsEvent {
data class SetLock(val lock: Boolean): SettingsEvent()
data class SetHome(val home: Boolean): SettingsEvent()
data class SetChangeStartTime(val changeStartTime: Boolean): SettingsEvent()
data class SetCurrentHomeWallpaper(val currentHomeWallpaper: String?): SettingsEvent()
data class SetCurrentLockWallpaper(val currentLockWallpaper: String?): SettingsEvent()
data class SetCurrentWallpaper(val currentHomeWallpaper: String?, val currentLockWallpaper: String?): SettingsEvent()
data class SetAlbumName(val homeAlbumName: String? = null, val lockAlbumName: String? = null): SettingsEvent()
data class SetAlbum(val homeAlbumName: String? = null, val lockAlbumName: String? = null): SettingsEvent()
data class RemoveSelectedAlbumAsType(val removeLock: Boolean = false, val removeHome: Boolean = false): SettingsEvent()
data class RemoveSelectedAlbumAsName(val albumName: String): SettingsEvent()
data class SetScheduleSeparately(val scheduleSeparately: Boolean): SettingsEvent()
@@ -34,9 +31,9 @@ sealed class SettingsEvent {
data class SetGrayscalePercentage(val homeGrayscalePercentage: Int?, val lockGrayscalePercentage: Int?): SettingsEvent()
data class SetChangerToggle(val toggle: Boolean): SettingsEvent()
data class SetWallpaperScaling(val scaling: ScalingConstants): SettingsEvent()
data class SetNextHomeWallpaper(val nextHomeWallpaper: String?): SettingsEvent()
data class SetNextLockWallpaper(val nextLockWallpaper: String?): SettingsEvent()
data class SetNextWallpaper(val nextHomeWallpaper: String?, val nextLockWallpaper: String?): SettingsEvent()
data class SetStartTime(val hour: Int, val minute: Int): SettingsEvent()
data object RefreshNextWallpaper: SettingsEvent()
data class SetShuffle(val shuffle: Boolean): SettingsEvent()
data class SetRefresh(val refresh: Boolean): SettingsEvent()
data class SetSkipLandscape(val skipLandscape: Boolean): SettingsEvent()
data class SetSkipNonInteractive(val skipNonInteractive: Boolean): SettingsEvent()
}
@@ -27,74 +27,72 @@ import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.lerp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.ThemeSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.AmoledListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.AnimationListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.ContactListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.DarkModeListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.DynamicThemingListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.LicenseListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.ListSectionTitle
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.NotificationListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.PaperizeListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.PrivacyPolicyListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.ResetListItem
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components.TranslateListItem
import kotlinx.coroutines.flow.StateFlow
import me.onebone.toolbar.CollapsingToolbarScaffold
import me.onebone.toolbar.ScrollStrategy
import me.onebone.toolbar.rememberCollapsingToolbarScaffoldState
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
private object Links {
const val TRANSLATE = "https://crowdin.com/project/paperize/invite?h=d8d7a7513d2beb0c96ba9b2a5f85473e2084922"
const val GITHUB = "https://github.com/Anthonyy232/Paperize"
const val FDROID = "https://f-droid.org/en/packages/com.anthonyla.paperize/"
const val IZZY = "https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize"
}
private object ToolbarConfig {
@OptIn(ExperimentalMaterial3Api::class)
val LargeTopAppBarHeight = TopAppBarDefaults.LargeAppBarExpandedHeight
val StartPadding = 64.dp
val EndPadding = 16.dp
const val START = 30
const val END = 21
val TitleExtraStartPadding = 32.dp
}
@Composable
private fun calculateToolbarValues(collapseFraction: Float) = with(ToolbarConfig) {
val firstPaddingInterpolation = lerp((EndPadding * 5 / 4), EndPadding, collapseFraction) + TitleExtraStartPadding
val secondPaddingInterpolation = lerp(StartPadding, (EndPadding * 5 / 4), collapseFraction)
val dynamicPaddingStart = lerp(firstPaddingInterpolation, secondPaddingInterpolation, collapseFraction)
val textSize = (END + (START - END) * collapseFraction).sp
Pair(dynamicPaddingStart, textSize)
}
@Composable
fun SettingsScreen(
settingsState: StateFlow<SettingsState>,
themeSettings: ThemeSettings,
onBackClick: () -> Unit,
onDarkModeClick: (Boolean?) -> Unit,
onAmoledClick: (Boolean) -> Unit,
onDynamicThemingClick: (Boolean) -> Unit,
onAnimateClick: (Boolean) -> Unit,
onPrivacyClick: () -> Unit,
onLicenseClick: () -> Unit,
onResetClick: () -> Unit,
onContactClick: () -> Unit
) {
val topBarState = rememberCollapsingToolbarScaffoldState()
val state = settingsState.collectAsStateWithLifecycle()
val context = LocalContext.current
val topBarState = rememberCollapsingToolbarScaffoldState()
val (dynamicPaddingStart, textSize) = calculateToolbarValues(topBarState.toolbarState.progress)
val translateLink = "https://crowdin.com/project/paperize/invite?h=d8d7a7513d2beb0c96ba9b2a5f85473e2084922"
val githubLink = "https://github.com/Anthonyy232/Paperize"
val fdroidLink = "https://f-droid.org/en/packages/com.anthonyla.paperize/"
val izzyOnDroidLink = "https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize"
// Collapsing top bar
val largeTopAppBarHeight = TopAppBarDefaults.LargeAppBarExpandedHeight
val startPadding = 64.dp
val endPadding = 16.dp
val titleFontScaleStart = 30
val titleFontScaleEnd = 21
val titleExtraStartPadding = 32.dp
val collapseFraction = topBarState.toolbarState.progress
val firstPaddingInterpolation = lerp((endPadding * 5 / 4), endPadding, collapseFraction) + titleExtraStartPadding
val secondPaddingInterpolation = lerp(startPadding, (endPadding * 5 / 4), collapseFraction)
val dynamicPaddingStart = lerp(firstPaddingInterpolation, secondPaddingInterpolation, collapseFraction)
val textSize = (titleFontScaleEnd + (titleFontScaleStart - titleFontScaleEnd) * collapseFraction).sp
Scaffold(
modifier = Modifier.semantics { testTagsAsResourceId = true },
) {
Scaffold {
CollapsingToolbarScaffold(
state = topBarState,
modifier = Modifier.fillMaxSize().padding(it),
@@ -103,7 +101,7 @@ fun SettingsScreen(
Box(
modifier = Modifier
.fillMaxWidth()
.height(largeTopAppBarHeight)
.height(ToolbarConfig.LargeTopAppBarHeight)
.background(MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp))
.pin()
)
@@ -112,7 +110,6 @@ fun SettingsScreen(
modifier = Modifier
.padding(16.dp)
.size(24.dp)
.testTag("paperize:settings_to_home_button"),
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
@@ -130,86 +127,111 @@ fun SettingsScreen(
)
}
) {
Column(
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top,
modifier = Modifier
.verticalScroll(rememberScrollState())
.fillMaxSize()
.padding(horizontal = 24.dp)
.testTag("paperize:settings_column"),
) {
ListSectionTitle(stringResource(R.string.appearance))
Spacer(modifier = Modifier.height(16.dp))
DarkModeListItem(
darkMode = state.value.darkMode,
onDarkModeClick = { onDarkModeClick(it) }
)
Spacer(modifier = Modifier.height(16.dp))
if (state.value.darkMode == null || state.value.darkMode == true) {
AmoledListItem(
amoledMode = state.value.amoledTheme,
onAmoledClick = { onAmoledClick(it) }
)
Spacer(modifier = Modifier.height(16.dp))
}
DynamicThemingListItem(
dynamicTheming = state.value.dynamicTheming,
onDynamicThemingClick = { onDynamicThemingClick(it) }
)
Spacer(modifier = Modifier.height(16.dp))
AnimationListItem(
animate = state.value.animate,
onAnimateClick = { onAnimateClick(it) }
)
Spacer(modifier = Modifier.height(16.dp))
ListSectionTitle(stringResource(R.string.about))
Spacer(modifier = Modifier.height(16.dp))
NotificationListItem(
onClick = {
val intent = Intent().apply {
action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
}
context.startActivity(intent)
}
)
Spacer(modifier = Modifier.height(16.dp))
TranslateListItem(
onClick = {
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse(translateLink)
context.startActivity(openURL)
}
)
Spacer(modifier = Modifier.height(16.dp))
PrivacyPolicyListItem (onPrivacyPolicyClick = onPrivacyClick)
Spacer(modifier = Modifier.height(16.dp))
LicenseListItem(onLicenseClick = onLicenseClick)
Spacer(modifier = Modifier.height(16.dp))
ContactListItem(onContactClick = onContactClick)
Spacer(modifier = Modifier.height(16.dp))
PaperizeListItem(
onGitHubClick = {
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse(githubLink)
context.startActivity(openURL)
},
onFdroidClick = {
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse(fdroidLink)
context.startActivity(openURL)
},
onIzzyOnDroidClick = {
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse(izzyOnDroidLink)
context.startActivity(openURL)
},
)
Spacer(modifier = Modifier.height(16.dp))
ResetListItem(onResetClick = onResetClick)
Spacer(modifier = Modifier.height(16.dp))
}
SettingsContent(
themeSettings = themeSettings,
onDarkModeClick = onDarkModeClick,
onAmoledClick = onAmoledClick,
onDynamicThemingClick = onDynamicThemingClick,
onAnimateClick = onAnimateClick,
onPrivacyClick = onPrivacyClick,
onResetClick = onResetClick,
onContactClick = onContactClick,
context = context
)
}
}
}
@Composable
private fun SettingsContent(
themeSettings: ThemeSettings,
onDarkModeClick: (Boolean?) -> Unit,
onAmoledClick: (Boolean) -> Unit,
onDynamicThemingClick: (Boolean) -> Unit,
onAnimateClick: (Boolean) -> Unit,
onPrivacyClick: () -> Unit,
onResetClick: () -> Unit,
onContactClick: () -> Unit,
context: android.content.Context
) {
Column(
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top,
modifier = Modifier
.verticalScroll(rememberScrollState())
.fillMaxSize()
.padding(horizontal = 24.dp)
) {
AppearanceSection(themeSettings, onDarkModeClick, onAmoledClick, onDynamicThemingClick, onAnimateClick)
AboutSection(context, onPrivacyClick, onContactClick, onResetClick)
}
}
@Composable
private fun AppearanceSection(
themeSettings: ThemeSettings,
onDarkModeClick: (Boolean?) -> Unit,
onAmoledClick: (Boolean) -> Unit,
onDynamicThemingClick: (Boolean) -> Unit,
onAnimateClick: (Boolean) -> Unit
) {
ListSectionTitle(stringResource(R.string.appearance))
Spacer(modifier = Modifier.height(16.dp))
DarkModeListItem(
darkMode = themeSettings.darkMode,
onDarkModeClick = onDarkModeClick
)
Spacer(modifier = Modifier.height(16.dp))
if (themeSettings.darkMode == null || themeSettings.darkMode == true) {
AmoledListItem(
amoledMode = themeSettings.amoledTheme,
onAmoledClick = onAmoledClick
)
Spacer(modifier = Modifier.height(16.dp))
}
DynamicThemingListItem(
dynamicTheming = themeSettings.dynamicTheming,
onDynamicThemingClick = onDynamicThemingClick
)
Spacer(modifier = Modifier.height(16.dp))
AnimationListItem(
animate = themeSettings.animate,
onAnimateClick = onAnimateClick
)
Spacer(modifier = Modifier.height(16.dp))
}
@Composable
private fun AboutSection(
context: android.content.Context,
onPrivacyClick: () -> Unit,
onContactClick: () -> Unit,
onResetClick: () -> Unit
) {
ListSectionTitle(stringResource(R.string.about))
Spacer(modifier = Modifier.height(16.dp))
NotificationListItem {
val intent = Intent().apply {
action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
}
context.startActivity(intent)
}
Spacer(modifier = Modifier.height(16.dp))
TranslateListItem {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(Links.TRANSLATE)))
}
Spacer(modifier = Modifier.height(16.dp))
PrivacyPolicyListItem(onPrivacyClick)
Spacer(modifier = Modifier.height(16.dp))
ContactListItem(onContactClick)
Spacer(modifier = Modifier.height(16.dp))
PaperizeListItem(
onGitHubClick = { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(Links.GITHUB))) },
onFdroidClick = { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(Links.FDROID))) },
onIzzyOnDroidClick = { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(Links.IZZY))) }
)
Spacer(modifier = Modifier.height(16.dp))
ResetListItem(onResetClick)
Spacer(modifier = Modifier.height(16.dp))
}
@@ -1,42 +1,86 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
data class SettingsState(
val firstLaunch: Boolean = true,
// App settings
val darkMode: Boolean? = null,
val amoledTheme: Boolean = false,
val dynamicTheming: Boolean = false,
val animate: Boolean = true,
// Wallpaper settings
val enableChanger: Boolean = false,
val setHomeWallpaper: Boolean = false,
val setLockWallpaper: Boolean = false,
val currentHomeWallpaper: String? = null,
val currentLockWallpaper: String? = null,
val homeAlbumName: String? = null,
val lockAlbumName: String? = null,
val scheduleSeparately: Boolean = false,
val homeInterval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val lockInterval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val lastSetTime: String? = null,
val nextSetTime: String? = null,
val homeDarkenPercentage: Int = 100,
val lockDarkenPercentage: Int = 100,
val darken: Boolean = false,
val blur: Boolean = false,
val homeBlurPercentage: Int = 0,
val lockBlurPercentage: Int = 0,
val vignette: Boolean = false,
val homeVignettePercentage: Int = 0,
val lockVignettePercentage: Int = 0,
val grayscale: Boolean = false,
val homeGrayscalePercentage: Int = 0,
val lockGrayscalePercentage: Int = 0,
val wallpaperScaling: ScalingConstants = ScalingConstants.FILL,
val nextHomeWallpaper: String? = null,
val nextLockWallpaper: String? = null,
val changeStartTime: Boolean = false,
val startTime: Pair<Int, Int> = Pair(0, 0)
)
val initialized: Boolean = false,
val themeSettings: ThemeSettings = ThemeSettings(),
val wallpaperSettings: WallpaperSettings = WallpaperSettings(),
val scheduleSettings: ScheduleSettings = ScheduleSettings(),
val effectSettings: EffectSettings = EffectSettings()
) {
data class ThemeSettings(
val darkMode: Boolean? = null,
val amoledTheme: Boolean = false,
val dynamicTheming: Boolean = false,
val animate: Boolean = true
)
data class WallpaperSettings(
val enableChanger: Boolean = false,
val setHomeWallpaper: Boolean = false,
val setLockWallpaper: Boolean = false,
val currentHomeWallpaper: String? = null,
val currentLockWallpaper: String? = null,
val nextHomeWallpaper: String? = null,
val nextLockWallpaper: String? = null,
val homeAlbumName: String? = null,
val lockAlbumName: String? = null,
val wallpaperScaling: ScalingConstants = ScalingConstants.FILL
)
data class ScheduleSettings(
val scheduleSeparately: Boolean = false,
val shuffle: Boolean = true,
val homeInterval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val lockInterval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val lastSetTime: String? = null,
val nextSetTime: String? = null,
val changeStartTime: Boolean = false,
val startTime: Pair<Int, Int> = Pair(0, 0),
val refresh: Boolean = true,
val skipLandscape: Boolean = false,
val skipNonInteractive: Boolean = false
)
data class EffectSettings(
val darken: Boolean = false,
val homeDarkenPercentage: Int = 100,
val lockDarkenPercentage: Int = 100,
val blur: Boolean = false,
val homeBlurPercentage: Int = 0,
val lockBlurPercentage: Int = 0,
val vignette: Boolean = false,
val homeVignettePercentage: Int = 0,
val lockVignettePercentage: Int = 0,
val grayscale: Boolean = false,
val homeGrayscalePercentage: Int = 0,
val lockGrayscalePercentage: Int = 0
)
data class ServiceSettings(
val enableChanger: Boolean,
val setHome: Boolean,
val setLock: Boolean,
val scaling: ScalingConstants,
val darken: Boolean,
val homeDarkenPercentage: Int,
val lockDarkenPercentage: Int,
val blur: Boolean,
val homeBlurPercentage: Int,
val lockBlurPercentage: Int,
val vignette: Boolean,
val homeVignettePercentage: Int,
val lockVignettePercentage: Int,
val grayscale: Boolean,
val homeGrayscalePercentage: Int,
val lockGrayscalePercentage: Int,
val lockAlbumName: String,
val homeAlbumName: String,
val shuffle: Boolean,
val skipLandscape: Boolean,
val skipNonInteractive: Boolean
)
}
@@ -1,48 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.LibraryBooks
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
/**
* A list item that displays the licenses
*/
@Composable
fun LicenseListItem(onLicenseClick: () -> Unit) {
Row {
ListItem(
modifier = Modifier
.clip(RoundedCornerShape(16.dp))
.clickable { onLicenseClick() },
headlineContent = {
Text(
text = stringResource(R.string.licenses),
style = MaterialTheme.typography.titleMedium
) },
supportingContent = {
Text(
text = stringResource(R.string.click_here_to_view_the_licenses),
style = MaterialTheme.typography.bodySmall
) },
trailingContent = {},
leadingContent = {
Icon(
Icons.AutoMirrored.Outlined.LibraryBooks,
contentDescription = stringResource(R.string.licenses),
tint = MaterialTheme.colorScheme.primary
) },
tonalElevation = 5.dp
)
}
}
@@ -0,0 +1,35 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen
import androidx.compose.foundation.lazy.LazyListItemInfo
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
sealed class SortEvent {
data object Reset: SortEvent()
data class LoadSortView(
val folders: List<Folder>,
val wallpapers: List<Wallpaper>
): SortEvent()
data class ShiftFolder(
val from: LazyListItemInfo,
val to: LazyListItemInfo
): SortEvent()
data class ShiftWallpaper(
val from: LazyListItemInfo,
val to: LazyListItemInfo
): SortEvent()
data class ShiftFolderWallpaper(
val folderId: String,
val from: LazyListItemInfo,
val to: LazyListItemInfo
): SortEvent()
data object SortAlphabetically : SortEvent()
data object SortAlphabeticallyReverse : SortEvent()
data object SortByLastModified : SortEvent()
data object SortByLastModifiedReverse : SortEvent()
}
@@ -0,0 +1,9 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
data class SortState(
val folders: List<Folder> = emptyList(),
val wallpapers: List<Wallpaper> = emptyList()
)
@@ -0,0 +1,191 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
/**
* ViewModel for the sort view screen to hold the folders and wallpapers
*/
class SortViewModel @Inject constructor (): ViewModel() {
private val _state = MutableStateFlow<SortState>(SortState())
val state = _state.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = SortState()
)
fun onEvent(event: SortEvent) {
when (event) {
is SortEvent.LoadSortView -> {
_state.value = state.value.copy(
folders = event.folders,
wallpapers = event.wallpapers
)
}
is SortEvent.ShiftFolder -> {
val currentFolders = state.value.folders.toMutableList()
val fromIndex = currentFolders.indexOfFirst { it.folderUri == event.from.key }
val toIndex = currentFolders.indexOfFirst { it.folderUri == event.to.key }
val movedFolder = currentFolders.removeAt(fromIndex)
currentFolders.add(toIndex, movedFolder)
currentFolders.forEachIndexed { index, folder ->
currentFolders[index] = folder.copy(order = index)
}
_state.value = state.value.copy(folders = currentFolders)
}
is SortEvent.ShiftFolderWallpaper -> {
val folder = state.value.folders.find { it.folderUri == event.folderId }
val currentWallpapers = folder?.wallpapers?.toMutableList() ?: return
val fromIndex = currentWallpapers.indexOfFirst { it.wallpaperUri == event.from.key }
val toIndex = currentWallpapers.indexOfFirst { it.wallpaperUri == event.to.key }
val movedWallpaper = currentWallpapers.removeAt(fromIndex)
currentWallpapers.add(toIndex, movedWallpaper)
currentWallpapers.forEachIndexed { index, wallpaper ->
currentWallpapers[index] = wallpaper.copy(order = index)
}
val updatedFolders = state.value.folders.map { folder ->
if (folder.folderUri == event.folderId) {
folder.copy(
wallpapers = currentWallpapers,
coverUri = currentWallpapers.firstOrNull()?.wallpaperUri ?: folder.coverUri
)
} else {
folder
}
}
_state.value = state.value.copy(folders = updatedFolders)
}
is SortEvent.ShiftWallpaper -> {
val currentWallpapers = state.value.wallpapers.toMutableList()
val fromIndex = currentWallpapers.indexOfFirst { it.wallpaperUri == event.from.key }
val toIndex = currentWallpapers.indexOfFirst { it.wallpaperUri == event.to.key }
val movedWallpaper = currentWallpapers.removeAt(fromIndex)
currentWallpapers.add(toIndex, movedWallpaper)
currentWallpapers.forEachIndexed { index, wallpaper ->
currentWallpapers[index] = wallpaper.copy(order = index)
}
_state.value = state.value.copy(wallpapers = currentWallpapers)
}
is SortEvent.Reset -> {
_state.value = SortState()
}
is SortEvent.SortAlphabetically -> {
val sortedFolders = state.value.folders
.map { folder ->
val sortedFolderWallpapers = folder.wallpapers
.sortedBy { it.fileName }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
folder.copy(wallpapers = sortedFolderWallpapers)
}
.sortedBy { it.folderName }
.mapIndexed { index, folder ->
folder.copy(order = index)
}
val sortedWallpapers = state.value.wallpapers
.sortedBy { it.fileName }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
_state.value = state.value.copy(
folders = sortedFolders,
wallpapers = sortedWallpapers
)
}
is SortEvent.SortAlphabeticallyReverse -> {
val sortedFolders = state.value.folders
.map { folder ->
val sortedFolderWallpapers = folder.wallpapers
.sortedByDescending { it.fileName }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
folder.copy(wallpapers = sortedFolderWallpapers)
}
.sortedByDescending { it.folderName }
.mapIndexed { index, folder ->
folder.copy(order = index)
}
val sortedWallpapers = state.value.wallpapers
.sortedByDescending { it.fileName }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
_state.value = state.value.copy(
folders = sortedFolders,
wallpapers = sortedWallpapers
)
}
is SortEvent.SortByLastModified -> {
val sortedFolders = state.value.folders
.map { folder ->
val sortedFolderWallpapers = folder.wallpapers
.sortedBy { it.dateModified }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
folder.copy(wallpapers = sortedFolderWallpapers)
}
.sortedBy { it.dateModified }
.mapIndexed { index, folder ->
folder.copy(order = index)
}
val sortedWallpapers = state.value.wallpapers
.sortedBy { it.dateModified }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
_state.value = state.value.copy(
folders = sortedFolders,
wallpapers = sortedWallpapers
)
}
is SortEvent.SortByLastModifiedReverse -> {
val sortedFolders = state.value.folders
.map { folder ->
val sortedFolderWallpapers = folder.wallpapers
.sortedByDescending { it.dateModified }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
folder.copy(wallpapers = sortedFolderWallpapers)
}
.sortedByDescending { it.dateModified }
.mapIndexed { index, folder ->
folder.copy(order = index)
}
val sortedWallpapers = state.value.wallpapers
.sortedByDescending { it.dateModified }
.mapIndexed { index, wallpaper ->
wallpaper.copy(order = index)
}
_state.value = state.value.copy(
folders = sortedFolders,
wallpapers = sortedWallpapers
)
}
}
}
}
@@ -0,0 +1,410 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen
import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Card
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.components.SortViewTopBar
import sh.calvin.reorderable.ReorderableItem
import sh.calvin.reorderable.rememberReorderableLazyListState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.res.stringResource
import com.anthonyla.paperize.R
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.CardColors
import androidx.compose.material3.IconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.core.net.toUri
import com.anthonyla.paperize.core.decompress
import com.skydoves.landscapist.glide.GlideImage
import com.skydoves.landscapist.ImageOptions
import androidx.compose.ui.layout.ContentScale
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun SortViewScreen(
sortViewModel: SortViewModel,
onSaveClick: () -> Unit,
onBackClick: () -> Unit,
) {
val view = LocalView.current
val state = sortViewModel.state.collectAsStateWithLifecycle()
val lazyListState = rememberLazyListState()
val expandedFolderId = remember { mutableStateOf<String?>(null) }
val onTopBarBackClick: () -> Unit = {
if (expandedFolderId.value != null) {
expandedFolderId.value = null
} else {
onBackClick()
}
}
// Logic to determine the title for the top bar
val topBarTitle = remember(expandedFolderId.value, state.value.folders) {
val currentFolderId = expandedFolderId.value
if (!currentFolderId.isNullOrEmpty()) {
state.value.folders.find { it.folderUri == currentFolderId }?.folderName ?: ""
} else {
""
}
}
val reorderableLazyListStateFolder = rememberReorderableLazyListState(lazyListState) { from, to ->
sortViewModel.onEvent(SortEvent.ShiftFolder(from, to))
}
val reorderableLazyListStateWallpaper = rememberReorderableLazyListState(lazyListState) { from, to ->
sortViewModel.onEvent(SortEvent.ShiftWallpaper(from, to))
}
val folderWallpapersListState = rememberLazyListState()
val reorderableFolderWallpapersState = rememberReorderableLazyListState(folderWallpapersListState) { from, to ->
expandedFolderId.value?.let { folderId ->
sortViewModel.onEvent(SortEvent.ShiftFolderWallpaper(folderId, from, to))
}
}
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
SortViewTopBar(
title = topBarTitle,
onBackClick = onTopBarBackClick,
onSaveClick = onSaveClick,
onSortAlphabetically = { sortViewModel.onEvent(SortEvent.SortAlphabetically) },
onSortAlphabeticallyReverse = { sortViewModel.onEvent(SortEvent.SortAlphabeticallyReverse) },
onSortByLastModified = { sortViewModel.onEvent(SortEvent.SortByLastModified) },
onSortByLastModifiedReverse = { sortViewModel.onEvent(SortEvent.SortByLastModifiedReverse) },
)
}
) {
SharedTransitionLayout (modifier = Modifier.fillMaxSize()) {
AnimatedContent(
modifier = Modifier.fillMaxSize(),
targetState = !expandedFolderId.value.isNullOrEmpty(), label = "",
) { targetState ->
with (this@SharedTransitionLayout) {
if (!targetState) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(it),
state = lazyListState,
contentPadding = PaddingValues(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (state.value.folders.isNotEmpty()) {
item {
Text(
text = stringResource(R.string.folders),
modifier = Modifier.padding(8.dp),
fontWeight = FontWeight.Bold
)
}
}
items(state.value.folders, key = { it.folderUri }) { folder ->
ReorderableItem(
state = reorderableLazyListStateFolder,
key = folder.folderUri
) { isDragging ->
val interactionSource = remember { MutableInteractionSource() }
Card(
modifier = Modifier
.fillMaxWidth()
.longPressDraggableHandle(
onDragStarted = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
view.performHapticFeedback(
HapticFeedbackConstants.DRAG_START
)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(
HapticFeedbackConstants.GESTURE_START
)
} else {
view.performHapticFeedback(
HapticFeedbackConstants.LONG_PRESS
)
}
},
onDragStopped = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
view.performHapticFeedback(
HapticFeedbackConstants.GESTURE_END
)
} else {
view.performHapticFeedback(
HapticFeedbackConstants.LONG_PRESS
)
}
},
interactionSource = interactionSource,
),
colors = CardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer,
disabledContentColor = MaterialTheme.colorScheme.onSecondaryContainer,
),
onClick = { expandedFolderId.value = folder.folderUri }
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = folder.folderName ?: "",
modifier = Modifier.sharedElement(
rememberSharedContentState(folder.folderName ?: ""),
animatedVisibilityScope = this@AnimatedContent,
)
)
IconButton(onClick = {
expandedFolderId.value = folder.folderUri
}) {
Icon(
Icons.Default.Add,
contentDescription = stringResource(R.string.expand)
)
}
}
}
}
}
if (state.value.wallpapers.isNotEmpty()) {
item {
Text(
text = stringResource(R.string.wallpapers_sort),
modifier = Modifier.padding(8.dp),
fontWeight = FontWeight.Bold
)
}
}
items(state.value.wallpapers, key = { it.wallpaperUri }) { wallpaper ->
ReorderableItem(
reorderableLazyListStateWallpaper,
key = wallpaper.wallpaperUri
) { isDragging ->
val interactionSource = remember { MutableInteractionSource() }
Card(
modifier = Modifier
.fillMaxWidth()
.longPressDraggableHandle(
onDragStarted = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
view.performHapticFeedback(
HapticFeedbackConstants.DRAG_START
)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(
HapticFeedbackConstants.GESTURE_START
)
} else {
view.performHapticFeedback(
HapticFeedbackConstants.LONG_PRESS
)
}
},
onDragStopped = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
view.performHapticFeedback(
HapticFeedbackConstants.GESTURE_END
)
} else {
view.performHapticFeedback(
HapticFeedbackConstants.LONG_PRESS
)
}
},
interactionSource = interactionSource,
),
onClick = {},
colors = CardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer,
disabledContentColor = MaterialTheme.colorScheme.onSecondaryContainer,
),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.padding(16.dp)
) {
Text(
text = wallpaper.fileName,
modifier = Modifier.weight(1f)
)
Spacer(modifier = Modifier.width(8.dp))
GlideImage(
imageModel = { wallpaper.wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri() },
modifier = Modifier
.size(48.dp)
.border(BorderStroke(1.dp, MaterialTheme.colorScheme.onSecondaryContainer), CircleShape)
.clip(CircleShape),
imageOptions = ImageOptions(
contentScale = ContentScale.Crop
)
)
}
}
}
}
}
}
else {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(it),
state = folderWallpapersListState,
contentPadding = PaddingValues(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
val currentFolder = state.value.folders.find { it.folderUri == expandedFolderId.value }
if (currentFolder != null) {
item {
ListItem(
modifier = Modifier.fillMaxWidth(),
leadingContent = {
GlideImage(
imageModel = { currentFolder.coverUri?.decompress("content://com.android.externalstorage.documents/")?.toUri() },
modifier = Modifier
.size(48.dp)
.clip(RoundedCornerShape(8.dp)),
imageOptions = ImageOptions(
contentScale = ContentScale.Crop
)
)
},
headlineContent = {
Text(text = currentFolder.folderName ?: "")
},
supportingContent = {
Text(text = currentFolder.wallpapers.size.toString().plus(" " + stringResource(R.string.wallpapers)))
},
trailingContent = {
IconButton(onClick = { expandedFolderId.value = null }) {
Icon(
Icons.Default.Close,
contentDescription = stringResource(R.string.close)
)
}
}
)
}
items(currentFolder.wallpapers, key = { it.wallpaperUri }) { wallpaper ->
ReorderableItem(
reorderableFolderWallpapersState,
key = wallpaper.wallpaperUri
) { isDragging ->
val interactionSource = remember { MutableInteractionSource() }
Card(
modifier = Modifier
.fillMaxWidth()
.longPressDraggableHandle(
onDragStarted = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
view.performHapticFeedback(
HapticFeedbackConstants.DRAG_START
)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(
HapticFeedbackConstants.GESTURE_START
)
} else {
view.performHapticFeedback(
HapticFeedbackConstants.LONG_PRESS
)
}
},
onDragStopped = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
view.performHapticFeedback(
HapticFeedbackConstants.GESTURE_END
)
} else {
view.performHapticFeedback(
HapticFeedbackConstants.LONG_PRESS
)
}
},
interactionSource = interactionSource,
),
onClick = {},
colors = CardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer,
disabledContentColor = MaterialTheme.colorScheme.onSecondaryContainer,
),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.padding(16.dp)
) {
Text(
text = wallpaper.fileName,
modifier = Modifier.weight(1f)
)
Spacer(modifier = Modifier.width(8.dp))
GlideImage(
imageModel = { wallpaper.wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri() },
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.border(BorderStroke(1.dp, MaterialTheme.colorScheme.onSecondaryContainer), CircleShape),
imageOptions = ImageOptions(
contentScale = ContentScale.Crop
)
)
}
}
}
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,129 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.shape.RoundedCornerShape
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.Add
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
/**
* Top bar for the folder view screen.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SortViewTopBar(
title: String,
onBackClick: () -> Unit,
onSaveClick: () -> Unit,
onSortAlphabetically: () -> Unit,
onSortByLastModified: () -> Unit,
onSortAlphabeticallyReverse: () -> Unit,
onSortByLastModifiedReverse: () -> Unit
) {
var showSortMenu by remember { mutableStateOf(false) }
TopAppBar(
colors = topAppBarColors(containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)),
title = { Text(title) },
navigationIcon = {
IconButton(
onClick = onBackClick,
modifier = Modifier
.padding(16.dp)
.requiredSize(24.dp)
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.home_screen),
)
}
},
actions = {
Row {
IconButton(
onClick = { showSortMenu = true },
modifier = Modifier
.padding(16.dp)
.requiredSize(24.dp)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.Sort,
contentDescription = stringResource(R.string.sort_items),
)
}
MaterialTheme(
shapes = MaterialTheme.shapes.copy(extraSmall = RoundedCornerShape(16.dp))
) {
DropdownMenu(
expanded = showSortMenu,
onDismissRequest = { showSortMenu = false },
containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.sort_alphabetically_a_z)) },
onClick = {
onSortAlphabetically()
showSortMenu = false
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.sort_alphabetically_z_a)) },
onClick = {
onSortAlphabeticallyReverse()
showSortMenu = false
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.sort_by_last_modified_newest)) },
onClick = {
onSortByLastModified()
showSortMenu = false
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.sort_by_last_modified_oldest)) },
onClick = {
onSortByLastModifiedReverse()
showSortMenu = false
}
)
}
}
IconButton(
onClick = onSaveClick,
modifier = Modifier
.padding(16.dp)
.requiredSize(24.dp)
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = stringResource(R.string.sort_items),
)
}
}
}
)
}
@@ -37,11 +37,9 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.compose.LottieAnimation
@@ -75,20 +73,13 @@ fun StartupScreen(
}
Scaffold(
modifier = Modifier.semantics {
testTagsAsResourceId = true
},
snackbarHost = {
SnackbarHost(
hostState = snackbarHostState,
snackbar = { data ->
Snackbar(
snackbarData = data,
modifier = Modifier
.padding(PaddingValues(horizontal = 8.dp))
.semantics {
testTagsAsResourceId = true
},
modifier = Modifier.padding(PaddingValues(horizontal = 8.dp)),
shape = RoundedCornerShape(24.dp)
)
}
@@ -129,9 +120,7 @@ fun StartupScreen(
snackbarHostState.currentSnackbarData?.dismiss()
showToS = true
} },
modifier = Modifier
.padding(PaddingValues(vertical = 16.dp))
.testTag("paperize:privacy_notice_button"),
modifier = Modifier.padding(PaddingValues(vertical = 16.dp))
) {
Text(text = stringResource(R.string.privacy_notice), textAlign = TextAlign.Start)
}
@@ -140,9 +129,7 @@ fun StartupScreen(
},
floatingActionButton = {
ExtendedFloatingActionButton(
modifier = Modifier
.padding(8.dp)
.testTag("paperize:floating_agree_button"),
modifier = Modifier.padding(8.dp),
onClick = {
if (seenToS) {
onAgree()
@@ -176,11 +163,7 @@ fun StartupScreen(
if (showToS) {
seenToS = true
AlertDialog(
modifier = Modifier
.fillMaxHeight(0.7f)
.semantics {
testTagsAsResourceId = true
},
modifier = Modifier.fillMaxHeight(0.7f),
onDismissRequest = { showToS = false },
title = {
Box(modifier = Modifier.fillMaxWidth()) {
@@ -194,8 +177,7 @@ fun StartupScreen(
text = { PrivacyNoticeText() },
confirmButton = {
Button(
onClick = { showToS = false },
modifier = Modifier.testTag("paperize:dismiss_button"),
onClick = { showToS = false }
) {
Text(stringResource(R.string.dismiss))
}
@@ -1,11 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
sealed class WallpaperEvent {
data class AddSelectedAlbum(val album: AlbumWithWallpaperAndFolder, val deleteAlbumName: String? = null): WallpaperEvent()
data class UpdateSelectedAlbum(val album: SelectedAlbum): WallpaperEvent()
data class Reset(val album: SelectedAlbum? = null) : WallpaperEvent()
data object Refresh : WallpaperEvent()
}
@@ -5,7 +5,6 @@ import android.content.Intent
import android.os.Build
import android.provider.Settings
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
@@ -26,17 +25,17 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.EffectSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.ScheduleSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.ThemeSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.WallpaperSettings
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.AlbumBottomSheet
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.BlurSwitchAndSlider
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.ChangerSelectionRow
@@ -45,74 +44,85 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.co
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.DarkenSwitchAndSlider
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.GrayscaleSwitchAndSlider
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.IndividualSchedulingAndToggleRow
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.RefreshSwitch
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.ShuffleSwitch
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.SkipLandscapeSwitch
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.SkipNonInteractiveSwitch
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.TimeSliders
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.VignetteSwitchAndSlider
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.WallpaperPreviewAndScale
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WallpaperScreen(
albums: List<AlbumWithWallpaperAndFolder>,
animate: Boolean,
darken: Boolean,
homeDarkenPercentage: Int,
lockDarkenPercentage: Int,
enableChanger: Boolean,
homeEnabled: Boolean,
homeInterval: Int,
lockInterval: Int,
lastSetTime: String?,
lockEnabled: Boolean,
nextSetTime: String?,
currentHomeWallpaper: String?,
currentLockWallpaper: String?,
homeSelectedAlbum: AlbumWithWallpaperAndFolder?,
lockSelectedAlbum: AlbumWithWallpaperAndFolder?,
wallpaperSettings: WallpaperSettings,
scheduleSettings: ScheduleSettings,
themeSettings: ThemeSettings,
effectSettings: EffectSettings,
onDarkCheck: (Boolean) -> Unit,
onDarkenPercentage: (Int, Int) -> Unit,
onHomeCheckedChange: (Boolean) -> Unit,
onLockCheckedChange: (Boolean) -> Unit,
scheduleSeparately: Boolean,
onScheduleSeparatelyChange: (Boolean) -> Unit,
onScheduleWallpaperChanger: () -> Unit,
onScalingChange: (ScalingConstants) -> Unit,
onScheduleSeparatelyChange: (Boolean) -> Unit,
onSelectAlbum: (AlbumWithWallpaperAndFolder, Boolean, Boolean) -> Unit,
onHomeTimeChange: (Int) -> Unit,
onLockTimeChange: (Int) -> Unit,
onStop: (Boolean, Boolean) -> Unit,
onDeselect: (Boolean, Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
scaling: ScalingConstants,
homeSelectedAlbum: SelectedAlbum?,
lockSelectedAlbum: SelectedAlbum?,
blur: Boolean,
onBlurPercentageChange: (Int, Int) -> Unit,
onBlurChange: (Boolean) -> Unit,
homeBlurPercentage: Int,
lockBlurPercentage: Int,
homeVignettePercentage: Int,
lockVignettePercentage: Int,
onVignettePercentageChange: (Int, Int) -> Unit,
onVignetteChange: (Boolean) -> Unit,
vignette: Boolean,
homeGrayscalePercentage: Int,
lockGrayscalePercentage: Int,
onGrayscalePercentageChange: (Int, Int) -> Unit,
onGrayscaleChange: (Boolean) -> Unit,
grayscale: Boolean,
changeStartTime: Boolean,
onChangeStartTimeToggle: (Boolean) -> Unit,
onStartTimeChange: (TimePickerState) -> Unit,
startingTime: Pair<Int, Int>
onShuffleCheck: (Boolean) -> Unit,
onRefreshChange: (Boolean) -> Unit,
onSkipLandscapeChange: (Boolean) -> Unit,
onSkipNonInteractiveChange: (Boolean) -> Unit
) {
val shouldShowScreen = homeEnabled || lockEnabled
val shouldShowScreen = wallpaperSettings.setHomeWallpaper || wallpaperSettings.setLockWallpaper
val shouldShowSettings = shouldShowScreen && homeSelectedAlbum != null && lockSelectedAlbum != null
val scrollState = rememberScrollState()
val context = LocalContext.current
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val scrollState = rememberScrollState()
val snackbarHostState = remember { SnackbarHostState() }
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
val showInterval = rememberSaveable { mutableStateOf(false) }
val lock = rememberSaveable { mutableStateOf(false) }
val home = rememberSaveable { mutableStateOf(false) }
val lockSource = rememberSaveable { mutableStateOf(false) }
val homeSource = rememberSaveable { mutableStateOf(false) }
val handleAlbumSelection: (AlbumWithWallpaperAndFolder) -> Unit = { album ->
openBottomSheet = false
val alarmManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
ContextCompat.getSystemService(context, AlarmManager::class.java)
} else null
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && alarmManager?.canScheduleExactAlarms() == false -> {
context.startActivity(Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM))
}
else -> onSelectAlbum(album, lockSource.value, homeSource.value)
}
}
val showSnackBar: (String) -> Unit = { message ->
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = message,
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
}
Scaffold(
snackbarHost = {
@@ -121,207 +131,174 @@ fun WallpaperScreen(
snackbar = { data ->
Snackbar(
snackbarData = data,
modifier = Modifier.padding(PaddingValues(horizontal = 16.dp, vertical = 24.dp)),
modifier = Modifier.padding(horizontal = 16.dp, vertical = 24.dp),
shape = RoundedCornerShape(24.dp)
)
}
) },
modifier = Modifier
.fillMaxSize()
.semantics { testTagsAsResourceId = true },
content = { padding ->
Column(
modifier = Modifier
.verticalScroll(scrollState)
.fillMaxSize()
.padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
ChangerSelectionRow(
homeEnabled = homeEnabled,
lockEnabled = lockEnabled,
onHomeCheckedChange = onHomeCheckedChange,
onLockCheckedChange = onLockCheckedChange
)
},
modifier = Modifier.fillMaxSize()
) { it
Column (
modifier = Modifier
.fillMaxSize()
.padding(8.dp)
.verticalScroll(scrollState),
horizontalAlignment = Alignment.CenterHorizontally
) {
ChangerSelectionRow(
onHomeCheckedChange = onHomeCheckedChange,
onLockCheckedChange = onLockCheckedChange,
homeEnabled = wallpaperSettings.setHomeWallpaper,
lockEnabled = wallpaperSettings.setLockWallpaper
)
if (wallpaperSettings.setHomeWallpaper && wallpaperSettings.setLockWallpaper) {
IndividualSchedulingAndToggleRow(
onToggleChanger = onToggleChanger,
onScheduleSeparatelyChange = onScheduleSeparatelyChange,
scheduleSeparately = scheduleSettings.scheduleSeparately,
enableChanger = wallpaperSettings.enableChanger,
animate = themeSettings.animate
)
if (homeEnabled && lockEnabled) {
IndividualSchedulingAndToggleRow(
animate = animate,
scheduleSeparately = scheduleSeparately,
enableChanger = enableChanger,
onToggleChanger = onToggleChanger,
onScheduleSeparatelyChange = onScheduleSeparatelyChange
)
}
if (homeEnabled || lockEnabled) {
CurrentSelectedAlbum(
homeSelectedAlbum = homeSelectedAlbum,
lockSelectedAlbum = lockSelectedAlbum,
scheduleSeparately = scheduleSeparately,
animate = animate,
enableChanger = enableChanger,
onToggleChanger = {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
if (!it) {
snackbarHostState.showSnackbar(
message = context.getString(R.string.wallpaper_changer_has_been_disabled),
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
}
onToggleChanger(it)
},
onOpenBottomSheet = { changeLock, changeHome ->
if (albums.firstOrNull() != null) {
openBottomSheet = true
lock.value = changeLock
home.value = changeHome
} else {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = context.getString(R.string.no_albums_found),
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
}
},
onStop = { lock, home ->
if (homeSelectedAlbum != null || lockSelectedAlbum != null) {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = context.getString(
R.string.has_been_unselected,
when {
home && lock -> homeSelectedAlbum?.album?.displayedAlbumName ?: ""
home -> homeSelectedAlbum?.album?.displayedAlbumName ?: ""
lock -> lockSelectedAlbum?.album?.displayedAlbumName ?: ""
else -> ""
}
),
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
onStop(lock, home)
}
}
if (shouldShowScreen) {
CurrentSelectedAlbum(
homeSelectedAlbum = homeSelectedAlbum,
lockSelectedAlbum = lockSelectedAlbum,
onToggleChanger = {
if (!it) showSnackBar(context.getString(R.string.wallpaper_changer_has_been_disabled))
onToggleChanger(it)
},
onOpenBottomSheet = { changeLock, changeHome ->
if (albums.firstOrNull() != null) {
openBottomSheet = true
lockSource.value = changeLock
homeSource.value = changeHome
} else {
showSnackBar(context.getString(R.string.no_albums_found))
}
},
onDeselect = { lock, home ->
if (homeSelectedAlbum != null || lockSelectedAlbum != null) {
onDeselect(lock, home)
}
},
scheduleSeparately = scheduleSettings.scheduleSeparately,
enableChanger = wallpaperSettings.enableChanger,
animate = themeSettings.animate
)
if (shouldShowSettings) {
WallpaperPreviewAndScale(
currentHomeWallpaper = wallpaperSettings.currentHomeWallpaper,
currentLockWallpaper = wallpaperSettings.currentLockWallpaper,
scaling = wallpaperSettings.wallpaperScaling,
onScalingChange = onScalingChange,
homeBlurPercentage = effectSettings.homeBlurPercentage,
lockBlurPercentage = effectSettings.lockBlurPercentage,
homeDarkenPercentage = effectSettings.homeDarkenPercentage,
lockDarkenPercentage = effectSettings.lockDarkenPercentage,
homeVignettePercentage = effectSettings.homeVignettePercentage,
lockVignettePercentage = effectSettings.lockVignettePercentage,
homeGrayscalePercentage = effectSettings.homeGrayscalePercentage,
lockGrayscalePercentage = effectSettings.lockGrayscalePercentage,
homeEnabled = wallpaperSettings.setHomeWallpaper,
lockEnabled = wallpaperSettings.setLockWallpaper,
darken = effectSettings.darken,
blur = effectSettings.blur,
vignette = effectSettings.vignette,
grayscale = effectSettings.grayscale
)
CurrentAndNextChange(scheduleSettings.lastSetTime, scheduleSettings.nextSetTime)
TimeSliders(
homeInterval = scheduleSettings.homeInterval,
lockInterval = scheduleSettings.lockInterval,
startingTime = scheduleSettings.startTime,
onHomeIntervalChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onHomeTimeChange(totalMinutes)
},
onLockIntervalChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onLockTimeChange(totalMinutes)
},
onStartTimeChange = onStartTimeChange,
onShowIntervalChange = { showInterval.value = it },
onChangeStartTimeToggle = onChangeStartTimeToggle,
homeEnabled = wallpaperSettings.setHomeWallpaper,
lockEnabled = wallpaperSettings.setLockWallpaper,
showInterval = showInterval.value,
scheduleSeparately = scheduleSettings.scheduleSeparately,
changeStartTime = scheduleSettings.changeStartTime,
animate = themeSettings.animate
)
ShuffleSwitch(
shuffle = scheduleSettings.shuffle,
onShuffleCheck = { onShuffleCheck(it) },
)
DarkenSwitchAndSlider(
homeDarkenPercentage = effectSettings.homeDarkenPercentage,
lockDarkenPercentage = effectSettings.lockDarkenPercentage,
onDarkCheck = onDarkCheck,
onDarkenChange = onDarkenPercentage,
darken = effectSettings.darken,
animate = themeSettings.animate,
bothEnabled = wallpaperSettings.setHomeWallpaper && wallpaperSettings.setLockWallpaper
)
BlurSwitchAndSlider(
homeBlurPercentage = effectSettings.homeBlurPercentage,
lockBlurPercentage = effectSettings.lockBlurPercentage,
onBlurPercentageChange = onBlurPercentageChange,
onBlurChange = onBlurChange,
blur = effectSettings.blur,
animate = themeSettings.animate,
bothEnabled = wallpaperSettings.setHomeWallpaper && wallpaperSettings.setLockWallpaper
)
VignetteSwitchAndSlider(
homeVignettePercentage = effectSettings.homeVignettePercentage,
lockVignettePercentage = effectSettings.lockVignettePercentage,
onVignettePercentageChange = onVignettePercentageChange,
onVignetteChange = onVignetteChange,
vignette = effectSettings.vignette,
animate = themeSettings.animate,
bothEnabled = wallpaperSettings.setHomeWallpaper && wallpaperSettings.setLockWallpaper
)
GrayscaleSwitchAndSlider(
homeGrayscalePercentage = effectSettings.homeGrayscalePercentage,
lockGrayscalePercentage = effectSettings.lockGrayscalePercentage,
onGrayscalePercentageChange = onGrayscalePercentageChange,
onGrayscaleChange = onGrayscaleChange,
grayscale = effectSettings.grayscale,
animate = themeSettings.animate,
bothEnabled = wallpaperSettings.setHomeWallpaper && wallpaperSettings.setLockWallpaper
)
RefreshSwitch(
refresh = scheduleSettings.refresh,
onRefreshChange = onRefreshChange
)
SkipLandscapeSwitch(
skipLandscape = scheduleSettings.skipLandscape,
onSkipLandscapeChange = onSkipLandscapeChange
)
SkipNonInteractiveSwitch(
skipNonInteractive = scheduleSettings.skipNonInteractive,
onSkipNonInteractiveChange = onSkipNonInteractiveChange
)
if (shouldShowSettings) {
WallpaperPreviewAndScale(
currentHomeWallpaper = currentHomeWallpaper,
currentLockWallpaper = currentLockWallpaper,
darken = darken,
homeDarkenPercentage = homeDarkenPercentage,
lockDarkenPercentage = lockDarkenPercentage,
scaling = scaling,
onScalingChange = onScalingChange,
homeEnabled = homeEnabled,
lockEnabled = lockEnabled,
blur = blur,
homeBlurPercentage = homeBlurPercentage,
lockBlurPercentage = lockBlurPercentage,
vignette = vignette,
homeVignettePercentage = homeVignettePercentage,
lockVignettePercentage = lockVignettePercentage,
grayscale = grayscale,
homeGrayscalePercentage = homeGrayscalePercentage,
lockGrayscalePercentage = lockGrayscalePercentage
)
CurrentAndNextChange(lastSetTime, nextSetTime)
TimeSliders(
homeInterval = homeInterval,
lockInterval = lockInterval,
onHomeIntervalChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onHomeTimeChange(totalMinutes)
},
onLockIntervalChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onLockTimeChange(totalMinutes)
},
showInterval = showInterval.value,
animate = animate,
onShowIntervalChange = { showInterval.value = it },
scheduleSeparately = scheduleSeparately,
lockEnabled = lockEnabled,
homeEnabled = homeEnabled,
onStartTimeChange = onStartTimeChange,
changeStartTime = changeStartTime,
startingTime = startingTime,
onChangeStartTimeToggle = onChangeStartTimeToggle
)
DarkenSwitchAndSlider(
onDarkCheck = onDarkCheck,
darken = darken,
onDarkenChange = onDarkenPercentage,
homeDarkenPercentage = homeDarkenPercentage,
lockDarkenPercentage = lockDarkenPercentage,
animate = animate,
bothEnabled = homeEnabled && lockEnabled
)
BlurSwitchAndSlider(
onBlurPercentageChange = onBlurPercentageChange,
onBlurChange = onBlurChange,
blur = blur,
homeBlurPercentage = homeBlurPercentage,
lockBlurPercentage = lockBlurPercentage,
animate = animate,
bothEnabled = homeEnabled && lockEnabled
)
VignetteSwitchAndSlider(
onVignettePercentageChange = onVignettePercentageChange,
onVignetteChange = onVignetteChange,
vignette = vignette,
homeVignettePercentage = homeVignettePercentage,
lockVignettePercentage = lockVignettePercentage,
animate = animate,
bothEnabled = homeEnabled && lockEnabled
)
GrayscaleSwitchAndSlider(
onGrayscalePercentageChange = onGrayscalePercentageChange,
onGrayscaleChange = onGrayscaleChange,
grayscale = grayscale,
homeGrayscalePercentage = homeGrayscalePercentage,
lockGrayscalePercentage = lockGrayscalePercentage,
animate = animate,
bothEnabled = homeEnabled && lockEnabled
)
}
}
}
if (shouldShowScreen && openBottomSheet) {
AlbumBottomSheet(
albums = albums,
homeSelectedAlbum = homeSelectedAlbum,
lockSelectedAlbum = lockSelectedAlbum,
onSelect = handleAlbumSelection,
onDismiss = { openBottomSheet = false },
onSelect = { album ->
openBottomSheet = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val alarmManager = ContextCompat.getSystemService(context, AlarmManager::class.java)
if (alarmManager?.canScheduleExactAlarms() == false) {
Intent().also { intent ->
intent.action = Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM
context.startActivity(intent)
}
}
else {
onSelectAlbum(album, lock.value, home.value)
onScheduleWallpaperChanger()
}
}
else {
onSelectAlbum(album, lock.value, home.value)
onScheduleWallpaperChanger()
}
},
animate = animate
animate = themeSettings.animate
)
}
},
)
}
}
}
@@ -1,128 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class WallpaperScreenViewModel @Inject constructor (
application: Application,
private val repository: SelectedAlbumRepository,
) : AndroidViewModel(application) {
private var _state = MutableStateFlow(WallpaperState())
val state = _state.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000), WallpaperState()
)
init {
viewModelScope.launch(Dispatchers.IO) {
repository.getSelectedAlbum().collect { selectedAlbum ->
_state.update {
it.copy(
selectedAlbum = selectedAlbum,
isDataLoaded = true
)
}
}
}
}
fun onEvent(event: WallpaperEvent) {
when (event) {
is WallpaperEvent.AddSelectedAlbum -> {
viewModelScope.launch(Dispatchers.IO) {
val deleted = event.deleteAlbumName?.let {
repository.cascadeDeleteAlbum(it)
true
} ?: false
val wallpapers = event.album.wallpapers + event.album.folders.flatMap { folder ->
folder.wallpapers.map { wallpaper ->
Wallpaper(
initialAlbumName = event.album.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaper.hashCode() + event.album.album.initialAlbumName.hashCode() + System.currentTimeMillis().toInt(),
)
}
}
val newSelectedAlbum = SelectedAlbum(
album = event.album.album.copy(
lockWallpapersInQueue = wallpapers.map { it.wallpaperUri }.shuffled(),
homeWallpapersInQueue = wallpapers.map { it.wallpaperUri }.shuffled()
),
wallpapers = wallpapers
)
repository.upsertSelectedAlbum(newSelectedAlbum)
_state.update {
it.copy(
selectedAlbum = it.selectedAlbum?.let { selectedAlbums ->
selectedAlbums.filterNot { selectedAlbum -> deleted && selectedAlbum.album.initialAlbumName == event.deleteAlbumName } + newSelectedAlbum
}
)
}
}
}
is WallpaperEvent.UpdateSelectedAlbum -> {
viewModelScope.launch(Dispatchers.IO) {
repository.upsertSelectedAlbum(event.album)
_state.update {
it.copy(
selectedAlbum = it.selectedAlbum?.map { selectedAlbum ->
if (selectedAlbum.album.initialAlbumName == event.album.album.initialAlbumName) {
event.album
} else {
selectedAlbum
}
}
)
}
}
}
is WallpaperEvent.Refresh -> {
refreshAlbums()
}
is WallpaperEvent.Reset -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.album == null) {
repository.deleteAll()
_state.update {
it.copy(
selectedAlbum = null
)
}
}
else {
repository.cascadeDeleteAlbum(event.album.album.initialAlbumName)
_state.update {
it.copy(
selectedAlbum = it.selectedAlbum?.filter { selectedAlbum -> selectedAlbum.album.initialAlbumName != event.album.album.initialAlbumName }
)
}
}
}
}
}
}
// Retrieve album from database into viewModel
private fun refreshAlbums() {
viewModelScope.launch(Dispatchers.IO) {
repository.getSelectedAlbum().collect { selectedAlbum ->
_state.update { it.copy(
selectedAlbum = selectedAlbum,
) }
}
}
}
}
@@ -1,8 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
data class WallpaperState (
val isDataLoaded: Boolean = false,
val selectedAlbum: List<SelectedAlbum>? = null
)
@@ -3,13 +3,17 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.c
import android.os.Build
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.RadioButtonChecked
@@ -35,9 +39,9 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
import kotlinx.coroutines.launch
@@ -48,97 +52,113 @@ import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlbumBottomSheet(
onDismiss: () -> Unit,
homeSelectedAlbum: SelectedAlbum?,
lockSelectedAlbum: SelectedAlbum?,
homeSelectedAlbum: AlbumWithWallpaperAndFolder?,
lockSelectedAlbum: AlbumWithWallpaperAndFolder?,
albums: List<AlbumWithWallpaperAndFolder>,
animate: Boolean,
onSelect: (AlbumWithWallpaperAndFolder) -> Unit,
animate: Boolean
onDismiss: () -> Unit,
) {
val modalBottomSheetState = rememberModalBottomSheetState()
val scope = rememberCoroutineScope()
val context = LocalContext.current
val navigationBarPadding = WindowInsets.navigationBars
.asPaddingValues()
.calculateBottomPadding()
val sheetModifier = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
Modifier
.fillMaxSize()
.padding(bottom = navigationBarPadding)
} else {
Modifier.padding(bottom = navigationBarPadding)
}
ModalBottomSheet(
onDismissRequest = { onDismiss() },
onDismissRequest = onDismiss,
sheetState = modalBottomSheetState,
dragHandle = { BottomSheetDefaults.DragHandle() },
containerColor = MaterialTheme.colorScheme.background,
tonalElevation = 5.dp,
modifier = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
Modifier
.fillMaxSize()
.padding(
bottom = WindowInsets.navigationBars
.asPaddingValues()
.calculateBottomPadding()
)
} else {
Modifier.padding(bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding())
}
modifier = sheetModifier
) {
albums.forEach {
if (it.folders.sumOf { folder -> folder.wallpapers.size } + it.wallpapers.size == 0) return@forEach
ListItem(
modifier = Modifier
.clickable {
val scrollState = rememberScrollState()
Column(
modifier = Modifier
.wrapContentHeight()
.verticalScroll(scrollState)
) {
albums.forEach { album ->
val totalWallpapers = album.folders.sumOf { it.wallpapers.size } + album.wallpapers.size
if (totalWallpapers == 0) return@forEach
val isSelected = (homeSelectedAlbum?.album?.initialAlbumName == album.album.initialAlbumName) ||
(lockSelectedAlbum?.album?.displayedAlbumName == album.album.displayedAlbumName)
ListItem(
modifier = Modifier.clickable {
scope.launch {
modalBottomSheetState.hide()
onSelect(it)
onDismiss()
}
onSelect(album)
onDismiss()
},
headlineContent = {
Text(
text = album.album.displayedAlbumName,
style = MaterialTheme.typography.titleMedium
)
},
supportingContent = {
Text(
text = context.resources.getQuantityString(
R.plurals.wallpaper_count,
totalWallpapers,
totalWallpapers
),
style = MaterialTheme.typography.bodySmall,
overflow = TextOverflow.Ellipsis
)
},
leadingContent = {
Box(modifier = Modifier.size(60.dp)) {
if (isValidUri(context, album.album.coverUri)) {
GlideImage(
imageModel = { album.album.coverUri?.decompress("content://com.android.externalstorage.documents/") },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150)
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
}
}
},
headlineContent = {
Text(
text = it.album.displayedAlbumName,
style = MaterialTheme.typography.titleMedium
) },
supportingContent = {
val totalWallpapers = it.folders.sumOf { folder -> folder.wallpapers.size } + it.wallpapers.size
Text(
text = LocalContext.current.resources.getQuantityString(R.plurals.wallpaper_count, totalWallpapers, totalWallpapers),
style = MaterialTheme.typography.bodySmall,
overflow = TextOverflow.Ellipsis
)
},
leadingContent = {
Box (
modifier = Modifier.size(60.dp)
) {
val showCoverUri = isValidUri(LocalContext.current, it.album.coverUri)
if (showCoverUri) {
GlideImage(
imageModel = { it.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(
Alignment.Center
)
)
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
trailingContent = {
Icon(
imageVector = if (isSelected) Icons.Filled.RadioButtonChecked
else Icons.Filled.RadioButtonUnchecked,
contentDescription = stringResource(
if (isSelected) R.string.currently_selected_album
else R.string.unselected_album
)
}
)
}
},
trailingContent = {
val isSelected = (homeSelectedAlbum?.album?.initialAlbumName == it.album.initialAlbumName) ||
(lockSelectedAlbum?.album?.displayedAlbumName == it.album.displayedAlbumName)
Icon(
contentDescription = if (isSelected) stringResource(R.string.currently_selected_album) else stringResource(R.string.unselected_album),
imageVector = if (isSelected) Icons.Filled.RadioButtonChecked else Icons.Filled.RadioButtonUnchecked,
)
},
)
)
}
}
}
}
}
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
@@ -18,7 +19,9 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
@@ -71,159 +74,191 @@ fun BlurSwitchAndSlider(
val columnModifier = if (animate) {
Modifier.animateContentSize(animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing))
} else { Modifier }
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = columnModifier
Column(
modifier = columnModifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row (horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(R.string.change_blur),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.change_blur),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (!blur) {
Text(
text = stringResource(R.string.add_blur_to_the_image),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Switch(
checked = blur,
onCheckedChange = onBlurChange
)
}
if (animate) {
AnimatedVisibility(
visible = blur,
enter = expandVertically(animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)),
exit = fadeOut(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
)
) {
Column {
Spacer(modifier = Modifier.height(8.dp))
// Show sliders when blur is enabled, regardless of animation setting
if (blur) {
val sliderContent = @Composable {
Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
text = stringResource(R.string.home_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onBlurPercentageChange(it.roundToInt(), lockPercentage.roundToInt())
} else {
onBlurPercentageChange(it.roundToInt(), it.roundToInt())
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = {
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
homePercentage = value
job?.cancel()
job = scope.launch {
delay(500)
onBlurPercentageChange(homePercentage.roundToInt(), it.roundToInt())
delay(100)
onBlurPercentageChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.lock_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${lockPercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = value
job?.cancel()
job = scope.launch {
delay(100)
onBlurPercentageChange(homePercentage.roundToInt(), value.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
} else {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = value
job?.cancel()
job = scope.launch {
delay(100)
onBlurPercentageChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
} else {
if (blur) {
Column {
Spacer(modifier = Modifier.height(8.dp))
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
if (animate) {
AnimatedVisibility(
visible = blur,
enter = expandVertically(animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)),
exit = fadeOut(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onBlurPercentageChange(it.roundToInt(), lockPercentage.roundToInt())
} else {
onBlurPercentageChange(it.roundToInt(), it.roundToInt())
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Spacer(modifier = Modifier.height(16.dp))
Slider(
value = lockPercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
job?.cancel()
job = scope.launch {
delay(500)
onBlurPercentageChange(homePercentage.roundToInt(), it.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
}
Spacer(modifier = Modifier.height(16.dp))
) {
sliderContent()
}
} else {
sliderContent()
}
}
}
}
}
}
@@ -9,8 +9,8 @@ import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
@@ -30,17 +30,23 @@ fun ChangerSelectionRow(
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2),
onCheckedChange = onLockCheckedChange,
checked = lockEnabled,
modifier = Modifier.testTag("paperize:lock_button"),
) {
Text(stringResource(R.string.lock_screen_btn))
Text(
stringResource(R.string.lock_screen_btn),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2),
onCheckedChange = onHomeCheckedChange,
checked = homeEnabled,
modifier = Modifier.testTag("paperize:home_button"),
) {
Text(text = stringResource(R.string.home_screen_btn))
Text(
text = stringResource(R.string.home_screen_btn),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
@@ -98,7 +98,7 @@ fun CurrentAndNextChange(
Text(parts[1], style = textSecond, modifier = Modifier.align(Alignment.CenterHorizontally))
}
else if (parts.size == 3) {
Text(stringResource(R.string.last_change), style = textFirst, modifier = Modifier.align(Alignment.CenterHorizontally))
Text(stringResource(R.string.next_change), style = textFirst, modifier = Modifier.align(Alignment.CenterHorizontally))
Text(parts[0].replace(',', ' '), style = textSecond, modifier = Modifier.align(Alignment.CenterHorizontally))
Text(parts[1] + ' ' + parts[2], style = textSecond, modifier = Modifier.align(Alignment.CenterHorizontally))
}
@@ -1,16 +1,14 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -37,196 +35,127 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
/**
* The inner card for the album bottom sheet to represent each album
*/
@Composable
fun CurrentSelectedAlbum(
homeSelectedAlbum: SelectedAlbum?,
lockSelectedAlbum: SelectedAlbum?,
homeSelectedAlbum: AlbumWithWallpaperAndFolder?,
lockSelectedAlbum: AlbumWithWallpaperAndFolder?,
scheduleSeparately: Boolean,
enableChanger: Boolean,
animate: Boolean,
onOpenBottomSheet: (Boolean, Boolean) -> Unit, // lock, home
onStop: (Boolean, Boolean) -> Unit,
onOpenBottomSheet: (lock: Boolean, home: Boolean) -> Unit,
onDeselect: (lock: Boolean, home: Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit
) {
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
}
true
} catch (e: Exception) { false }
val context = LocalContext.current
val showHomeCoverUri = isValidUri(context, homeSelectedAlbum?.album?.coverUri)
val showLockCoverUri = isValidUri(context, lockSelectedAlbum?.album?.coverUri)
val baseListItemModifier = { horizontal: Int ->
Modifier
.padding(PaddingValues(vertical = 4.dp, horizontal = horizontal.dp))
.clip(RoundedCornerShape(16.dp))
}
val showHomeCoverUri = isValidUri(LocalContext.current, homeSelectedAlbum?.album?.coverUri)
val showLockCoverUri = isValidUri(LocalContext.current, lockSelectedAlbum?.album?.coverUri)
val albumImage = @Composable { album: AlbumWithWallpaperAndFolder?, showCoverUri: Boolean, size: Int ->
Box(modifier = Modifier.size(size.dp)) {
if (album != null && showCoverUri) {
GlideImage(
imageModel = { album.album.coverUri?.decompress("content://com.android.externalstorage.documents/") },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
}
}
if (scheduleSeparately) {
Row {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
// Lock screen album
ListItem(
modifier = Modifier
.padding(PaddingValues(top = 8.dp, bottom = 8.dp, start = 16.dp, end = 8.dp))
modifier = baseListItemModifier(16)
.weight(1f)
.clip(RoundedCornerShape(16.dp))
.clickable { onOpenBottomSheet(true, false) },
headlineContent = {
Row(modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.SpaceBetween) {
Box (modifier = Modifier.weight(1f)) {
Box(modifier = Modifier.weight(1f)) {
if (lockSelectedAlbum != null) {
IconButton(
onClick = { onStop(true, false) }
) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.stop_the_album)
)
IconButton(onClick = { onDeselect(true, false) }) {
Icon(Icons.Default.Stop, stringResource(R.string.stop_the_album))
}
}
}
Spacer(modifier = Modifier.size(8.dp))
Box (modifier = Modifier.weight(1f)) {
IconButton(
onClick = { onOpenBottomSheet(true, false) }
) {
Icon(
contentDescription = stringResource(R.string.click_to_select_a_different_album),
imageVector = Icons.Filled.ArrowDropDown,
)
Box(modifier = Modifier.weight(1f)) {
IconButton(onClick = { onOpenBottomSheet(true, false) }) {
Icon(Icons.Filled.ArrowDropDown, stringResource(R.string.click_to_select_a_different_album))
}
}
}
},
leadingContent = { albumImage(lockSelectedAlbum, showLockCoverUri, 48) },
supportingContent = {},
leadingContent = {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Box(modifier = Modifier.size(48.dp)) {
if (lockSelectedAlbum != null) {
if (showLockCoverUri) {
GlideImage(
imageModel = { lockSelectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(
Alignment.Center
)
)
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
}
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
}
}
},
trailingContent = {},
tonalElevation = 10.dp
)
// Home screen album
ListItem(
modifier = Modifier
.padding(PaddingValues(top = 8.dp, bottom = 8.dp, start = 8.dp, end = 16.dp))
modifier = baseListItemModifier(16)
.weight(1f)
.clip(RoundedCornerShape(16.dp))
.clickable { onOpenBottomSheet(false, true) },
headlineContent = {
Row(modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.SpaceBetween) {
Box (modifier = Modifier.weight(1f)) {
Box(modifier = Modifier.weight(1f)) {
if (homeSelectedAlbum != null) {
IconButton(onClick = { onStop(false, true) }) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.stop_the_album)
)
IconButton(onClick = { onDeselect(false, true) }) {
Icon(Icons.Default.Stop, stringResource(R.string.stop_the_album))
}
}
}
Spacer(modifier = Modifier.size(8.dp))
Box (modifier = Modifier.weight(1f)) {
Box(modifier = Modifier.weight(1f)) {
IconButton(onClick = { onOpenBottomSheet(false, true) }) {
Icon(
contentDescription = stringResource(R.string.click_to_select_a_different_album),
imageVector = Icons.Filled.ArrowDropDown,
)
Icon(Icons.Filled.ArrowDropDown, stringResource(R.string.click_to_select_a_different_album))
}
}
}
},
leadingContent = { albumImage(homeSelectedAlbum, showHomeCoverUri, 48) },
supportingContent = {},
leadingContent = {
Box(modifier = Modifier.size(48.dp)) {
if (homeSelectedAlbum != null) {
if (showHomeCoverUri) {
GlideImage(
imageModel = { homeSelectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(
Alignment.Center
)
)
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
}
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
}
},
trailingContent = {
},
trailingContent = {},
tonalElevation = 10.dp
)
}
}
else {
} else {
ListItem(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.clip(RoundedCornerShape(16.dp))
.clickable { onOpenBottomSheet(true, true) },
modifier = baseListItemModifier(16).clickable { onOpenBottomSheet(true, true) },
headlineContent = {
Text(
text = homeSelectedAlbum?.album?.displayedAlbumName ?: stringResource(R.string.no_album_selected),
@@ -236,82 +165,37 @@ fun CurrentSelectedAlbum(
)
},
supportingContent = {
if (homeSelectedAlbum != null) {
homeSelectedAlbum?.let {
Text(
text = LocalContext.current.resources.getQuantityString(
text = context.resources.getQuantityString(
R.plurals.wallpaper_count,
homeSelectedAlbum.wallpapers.size,
homeSelectedAlbum.wallpapers.size
it.folders.sumOf { folder -> folder.wallpapers.size } + it.wallpapers.size,
it.folders.sumOf { folder -> folder.wallpapers.size } + it.wallpapers.size
),
style = MaterialTheme.typography.bodySmall,
overflow = TextOverflow.Ellipsis
)
}
},
leadingContent = {
Box(modifier = Modifier.size(60.dp)) {
if (homeSelectedAlbum != null) {
if (showHomeCoverUri) {
GlideImage(
imageModel = { homeSelectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(
Alignment.Center
)
)
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
}
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
}
},
leadingContent = { albumImage(homeSelectedAlbum, showHomeCoverUri, 60) },
trailingContent = {
Row(
horizontalArrangement = Arrangement.spacedBy((-8).dp),
verticalAlignment = Alignment.CenterVertically
) {
if (homeSelectedAlbum != null) {
IconButton(onClick = { onStop(true, true) }) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.stop_the_album)
)
IconButton(onClick = { onDeselect(true, true) }) {
Icon(Icons.Default.Stop, stringResource(R.string.stop_the_album))
}
}
IconButton(onClick = { onOpenBottomSheet(true, true) }) {
Icon(
contentDescription = stringResource(R.string.click_to_select_a_different_album),
imageVector = Icons.Filled.ArrowDropDown,
)
}
if (homeSelectedAlbum != null) {
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger,
modifier = Modifier
.rotate(270f)
.scale(0.75f)
modifier = Modifier.rotate(270f).scale(0.75f)
)
}
IconButton(onClick = { onOpenBottomSheet(true, true) }) {
Icon(Icons.Filled.ArrowDropDown, stringResource(R.string.click_to_select_a_different_album))
}
}
},
tonalElevation = 10.dp
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
@@ -18,7 +19,9 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
@@ -71,17 +74,31 @@ fun DarkenSwitchAndSlider(
val columnModifier = if (animate) {
Modifier.animateContentSize(animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing))
} else { Modifier }
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = columnModifier
Column(
modifier = columnModifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row (horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(R.string.change_brightness),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.change_brightness),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (!darken) {
Text(
text = stringResource(R.string.change_the_image_brightness),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Switch(
checked = darken,
onCheckedChange = onDarkCheck
@@ -98,130 +115,135 @@ fun DarkenSwitchAndSlider(
)
)
) {
Column {
Spacer(modifier = Modifier.height(8.dp))
Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onDarkenChange(it.roundToInt(), lockPercentage.roundToInt())
}
else {
onDarkenChange(it.roundToInt(), it.roundToInt())
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Spacer(modifier = Modifier.height(16.dp))
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
text = stringResource(R.string.home_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = {
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
homePercentage = value
job?.cancel()
job = scope.launch {
delay(500)
onDarkenChange(homeDarkenPercentage, it.roundToInt())
delay(100)
onDarkenChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
} else {
if (darken) {
Column {
Spacer(modifier = Modifier.height(8.dp))
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onDarkenChange(it.roundToInt(), lockPercentage.roundToInt())
}
else {
onDarkenChange(it.roundToInt(), it.roundToInt())
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Spacer(modifier = Modifier.height(16.dp))
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.lock_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${lockPercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = {
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
lockPercentage = value
job?.cancel()
job = scope.launch {
delay(500)
onDarkenChange(homeDarkenPercentage, it.roundToInt())
delay(100)
onDarkenChange(homePercentage.roundToInt(), value.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
} else {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = value
job?.cancel()
job = scope.launch {
delay(100)
onDarkenChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
@@ -18,7 +19,9 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
@@ -71,17 +74,31 @@ fun GrayscaleSwitchAndSlider(
val columnModifier = if (animate) {
Modifier.animateContentSize(animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing))
} else { Modifier }
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = columnModifier
Column(
modifier = columnModifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row (horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(R.string.gray_filter),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.gray_filter),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (!grayscale) {
Text(
text = stringResource(R.string.make_the_colors_grayscale),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Switch(
checked = grayscale,
onCheckedChange = onGrayscaleChange
@@ -98,132 +115,138 @@ fun GrayscaleSwitchAndSlider(
)
)
) {
Column {
Spacer(modifier = Modifier.height(8.dp))
Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
text = stringResource(R.string.home_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onGrayscalePercentageChange(it.roundToInt(), lockPercentage.roundToInt())
} else {
onGrayscalePercentageChange(it.roundToInt(), it.roundToInt())
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = {
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
homePercentage = value
job?.cancel()
job = scope.launch {
delay(500)
onGrayscalePercentageChange(homePercentage.roundToInt(), it.roundToInt())
delay(100)
onGrayscalePercentageChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
} else {
if (grayscale) {
Column {
Spacer(modifier = Modifier.height(8.dp))
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onGrayscalePercentageChange(it.roundToInt(), lockPercentage.roundToInt())
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
onGrayscalePercentageChange(it.roundToInt(), it.roundToInt())
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Spacer(modifier = Modifier.height(16.dp))
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.lock_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${lockPercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = {
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
lockPercentage = value
job?.cancel()
job = scope.launch {
delay(500)
onGrayscalePercentageChange(homePercentage.roundToInt(), it.roundToInt())
delay(100)
onGrayscalePercentageChange(homePercentage.roundToInt(), value.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
} else {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = value
job?.cancel()
job = scope.launch {
delay(100)
onGrayscalePercentageChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
}
}
}
@@ -10,7 +10,6 @@ import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
@@ -25,13 +24,15 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
private val HorizontalPadding = 32.dp
private val VerticalPadding = 8.dp
/**
* Composable to toggle individual scheduling settings and toggle wallpaper changer when scheduling separately
*/
@@ -39,7 +40,7 @@ import com.anthonyla.paperize.R
fun IndividualSchedulingAndToggleRow(
animate: Boolean,
scheduleSeparately: Boolean,
enableChanger : Boolean,
enableChanger: Boolean,
onToggleChanger: (Boolean) -> Unit,
onScheduleSeparatelyChange: (Boolean) -> Unit,
) {
@@ -51,7 +52,7 @@ fun IndividualSchedulingAndToggleRow(
stiffness = Spring.StiffnessLow
)
)
} else { Modifier }
} else Modifier
}
Surface(
@@ -59,83 +60,79 @@ fun IndividualSchedulingAndToggleRow(
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
.padding(horizontal = 16.dp, vertical = VerticalPadding)
) {
Column(
modifier = columnModifier
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 32.dp, end = 32.dp, top = 8.dp, bottom = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.individual_scheduling),
fontWeight = FontWeight.W500,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Spacer(modifier = Modifier.padding(8.dp))
Switch(
checked = scheduleSeparately,
onCheckedChange = onScheduleSeparatelyChange,
modifier = Modifier.testTag("paperize:individual_scheduling_switch"),
)
}
if (animate) {
AnimatedVisibility(
visible = scheduleSeparately,
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp)) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline, thickness = 2.dp)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 32.dp, end = 32.dp, top = 8.dp, bottom = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
Column(modifier = columnModifier) {
SettingsRow(
text = stringResource(R.string.individual_scheduling),
checked = scheduleSeparately,
onCheckedChange = onScheduleSeparatelyChange
)
if (scheduleSeparately) {
if (animate) {
AnimatedVisibility(
visible = true,
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
Text(
text = stringResource(R.string.enable_wallpaper_changer),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger
)
}
}
}
else {
if (scheduleSeparately) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.enable_wallpaper_changer),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger
)
ChangerToggleSection(enableChanger, onToggleChanger)
}
} else {
ChangerToggleSection(enableChanger, onToggleChanger)
}
}
}
}
}
@Composable
private fun SettingsRow(
text: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
start = HorizontalPadding,
end = HorizontalPadding,
top = VerticalPadding,
bottom = VerticalPadding
),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = text,
fontWeight = FontWeight.W500,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Spacer(modifier = Modifier.padding(VerticalPadding))
Switch(
checked = checked,
onCheckedChange = onCheckedChange
)
}
}
@Composable
private fun ChangerToggleSection(
enableChanger: Boolean,
onToggleChanger: (Boolean) -> Unit
) {
HorizontalDivider(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp),
color = MaterialTheme.colorScheme.outline,
thickness = 2.dp
)
SettingsRow(
text = stringResource(R.string.enable_wallpaper_changer),
checked = enableChanger,
onCheckedChange = onToggleChanger
)
}
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.size
@@ -18,10 +19,14 @@ import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.times
import androidx.core.net.toUri
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.VignetteBitmapTransformation
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.isValidUri
import com.bumptech.glide.request.RequestOptions
import com.skydoves.landscapist.ImageOptions
@@ -30,6 +35,7 @@ import com.skydoves.landscapist.glide.GlideImage
/**
* A composable that displays a wallpaper for preview
*/
@SuppressLint("ConfigurationScreenWidthHeight")
@Composable
fun PreviewItem(
wallpaperUri: String,
@@ -49,8 +55,9 @@ fun PreviewItem(
val screenWidth = configuration.screenWidthDp.dp
val screenHeight = configuration.screenHeightDp.dp
if (showUri) {
val uri = wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri()
GlideImage(
imageModel = { wallpaperUri },
imageModel = { uri },
imageOptions = ImageOptions(
contentScale = when (scaling) {
ScalingConstants.FILL -> ContentScale.FillHeight
@@ -0,0 +1,64 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
/**
* Composable that toggles whether to allow album refresh (24 hrs)
*/
@Composable
fun RefreshSwitch(
refresh: Boolean,
onRefreshChange: (Boolean) -> Unit,
) {
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.periodic_refresh),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
Text(
text = stringResource(R.string.check_folders_for_new_wallpapers),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch(
checked = refresh,
onCheckedChange = onRefreshChange
)
}
}
}
@@ -0,0 +1,61 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
@Composable
fun ShuffleSwitch(
shuffle: Boolean,
onShuffleCheck: (Boolean) -> Unit
) {
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.shuffle),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
Text(
text = stringResource(R.string.shuffle_the_wallpapers),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch(
checked = shuffle,
onCheckedChange = onShuffleCheck
)
}
}
}
@@ -0,0 +1,61 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
@Composable
fun SkipLandscapeSwitch(
skipLandscape: Boolean,
onSkipLandscapeChange: (Boolean) -> Unit
) {
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.skip_landscape_mode),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
Text(
text = stringResource(R.string.prevent_changing_during_landscape_mode),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch(
checked = skipLandscape,
onCheckedChange = onSkipLandscapeChange
)
}
}
}
@@ -0,0 +1,61 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
@Composable
fun SkipNonInteractiveSwitch(
skipNonInteractive: Boolean,
onSkipNonInteractiveChange: (Boolean) -> Unit
) {
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.skip_non_interactive_state),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
Text(
text = stringResource(R.string.prevent_changing_during_non_interactive_state),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch(
checked = skipNonInteractive,
onCheckedChange = onSkipNonInteractiveChange
)
}
}
}
@@ -23,16 +23,21 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.TimePickerDefaults
import androidx.compose.material3.TimePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
@@ -108,10 +113,16 @@ fun TimeSliders(
) {
Surface(
shape = MaterialTheme.shapes.large,
tonalElevation = 5.dp,
tonalElevation = 8.dp,
modifier = Modifier
.width(IntrinsicSize.Min)
.height(IntrinsicSize.Min)
.animateContentSize(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
) {
Column(
modifier = Modifier.padding(24.dp),
@@ -122,23 +133,54 @@ fun TimeSliders(
.fillMaxWidth()
.padding(bottom = 24.dp),
text = stringResource(R.string.select_starting_time),
style = MaterialTheme.typography.labelMedium
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface
)
TimePicker(
state = timePickerState,
colors = TimePickerDefaults.colors(
clockDialColor = MaterialTheme.colorScheme.primaryContainer,
clockDialSelectedContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
clockDialUnselectedContentColor = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.6f),
selectorColor = MaterialTheme.colorScheme.primary,
containerColor = MaterialTheme.colorScheme.surface,
periodSelectorBorderColor = MaterialTheme.colorScheme.outline,
periodSelectorSelectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
periodSelectorUnselectedContainerColor = MaterialTheme.colorScheme.surface,
periodSelectorSelectedContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
periodSelectorUnselectedContentColor = MaterialTheme.colorScheme.onSurface,
timeSelectorSelectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
timeSelectorUnselectedContainerColor = MaterialTheme.colorScheme.surface,
timeSelectorSelectedContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
timeSelectorUnselectedContentColor = MaterialTheme.colorScheme.onSurface
)
)
TimePicker(state = timePickerState)
Spacer(modifier = Modifier.height(24.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Button(
onClick = { shouldShowDialog.value = false }
onClick = { shouldShowDialog.value = false },
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
) { Text(stringResource(R.string.dismiss)) }
Button(
onClick = { onStartTimeChange(timePickerState); shouldShowDialog.value = false }
onClick = { onStartTimeChange(timePickerState); shouldShowDialog.value = false },
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) { Text(stringResource(R.string.confirm)) }
}
Button(
onClick = { onChangeStartTimeToggle(false); shouldShowDialog.value = false }
Spacer(modifier = Modifier.height(16.dp))
TextButton(
onClick = { onChangeStartTimeToggle(false); shouldShowDialog.value = false },
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.primary
)
) { Text(stringResource(R.string.reset_to_default)) }
}
}
@@ -277,7 +319,26 @@ fun TimeSliders(
)
)
) {
Column {
Column(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
) {
// Days Slider
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.days_txt),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = days1.toInt().toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = days1,
onValueChange = { newDays ->
@@ -301,9 +362,31 @@ fun TimeSliders(
},
valueRange = 0f..30f,
steps = 30,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
)
)
Spacer(modifier = Modifier.height(16.dp))
// Hours Slider
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.hours_txt),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = hours1.toInt().toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = hours1,
onValueChange = { newHours ->
@@ -327,9 +410,31 @@ fun TimeSliders(
},
valueRange = 0f..24f,
steps = 24,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
)
)
Spacer(modifier = Modifier.height(16.dp))
// Minutes Slider
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.minutes_txt),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = minutes1.toInt().toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = minutes1,
onValueChange = { newMinutes ->
@@ -352,8 +457,13 @@ fun TimeSliders(
},
valueRange = 0f..60f,
steps = 60,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
)
)
if (homeEnabled && lockEnabled) {
AnimatedVisibility(
visible = scheduleSeparately,
@@ -385,6 +495,23 @@ fun TimeSliders(
text = formattedTime2,
fontWeight = FontWeight.W500,
)
// Days Slider
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.days_txt),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = days2.toInt().toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = days2,
onValueChange = { newDays ->
@@ -408,9 +535,31 @@ fun TimeSliders(
},
valueRange = 0f..30f,
steps = 30,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
)
)
Spacer(modifier = Modifier.height(16.dp))
// Hours Slider
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.hours_txt),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = hours2.toInt().toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = hours2,
onValueChange = { newHours ->
@@ -434,9 +583,31 @@ fun TimeSliders(
},
valueRange = 0f..24f,
steps = 24,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
)
)
Spacer(modifier = Modifier.height(16.dp))
// Minutes Slider
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.minutes_txt),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = minutes2.toInt().toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = minutes2,
onValueChange = { newMinutes ->
@@ -459,31 +630,64 @@ fun TimeSliders(
},
valueRange = 0f..60f,
steps = 60,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
)
)
}
}
}
Button(
onClick = {
shouldShowDialog.value = true
},
onClick = { shouldShowDialog.value = true },
modifier = Modifier
.padding(16.dp)
.padding(12.dp)
.align(Alignment.CenterHorizontally)
.then(
if (animate) {
Modifier.animateContentSize(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
} else {
Modifier
}
),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
),
shape = RoundedCornerShape(16.dp)
) {
val (hour, minute, period) = if (changeStartTime) {
val hour = if (timePickerState.hour == 0) 12 else timePickerState.hour % 12
val period = if (timePickerState.hour < 12) "AM" else "PM"
Triple(hour, timePickerState.minute, period)
} else {
val currentTime = Calendar.getInstance()
val hour = if (currentTime.get(Calendar.HOUR) == 0) 12 else currentTime.get(Calendar.HOUR) % 12
val period = if (currentTime.get(Calendar.AM_PM) == 0) "AM" else "PM"
Triple(hour, currentTime.get(Calendar.MINUTE), period)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
modifier = Modifier.padding(end = 8.dp)
)
val (hour, minute, period) = if (changeStartTime) {
val hour = if (timePickerState.hour == 0) 12 else timePickerState.hour % 12
val period = if (timePickerState.hour < 12) "AM" else "PM"
Triple(hour, timePickerState.minute, period)
} else {
val currentTime = Calendar.getInstance()
val hour = if (currentTime.get(Calendar.HOUR) == 0) 12 else currentTime.get(Calendar.HOUR) % 12
val period = if (currentTime.get(Calendar.AM_PM) == 0) "AM" else "PM"
Triple(hour, currentTime.get(Calendar.MINUTE), period)
}
val formattedMinutes = String.format(Locale.getDefault(), "%02d", minute)
Text(
text = "$hour:$formattedMinutes $period",
style = MaterialTheme.typography.titleMedium
)
}
val formattedMinutes = String.format(Locale.getDefault(), "%02d", minute)
Text(text = "$hour:$formattedMinutes $period")
}
}
}
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
@@ -18,7 +19,9 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
@@ -71,17 +74,31 @@ fun VignetteSwitchAndSlider(
val columnModifier = if (animate) {
Modifier.animateContentSize(animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing))
} else { Modifier }
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = columnModifier
Column(
modifier = columnModifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row (horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(R.string.change_vignette),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = stringResource(R.string.change_vignette),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (!vignette) {
Text(
text = stringResource(R.string.darken_the_edges_of_the_image),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Switch(
checked = vignette,
onCheckedChange = onVignetteChange
@@ -98,128 +115,135 @@ fun VignetteSwitchAndSlider(
)
)
) {
Column {
Spacer(modifier = Modifier.height(8.dp))
Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
text = stringResource(R.string.home_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onVignettePercentageChange(it.roundToInt(), lockPercentage.roundToInt())
} else {
onVignettePercentageChange(it.roundToInt(), it.roundToInt())
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = {
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
homePercentage = value
job?.cancel()
job = scope.launch {
delay(500)
onVignettePercentageChange(homePercentage.roundToInt(), it.roundToInt())
delay(100)
onVignettePercentageChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
} else {
if (vignette) {
Column {
Spacer(modifier = Modifier.height(8.dp))
if (bothEnabled) {
Text(
text = stringResource(R.string.home_screen) + " | " + stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
else {
Text(
text = stringResource(R.string.percentage, homePercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
}
Slider(
value = homePercentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = it
job?.cancel()
job = scope.launch {
delay(500)
if (bothEnabled) {
onVignettePercentageChange(it.roundToInt(), lockPercentage.roundToInt())
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
onVignettePercentageChange(it.roundToInt(), it.roundToInt())
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (bothEnabled) {
Text(
text = stringResource(R.string.lock) + " | " + stringResource(R.string.percentage, lockPercentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Spacer(modifier = Modifier.height(16.dp))
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.lock_screen),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${lockPercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = lockPercentage,
onValueChange = {
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
lockPercentage = it
lockPercentage = value
job?.cancel()
job = scope.launch {
delay(500)
onVignettePercentageChange(homePercentage.roundToInt(), it.roundToInt())
delay(100)
onVignettePercentageChange(homePercentage.roundToInt(), value.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
} else {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${homePercentage.roundToInt()}%",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Slider(
value = homePercentage,
onValueChange = { value ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
homePercentage = value
job?.cancel()
job = scope.launch {
delay(100)
onVignettePercentageChange(value.roundToInt(), lockPercentage.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
inactiveTrackColor = MaterialTheme.colorScheme.primaryContainer
),
onValueChangeFinished = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
} else {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@@ -4,14 +4,12 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
@@ -76,60 +74,111 @@ fun WallpaperPreviewAndScale(
)
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
tonalElevation = 8.dp,
shape = RoundedCornerShape(24.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
.padding(PaddingValues(horizontal = 16.dp, vertical = 12.dp))
) {
Column (
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.padding(vertical = 16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
val modifier = if (lockEnabled && homeEnabled) {
Modifier
.weight(1f)
.padding(8.dp)
} else {
Modifier
.fillMaxSize(0.5f)
.padding(8.dp)
}
if (lockEnabled) {
if (lockEnabled && homeEnabled) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center
modifier = Modifier.weight(1f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(text = stringResource(R.string.lock_screen), fontWeight = FontWeight.W500)
Text(
text = stringResource(R.string.lock_screen),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (currentLockWallpaper != null) {
PreviewItem(
wallpaperUri = currentLockWallpaper,
darken = darken,
darkenPercentage = if (!homeEnabled) homeDarkenPercentage else lockDarkenPercentage,
darkenPercentage = lockDarkenPercentage,
scaling = scaling,
blur = blur,
blurPercentage = if (!homeEnabled) homeBlurPercentage else lockBlurPercentage,
blurPercentage = lockBlurPercentage,
vignette = vignette,
vignettePercentage = if (!homeEnabled) homeVignettePercentage else lockVignettePercentage,
vignettePercentage = lockVignettePercentage,
grayscale = grayscale,
grayscalePercentage = if (!homeEnabled) homeGrayscalePercentage else lockGrayscalePercentage
grayscalePercentage = lockGrayscalePercentage
)
Spacer(modifier = Modifier.height(8.dp))
}
}
}
if (homeEnabled) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center
modifier = Modifier.weight(1f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(text = stringResource(R.string.home), fontWeight = FontWeight.W500)
Text(
text = stringResource(R.string.home),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (currentHomeWallpaper != null) {
PreviewItem(
wallpaperUri = currentHomeWallpaper,
darken = darken,
darkenPercentage = homeDarkenPercentage,
scaling = scaling,
blur = blur,
blurPercentage = homeBlurPercentage,
vignette = vignette,
vignettePercentage = homeVignettePercentage,
grayscale = grayscale,
grayscalePercentage = homeGrayscalePercentage
)
}
}
}
} else {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
if (lockEnabled) {
Text(
text = stringResource(R.string.lock_screen),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (currentLockWallpaper != null) {
PreviewItem(
wallpaperUri = currentLockWallpaper,
darken = darken,
darkenPercentage = homeDarkenPercentage,
scaling = scaling,
blur = blur,
blurPercentage = homeBlurPercentage,
vignette = vignette,
vignettePercentage = homeVignettePercentage,
grayscale = grayscale,
grayscalePercentage = homeGrayscalePercentage
)
}
}
if (homeEnabled) {
Text(
text = stringResource(R.string.home),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.W500
)
if (currentHomeWallpaper != null) {
PreviewItem(
wallpaperUri = currentHomeWallpaper,
@@ -143,15 +192,15 @@ fun WallpaperPreviewAndScale(
grayscale = grayscale,
grayscalePercentage = homeGrayscalePercentage
)
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
SingleChoiceSegmentedButtonRow (
SingleChoiceSegmentedButtonRow(
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(start = 8.dp, end = 8.dp, bottom = 16.dp))
.padding(horizontal = 16.dp)
) {
options.forEachIndexed { index, label ->
SegmentedButton(
@@ -166,12 +215,14 @@ fun WallpaperPreviewAndScale(
3 -> ScalingConstants.NONE
else -> ScalingConstants.FILL
}
) },
selected = index == selectedIndex
)
},
selected = index == selectedIndex,
modifier = Modifier.weight(1f)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Icon(
painter = when (index) {
@@ -183,9 +234,14 @@ fun WallpaperPreviewAndScale(
},
contentDescription = null,
tint = Color.Unspecified,
modifier = Modifier.size(32.dp)
modifier = Modifier.size(24.dp)
)
Text(
text = label,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.labelMedium
)
Text(text = label, maxLines = 1, overflow = TextOverflow.Ellipsis )
}
}
}
@@ -15,10 +15,13 @@ import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -26,9 +29,12 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.isValidUri
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
import net.engawapg.lib.zoomable.rememberZoomState
@@ -41,29 +47,30 @@ import net.engawapg.lib.zoomable.zoomable
@Composable
fun WallpaperViewScreen(
wallpaperUri: String,
wallpaperName: String,
onBackClick: () -> Unit,
animate : Boolean
) {
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
}
true
} catch (e: Exception) { false }
}
val showUri = isValidUri(LocalContext.current, wallpaperUri)
val zoomState = rememberZoomState()
BackHandler { onBackClick() }
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopAppBar(
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(containerColor = Color.Transparent),
title = {},
colors = topAppBarColors(containerColor = Color.Transparent),
title = {
if (zoomState.scale == 1f) {
Text(
text = wallpaperName,
color = Color.White,
style = MaterialTheme.typography.titleMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
},
navigationIcon = {
IconButton(
onClick = onBackClick,
@@ -100,7 +107,7 @@ fun WallpaperViewScreen(
) {
if (showUri) {
GlideImage(
imageModel = { wallpaperUri.toUri() },
imageModel = { wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri() },
imageOptions = ImageOptions(
contentScale = ContentScale.Fit,
alignment = Alignment.Center
@@ -35,11 +35,18 @@ class ActivityConfigBasicAction : Activity(), TaskerPluginConfigNoInput {
}
class ShortcutActionRunner : TaskerPluginRunnerActionNoOutputOrInput() {
companion object {
private const val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.SHORTCUT"
}
override fun run(context: Context, input: TaskerInput<Unit>): TaskerPluginResult<Unit> {
Handler(Looper.getMainLooper()).post {
val intent = Intent(context, WallpaperBootAndChangeReceiver::class.java)
val intent = Intent(ACTION_CHANGE_WALLPAPER).apply {
setClass(context, WallpaperBootAndChangeReceiver::class.java)
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
}
context.sendBroadcast(intent)
}
return TaskerPluginResultSucess()
}
}
}
@@ -0,0 +1,42 @@
package com.anthonyla.paperize.feature.wallpaper.util.navigation
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.runtime.Composable
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import com.anthonyla.paperize.feature.wallpaper.util.navigation.NavConstants.INITIAL_OFFSET
import kotlin.reflect.KType
inline fun <reified T : Any> NavGraphBuilder.animatedScreen(
typeMap: Map<KType, NavType<*>> = emptyMap(),
animate: Boolean = true,
deepLinks: List<NavDeepLink> = emptyList(),
noinline content: @Composable AnimatedContentScope.(NavBackStackEntry) -> Unit
) = composable<T>(
typeMap = typeMap,
deepLinks = deepLinks,
enterTransition = {
if (animate) {
sharedXTransitionIn(initial = { (it * INITIAL_OFFSET).toInt() })
} else { null }
},
exitTransition = {
if (animate) {
sharedXTransitionOut(target = { -(it * INITIAL_OFFSET).toInt() })
} else { null }
},
popEnterTransition = {
if (animate) {
sharedXTransitionIn(initial = { -(it * INITIAL_OFFSET).toInt() })
} else { null }
},
popExitTransition = {
if (animate) {
sharedXTransitionOut(target = { -(it * INITIAL_OFFSET).toInt() })
} else { null }
},
content = content
)
@@ -2,6 +2,6 @@ package com.anthonyla.paperize.feature.wallpaper.util.navigation
object NavConstants {
const val NAVIGATION_TIME: Int = 300
const val INITIAL_OFFSET = 0.15f
const val INITIAL_OFFSET = 0.175f
const val OFFSET_LIMIT = 0.4f
}
@@ -27,12 +27,6 @@ object Home
@Serializable
object Settings
/**
* Object for Licenses screen
*/
@Serializable
object Licenses
/**
* Object for Privacy screen
*/
@@ -49,16 +43,23 @@ data class AlbumView(val initialAlbumName: String)
* Data class for AddEdit screen
*/
@Serializable
data class AddEdit(val wallpaper: String)
data class AddAlbum(val initialAlbumName: String)
/**
* Data class for WallpaperView screen
*/
@Serializable
data class WallpaperView(val wallpaper: String)
data class WallpaperView(val wallpaperUri: String, val wallpaperName: String)
/**
* Object for FolderView screen
*/
@Serializable
object FolderView
object FolderView
/**
* Object for SortView screen
*/
@Serializable
object SortView
@@ -14,8 +14,9 @@ data class WallpaperAlarmItem(
val homeInterval: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val lockInterval: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val scheduleSeparately: Boolean = false,
val setHome : Boolean = false,
val setLock : Boolean = false,
val setHome: Boolean = false,
val setLock: Boolean = false,
val changeStartTime: Boolean = false,
val startTime: Pair<Int, Int> = Pair(0, 0),
val shuffle: Boolean = true
)
@@ -10,7 +10,16 @@ interface WallpaperAlarmScheduler {
* @param setAlarm whether to set the alarm or not
* @param firstLaunch whether this is the first launch of the wallpaper changer
*/
fun scheduleWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, origin: Int? = null, changeImmediate: Boolean = false, cancelImmediate: Boolean = false, setAlarm: Boolean = true, firstLaunch: Boolean = false)
suspend fun scheduleWallpaperAlarm(
wallpaperAlarmItem: WallpaperAlarmItem,
origin: Int? = null,
changeImmediate: Boolean = false,
cancelImmediate: Boolean = false,
setAlarm: Boolean = true,
firstLaunch: Boolean = false,
homeNextTime: String? = "",
lockNextTime: String? = "",
)
/**
* Update the wallpaper alarm with new times without changing the wallpaper
@@ -1,40 +1,108 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
import android.app.AlarmManager
import android.Manifest
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.AlarmManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperService
import dagger.hilt.android.qualifiers.ApplicationContext
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
/**
* This class is responsible for scheduling wallpaper alarms.
* It uses the AlarmManager to schedule alarms for the [WallpaperReceiver].
* It also uses [HomeWallpaperService] and [LockWallpaperService] to change the wallpaper due to receiver limitations.
*/
class WallpaperAlarmSchedulerImpl (
private val context: Context,
data class ServiceConfig(
val homeInterval: Int? = null,
val lockInterval: Int? = null,
val scheduleSeparately: Boolean? = null,
val type: Int? = null
)
sealed class WallpaperAction {
data object START : WallpaperAction()
data object UPDATE : WallpaperAction()
}
class WallpaperAlarmSchedulerImpl @Inject constructor(
@param:ApplicationContext private val context: Context,
private val settingsDataStore: SettingsDataStore
): WallpaperAlarmScheduler {
private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
/**
* Schedules the wallpaper alarm based on the origin and changeImmediate
*/
override fun scheduleWallpaperAlarm(
companion object {
private const val TAG = "WallpaperAlarmScheduler"
/**
* Schedules a refresh alarm every 24hrs
* This is a static method that doesn't require an instance of WallpaperAlarmSchedulerImpl
*/
fun scheduleRefresh(context: Context, refresh: Boolean = true) {
Log.d(TAG, "scheduleRefresh called with refresh: $refresh")
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Cancel any existing refresh alarm
val cancelIntent = Intent(context, WallpaperReceiver::class.java)
val cancelPendingIntent = PendingIntent.getBroadcast(
context,
Type.REFRESH.ordinal,
cancelIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
alarmManager.cancel(cancelPendingIntent)
if (refresh) {
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("refresh", true)
}
val nextMidnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0)
Log.d(TAG, "Scheduling inexact repeating refresh alarm for next midnight: $nextMidnight")
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
nextMidnight.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
AlarmManager.INTERVAL_DAY,
PendingIntent.getBroadcast(
context,
Type.REFRESH.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
}
}
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
override suspend fun scheduleWallpaperAlarm(
wallpaperAlarmItem: WallpaperAlarmItem,
origin: Int?,
changeImmediate: Boolean,
cancelImmediate: Boolean,
setAlarm: Boolean,
firstLaunch: Boolean
firstLaunch: Boolean,
homeNextTime: String?,
lockNextTime: String?,
) {
// Cancel previous alarms before setting new ones to prevent stale alarms
if (cancelImmediate) cancelWallpaperAlarm()
else {
Log.d(TAG, "scheduleWallpaperAlarm called with:")
Log.d(TAG, " - wallpaperAlarmItem: $wallpaperAlarmItem")
Log.d(TAG, " - changeImmediate: $changeImmediate, setAlarm: $setAlarm, firstLaunch: $firstLaunch")
if (cancelImmediate) {
Log.d(TAG, "Cancelling all previous alarms.")
cancelWallpaperAlarm()
} else {
when (origin) {
Type.HOME.ordinal -> cancelAlarm(Type.HOME)
Type.LOCK.ordinal -> cancelAlarm(Type.LOCK)
@@ -46,197 +114,208 @@ class WallpaperAlarmSchedulerImpl (
}
}
// Schedule new wallpaper alarm
if (wallpaperAlarmItem.scheduleSeparately) {
when (origin) {
Type.LOCK.ordinal -> {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
if (setAlarm) scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, origin, firstLaunch)
}
Type.HOME.ordinal -> {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
if (setAlarm) scheduleWallpaper(wallpaperAlarmItem, Type.HOME, origin, firstLaunch)
}
null -> {
if (changeImmediate) {
changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
}
if (setAlarm) {
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, Type.LOCK.ordinal, firstLaunch)
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, Type.HOME.ordinal, firstLaunch)
}
}
if (changeImmediate) {
if (wallpaperAlarmItem.scheduleSeparately) {
changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
} else {
changeWallpaperImmediate(wallpaperAlarmItem, Type.SINGLE)
}
}
else {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.SINGLE)
if (setAlarm) scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE, null, firstLaunch)
}
}
/**
* Update the alarms
*/
override fun updateWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, firstLaunch: Boolean) {
cancelWallpaperAlarm()
if (wallpaperAlarmItem.scheduleSeparately) {
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, null, firstLaunch)
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, null, firstLaunch)
}
else {
scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE, null, firstLaunch)
}
}
/**
* Update the wallpaper without scheduling alarms
*/
override fun updateWallpaper(scheduleSeparately: Boolean, setHome: Boolean, setLock: Boolean) {
if (scheduleSeparately) {
updateWallpaper(Type.LOCK, setHome, setLock)
updateWallpaper(Type.HOME, setHome, setLock)
}
else {
updateWallpaper(Type.SINGLE, setHome, setLock)
}
}
/**
* Cancels all active alarms
*/
override fun cancelWallpaperAlarm(cancelLock: Boolean, cancelHome: Boolean) {
if (cancelLock) cancelAlarm(Type.LOCK)
if (cancelHome) cancelAlarm(Type.HOME)
if (cancelLock && cancelHome) {
cancelAlarm(Type.SINGLE)
cancelAlarm(Type.REFRESH)
}
}
/**
* Schedules the wallpaper alarm based on type and time
*/
private fun scheduleWallpaper(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int? = null, firstLaunch: Boolean = false) {
val startTime = if (wallpaperAlarmItem.changeStartTime && firstLaunch) {
var calculatedStartTime = LocalDateTime.now().withHour(wallpaperAlarmItem.startTime.first).withMinute(wallpaperAlarmItem.startTime.second)
if (calculatedStartTime.isBefore(LocalDateTime.now())) {
calculatedStartTime = calculatedStartTime.plusDays(1)
if (setAlarm) {
if (wallpaperAlarmItem.scheduleSeparately) {
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, Type.LOCK.ordinal, firstLaunch, homeNextTime, lockNextTime)
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, Type.HOME.ordinal, firstLaunch, homeNextTime, lockNextTime)
} else {
scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE, null, firstLaunch, homeNextTime, lockNextTime)
}
calculatedStartTime
}
}
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
private suspend fun scheduleWallpaper(
wallpaperAlarmItem: WallpaperAlarmItem,
type: Type,
origin: Int? = null,
firstLaunch: Boolean = false,
homeNextTime: String? = null,
lockNextTime: String? = null
) {
Log.d(TAG, "scheduleWallpaper called for type: $type")
try {
val nextTime = calculateNextAlarmTime(wallpaperAlarmItem, type, firstLaunch, homeNextTime ?: "", lockNextTime ?: "")
Log.d(TAG, "Calculated next alarm time for type '$type': $nextTime")
val intent = createWallpaperIntent(wallpaperAlarmItem, type, origin)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
Log.w(TAG, "Cannot schedule exact alarms. Permission may be denied.")
cancelWallpaperAlarm()
return
}
scheduleExactAlarm(nextTime, intent)
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
when (type) {
Type.HOME -> settingsDataStore.putString(SettingsConstants.HOME_NEXT_SET_TIME, nextTime.toString())
Type.LOCK -> settingsDataStore.putString(SettingsConstants.LOCK_NEXT_SET_TIME, nextTime.toString())
Type.SINGLE -> {
settingsDataStore.putString(SettingsConstants.HOME_NEXT_SET_TIME, nextTime.toString())
settingsDataStore.putString(SettingsConstants.LOCK_NEXT_SET_TIME, nextTime.toString())
}
else -> {}
}
val currentHomeNext = settingsDataStore.getString(SettingsConstants.HOME_NEXT_SET_TIME)
val currentLockNext = settingsDataStore.getString(SettingsConstants.LOCK_NEXT_SET_TIME)
val nextHomeDateTime = runCatching { LocalDateTime.parse(currentHomeNext) }.getOrNull()
val nextLockDateTime = runCatching { LocalDateTime.parse(currentLockNext) }.getOrNull()
val nextSetTimeForNotification = listOfNotNull(nextHomeDateTime, nextLockDateTime)
.filter { it.isAfter(LocalDateTime.now()) }
.minOrNull() ?: nextTime
settingsDataStore.putString(SettingsConstants.NEXT_SET_TIME, nextSetTimeForNotification.format(formatter))
postNotification(nextSetTimeForNotification)
} catch (e: Exception) {
Log.e(TAG, "Error scheduling wallpaper alarm for type '$type'", e)
cancelWallpaperAlarm()
}
}
private fun calculateNextAlarmTime(
wallpaperAlarmItem: WallpaperAlarmItem,
type: Type,
firstLaunch: Boolean,
homeNextTime: String,
lockNextTime: String
): LocalDateTime {
val now = LocalDateTime.now()
val intervalMinutes = when {
type == Type.LOCK && wallpaperAlarmItem.scheduleSeparately -> wallpaperAlarmItem.lockInterval.toLong()
else -> wallpaperAlarmItem.homeInterval.toLong()
}
val nextTime = if (wallpaperAlarmItem.changeStartTime) {
var anchorTime = now
.withHour(wallpaperAlarmItem.startTime.first)
.withMinute(wallpaperAlarmItem.startTime.second)
.withSecond(0).withNano(0)
while (!anchorTime.isAfter(now)) {
anchorTime = anchorTime.plusMinutes(intervalMinutes)
}
anchorTime
} else {
LocalDateTime.now()
if (firstLaunch) {
now.plusMinutes(intervalMinutes)
} else {
val baseTime = when (type) {
Type.LOCK -> runCatching { LocalDateTime.parse(lockNextTime) }.getOrDefault(now)
else -> runCatching { LocalDateTime.parse(homeNextTime) }.getOrDefault(now)
}
var futureTime = baseTime.plusMinutes(intervalMinutes)
while (!futureTime.isAfter(now)) {
futureTime = futureTime.plusMinutes(intervalMinutes)
}
futureTime
}
}
val nextTime = when {
wallpaperAlarmItem.changeStartTime && firstLaunch -> startTime
type == Type.LOCK && wallpaperAlarmItem.scheduleSeparately -> startTime.plusMinutes(wallpaperAlarmItem.lockInterval.toLong())
type == Type.HOME && wallpaperAlarmItem.scheduleSeparately -> startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong()).plusSeconds(10)
else -> startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong())
return if (type == Type.HOME && wallpaperAlarmItem.scheduleSeparately) {
nextTime.plusSeconds(10).withSecond(0).withNano(0)
} else {
nextTime.withSecond(0).withNano(0)
}
val intent = Intent(context, WallpaperReceiver::class.java).apply {
}
private fun changeWallpaperImmediate(wallpaperAlarmItem: WallpaperAlarmItem, type: Type) {
Log.d(TAG, "changeWallpaperImmediate called for type: $type")
val serviceConfig = ServiceConfig(
homeInterval = wallpaperAlarmItem.homeInterval,
lockInterval = wallpaperAlarmItem.lockInterval,
scheduleSeparately = wallpaperAlarmItem.scheduleSeparately
)
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.SINGLE.ordinal))
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.SINGLE.ordinal))
}
Type.LOCK.ordinal -> startService(context, LockWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.LOCK.ordinal))
Type.HOME.ordinal -> startService(context, HomeWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.HOME.ordinal))
}
}
private fun startService(context: Context, serviceClass: Class<*>, action: WallpaperAction, config: ServiceConfig?) {
Log.d(TAG, "startService for ${serviceClass.simpleName}, action: ${action.javaClass.simpleName}")
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action.javaClass.simpleName
config?.let {
it.homeInterval?.let { interval -> putExtra("homeInterval", interval) }
it.lockInterval?.let { interval -> putExtra("lockInterval", interval) }
it.scheduleSeparately?.let { separate -> putExtra("scheduleSeparately", separate) }
it.type?.let { type -> putExtra("type", type) }
}
}
context.startForegroundService(serviceIntent)
}
private fun postNotification(nextSetTime: LocalDateTime) {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val formattedNextSetTime = nextSetTime.format(formatter)
val mainActivityIntent = Intent(context, MainActivity::class.java)
val pendingMainActivityIntent = PendingIntent.getActivity(
context, 3, mainActivityIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val notification = NotificationCompat.Builder(context, "wallpaper_service_channel").apply {
setContentTitle(context.getString(R.string.app_name))
setContentText(context.getString(R.string.next_wallpaper_change, formattedNextSetTime))
setSmallIcon(R.drawable.notification_icon)
setContentIntent(pendingMainActivityIntent)
priority = NotificationCompat.PRIORITY_DEFAULT
setOnlyAlertOnce(true)
}.build()
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
}
private fun createWallpaperIntent(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int?): Intent {
return Intent(context, WallpaperReceiver::class.java).apply {
putExtra("homeInterval", wallpaperAlarmItem.homeInterval)
putExtra("lockInterval", wallpaperAlarmItem.lockInterval)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
putExtra("setHome", wallpaperAlarmItem.setHome)
putExtra("setLock", wallpaperAlarmItem.setLock)
putExtra("changeStartTime", wallpaperAlarmItem.changeStartTime)
putExtra("startTime", wallpaperAlarmItem.startTime)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("origin", origin)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!alarmManager.canScheduleExactAlarms()) {
cancelWallpaperAlarm()
}
else {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
type.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
}
else {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
type.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
putExtra("type", type.ordinal)
putExtra("changeStartTime", wallpaperAlarmItem.changeStartTime)
putExtra("startTime", intArrayOf(wallpaperAlarmItem.startTime.first, wallpaperAlarmItem.startTime.second))
}
}
/**
* Schedules a refresh alarm every 24hrs
*/
fun scheduleRefresh() {
cancelAlarm(Type.REFRESH)
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("refresh", true)
}
val nextMidnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0)
alarmManager.setAndAllowWhileIdle(
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
private fun scheduleExactAlarm(nextTime: LocalDateTime, intent: Intent) {
val requestCode = intent.getIntExtra("type", 0)
val pendingIntent = PendingIntent.getBroadcast(
context,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
val triggerAtMillis = nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000
Log.d(TAG, "Setting exact alarm for $nextTime (Millis: $triggerAtMillis) with requestCode: $requestCode")
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextMidnight.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
Type.REFRESH.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
triggerAtMillis,
pendingIntent
)
}
/**
* Use the service to change the wallpaper
*/
private fun changeWallpaperImmediate(wallpaperAlarmItem: WallpaperAlarmItem, type: Type) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.LOCK.ordinal)
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.HOME.ordinal)
}
}
}
/**
* Updates the wallpaper without changing the alarm
*/
private fun updateWallpaper(type: Type, setHome: Boolean, setLock: Boolean) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.UPDATE.toString())
if (setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.UPDATE.toString())
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.UPDATE.toString())
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.UPDATE.toString())
}
}
}
/**
* Cancels the alarm based on type
*/
private fun cancelAlarm(type: Type) {
Log.d(TAG, "Cancelling alarm for type: $type (requestCode: ${type.ordinal})")
val pendingIntent = PendingIntent.getBroadcast(
context,
type.ordinal,
@@ -246,17 +325,34 @@ class WallpaperAlarmSchedulerImpl (
alarmManager.cancel(pendingIntent)
}
/**
* Starts the service to change the wallpaper
*/
private fun startService(context: Context, serviceClass: Class<*>, action: String, homeInterval: Int? = null, lockInterval: Int? = null, scheduleSeparately: Boolean? = null, type: Int? = null) {
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action
homeInterval?.let { putExtra("homeInterval", it) }
lockInterval?.let { putExtra("lockInterval", it) }
scheduleSeparately?.let { putExtra("scheduleSeparately", it) }
type?.let { putExtra("type", it) }
override fun updateWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, firstLaunch: Boolean) {}
override fun updateWallpaper(scheduleSeparately: Boolean, setHome: Boolean, setLock: Boolean) {
if (scheduleSeparately) {
updateWallpaper(Type.LOCK, setHome, setLock)
updateWallpaper(Type.HOME, setHome, setLock)
} else {
updateWallpaper(Type.SINGLE, setHome, setLock)
}
}
private fun updateWallpaper(type: Type, setHome: Boolean, setLock: Boolean) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE, null)
if (setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE, null)
}
Type.LOCK.ordinal -> startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE, null)
Type.HOME.ordinal -> startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE, null)
}
}
override fun cancelWallpaperAlarm(cancelLock: Boolean, cancelHome: Boolean) {
if (cancelLock) cancelAlarm(Type.LOCK)
if (cancelHome) cancelAlarm(Type.HOME)
if (cancelLock && cancelHome) {
cancelAlarm(Type.SINGLE)
cancelAlarm(Type.REFRESH)
}
context.startService(serviceIntent)
}
}
@@ -1,5 +1,4 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
@@ -13,41 +12,60 @@ import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import androidx.core.content.edit
/**
* Receiver for boot and time change and wallpaper change events to restart alarm manager
*/
@AndroidEntryPoint
class WallpaperBootAndChangeReceiver : BroadcastReceiver() {
companion object {
const val ACTION_SHORTCUT = "com.anthonyla.paperize.SHORTCUT"
private const val PREFS_NAME = "wallpaper_receiver_prefs"
private const val LAST_EXECUTION_TIME = "last_execution_time"
private const val MIN_INTERVAL_MS = 3000
}
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
@SuppressLint("UnsafeProtectedBroadcastReceiver")
override fun onReceive(context: Context, intent: Intent) = goAsync {
try {
val scheduler = WallpaperAlarmSchedulerImpl(context)
val toggleChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val selectedAlbum = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: ""
if (intent.action == ACTION_SHORTCUT && !canExecute(context)) return@goAsync
when(intent.action) {
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_TIME_CHANGED,
Intent.ACTION_TIMEZONE_CHANGED,
ACTION_SHORTCUT -> {
saveExecutionTime(context)
val scheduler = WallpaperAlarmSchedulerImpl(context, settingsDataStoreImpl)
val toggleChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val selectedAlbum = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: ""
if (selectedAlbum.isNotEmpty()) {
val homeInterval = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val lockInterval = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val alarmItem = WallpaperAlarmItem(
homeInterval = homeInterval,
lockInterval = lockInterval,
scheduleSeparately = scheduleSeparately,
setLock = setLock,
setHome = setHome
)
alarmItem.let{
scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true,
setAlarm = toggleChanger
)
if (selectedAlbum.isNotEmpty()) {
val homeInterval = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val lockInterval = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val refresh = settingsDataStoreImpl.getBoolean(SettingsConstants.REFRESH) ?: true
val alarmItem = WallpaperAlarmItem(
homeInterval = homeInterval,
lockInterval = lockInterval,
scheduleSeparately = scheduleSeparately,
setLock = setLock,
setHome = setHome
)
alarmItem.let{
scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true,
setAlarm = toggleChanger,
homeNextTime = settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME),
lockNextTime = settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME),
)
}
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, refresh)
}
}
}
} catch (e: Exception) {
@@ -55,6 +73,19 @@ class WallpaperBootAndChangeReceiver : BroadcastReceiver() {
}
}
private fun canExecute(context: Context): Boolean {
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val lastExecution = prefs.getLong(LAST_EXECUTION_TIME, 0)
val currentTime = System.currentTimeMillis()
return currentTime - lastExecution >= MIN_INTERVAL_MS
}
private fun saveExecutionTime(context: Context) {
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
prefs.edit() { putLong(LAST_EXECUTION_TIME, System.currentTimeMillis()) }
}
/* https://stackoverflow.com/questions/74111692/run-coroutine-functions-on-broadcast-receiver */
private fun BroadcastReceiver.goAsync(
context: CoroutineContext = EmptyCoroutineContext,
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more