diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 000000000..1606d61fc
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,23 @@
+# Copying and distribution of this file, with or without modification,
+# are permitted in any medium without royalty provided this notice is
+# preserved. This file is offered as-is, without any warranty.
+# Names of contributors must not be used to endorse or promote products
+# derived from this file without specific prior written permission.
+
+# EditorConfig
+# http://EditorConfig.org
+
+# top-most EditorConfig file
+root = true
+
+# LF end-of-line, insert an empty new line and UTF-8
+[*]
+end_of_line = lf
+insert_final_newline = true
+charset = utf-8
+indent_style = space
+indent_size = 4
+continuation_indent_size = 8
+
+[*.xml]
+continuation_indent_size = 4
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 000000000..9bad22a9b
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,3 @@
+github: [tibbi]
+patreon: tiborkaputa
+custom: ["https://www.paypal.com/paypalme/simplemobiletools", "https://www.simplemobiletools.com/donate"]
diff --git a/.gitignore b/.gitignore
index 7051e766d..d94d37b66 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,12 @@
*.iml
+*.aab
.gradle
/local.properties
-/gradle.properties
/.idea/
.DS_Store
/build
/captures
-release.keystore
-signing.properties
+keystore.jks
+keystore.properties
+/app/src/proprietary/assets/pesdk_license
+/app/src/proprietary/assets/vesdk_license
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7657fb9e..8bf95193a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,1502 @@
Changelog
==========
+Version 6.19.0 *(2021-01-21)*
+----------------------------
+
+ * Allow easily clearing the app cache from the app settings
+ * Allow customizing the spacing between file thumbnails, or using rounded corners
+ * Many other performance, UI, UX, translation and stability improvements
+
+Version 6.18.3 *(2021-01-14)*
+----------------------------
+
+ * Speed up fullscreen medium loading a bit too
+
+Version 6.18.2 *(2021-01-14)*
+----------------------------
+
+ * Improve the performance at scrolling media thumbnails
+ * Speed up cached folder fetching
+ * Some stability and translation improvements
+
+Version 6.18.1 *(2021-01-03)*
+----------------------------
+
+ * Updated the photo and video editor to fix some glitches
+ * Added some translation and stability improvements
+
+Version 6.18.0 *(2020-12-08)*
+----------------------------
+
+ * Added a Video Editor
+ * Added Stickers and Overlays to the Photo Editor
+ * Some translation, stability and UI improvements
+
+Version 6.17.3 *(2020-11-10)*
+----------------------------
+
+ * Properly update the folder thumbnail text colors
+
+Version 6.17.2 *(2020-11-09)*
+----------------------------
+
+ * Adding some folder thumbnail customization at the app settings
+ * Allow setting a default folder to be opened at app launch (by roland-kister)
+ * Updated the photo editor to fix some glitches
+
+Version 6.17.1 *(2020-11-03)*
+----------------------------
+
+ * Reverting to the previous UI of the main screen, but keep rounded corners at list view
+ * Some UI and stability improvements
+
+Version 6.17.0 *(2020-11-02)*
+----------------------------
+
+ * Redesigning the main folders screen, try making it moderner (!)
+ * Fix some glitches with deep zoomable fullscreen images not loading in well
+ * Couple other UX, stability and translation improvements
+
+Version 6.16.5 *(2020-10-28)*
+----------------------------
+
+ * Added some hidden folder handling related improvements
+ * Fixed saving files on the SD card after editing
+ * Couple other UX, translation and performance improvements
+
+Version 6.16.4 *(2020-10-24)*
+----------------------------
+
+ * Fixed an editor glitch occurring if the file path contained spaces
+ * Added some stability improvements
+
+Version 6.16.3 *(2020-10-16)*
+----------------------------
+
+ * Updated the photo editor to fix some issues, mostly related to Android 11
+ * Make sure file moving doesn't block the UI in any case
+
+Version 6.16.2 *(2020-10-10)*
+----------------------------
+
+ * Fix sorting by Date Taken
+ * Properly display some wrongly named WebP files
+
+Version 6.16.1 *(2020-09-27)*
+----------------------------
+
+ * Fixed a bug with some folders not being recognized
+ * Improved thumbnail loading performance in some cases
+
+Version 6.16.0 *(2020-09-25)*
+----------------------------
+
+ * Adding support for animated WebP files
+ * Fixed a permissions glitch after upgrading to Android 11
+ * Added many performance related improvements
+
+Version 6.15.6 *(2020-09-22)*
+----------------------------
+
+ * Fixed the file loading performance in some cases
+ * Fixed some photo editor related glitches
+ * Fixed the Use English language settings toggle
+
+Version 6.15.5 *(2020-09-16)*
+----------------------------
+
+ * Properly fetch the latest available Last Modified of files
+
+Version 6.15.4 *(2020-09-16)*
+----------------------------
+
+ * Improved file loading performance
+
+Version 6.15.3 *(2020-09-09)*
+----------------------------
+
+ * Improved file loading performance in some cases
+ * Some UX, translation and stability improvements
+
+Version 6.15.2 *(2020-06-17)*
+----------------------------
+
+ * Fixed a glitch at caching fullscreen images
+ * Properly recognize a new type of panoramic images
+
+Version 6.15.1 *(2020-06-12)*
+----------------------------
+
+ * Fixed a glitch at caching fullscreen images
+ * Improved batch renaming with patterns
+
+Version 6.15.0 *(2020-06-07)*
+----------------------------
+
+ * Rescan the internal storage from time to time, look for new folders containing media
+ * Improve the Search user experience, do not reset it at opening an item
+ * Fixed some editor glitches
+ * Speed up fullscreen image loading
+
+Version 6.14.10 *(2020-05-29)*
+----------------------------
+
+ * Updated the image editor, fix a glitch with black preview
+ * Show Portrait images by default on Android 10
+ * Use a nicer icon on older devices
+ * Some translation and stability improvements
+
+Version 6.14.9 *(2020-05-18)*
+----------------------------
+
+ * Fixing some glitches with hidden folders not being shown when appropriate
+ * Added some stability and translation improvements
+
+Version 6.14.8 *(2020-05-05)*
+----------------------------
+
+ * Added some crashfixes
+
+Version 6.14.7 *(2020-05-04)*
+----------------------------
+
+ * Fixed a glitch with some favorite items disappearing
+ * Improve folder hiding, add the new .nomedia file into MediaStore
+ * Improve the performance of getting video file duration
+ * A few other improvements here and there
+
+Version 6.14.6 *(2020-04-26)*
+----------------------------
+
+ * Added a few more stability and performance improvements
+
+Version 6.14.5 *(2020-04-26)*
+----------------------------
+
+ * Disable Portrait photo showing by default, until it gets improved
+ * Added a couple other performance improvements here and there
+
+Version 6.14.4 *(2020-04-24)*
+----------------------------
+
+ * Improved the performance on multiple places
+ * Removed some unnecessary permissions added recently
+ * Fixed some photo editor glitches
+ * Show Portrait images by default only on Android 9+
+
+Version 6.14.3 *(2020-04-21)*
+----------------------------
+
+ * Use the selected date format grouped thumbnail section titles too
+ * Fixed a glitch related to locked folders asking authentication too often
+ * Refresh the UI here and there a bit
+
+Version 6.14.2 *(2020-04-18)*
+----------------------------
+
+ * Fixed some Photo Editor bugs
+ * Properly handle locked folders at opening from widgets and shortcuts
+ * Open the map at clicking the coordinates at the Properties window
+ * Properly sort items at the Other Folder dialog at copy/move
+ * Fixed some folder un/hiding related glitches
+ * A couple other translation and UX improvements
+
+Version 6.14.1 *(2020-04-14)*
+----------------------------
+
+ * Fixed some SD card file related glitches
+ * Improved some third party intent handling
+ * Added some translation and stability improvements
+
+Version 6.14.0 *(2020-03-19)*
+----------------------------
+
+ * Properly delete playing videos
+ * Removed the Manage Hidden Folders settings button on Android 10+, it no longer works
+ * Added many changes under the hood in preparation for handling Scoped Storage soon
+ * Do not require the Storage permission at some third party intents
+
+Version 6.13.4 *(2020-03-08)*
+----------------------------
+
+ * Fixed some hiding, excluding and including related glitches
+ * Flipped Pin and Properties icons at the top menu for better user experience
+ * Avoid showing Portrait image folders at the main folders screen
+
+Version 6.13.3 *(2020-03-01)*
+----------------------------
+
+ * Avoid showing the "No Date Takens found" error in some cases
+
+Version 6.13.2 *(2020-03-01)*
+----------------------------
+
+ * Properly handle videos at slideshows
+ * Fixed some gestures during video playback
+ * Fixed a glitch with videos randomly restarting in some cases
+
+Version 6.13.1 *(2020-02-28)*
+----------------------------
+
+ * Adding a quick crashfix
+
+Version 6.13.0 *(2020-02-28)*
+----------------------------
+
+ * Allow fast forwarding videos by double clicking on screen sides
+ * Fixed an issue with the editor producing low quality outputs in some cases
+ * Improve some error messages, make them clearer
+ * Many translation and stability improvements
+
+Version 6.12.5 *(2020-02-12)*
+----------------------------
+
+ * Fixed some sorting related glitches
+ * Keep the old last modified value at file editing
+
+Version 6.12.4 *(2020-02-11)*
+----------------------------
+
+ * Fixed some folder sorting related glitches
+
+Version 6.12.3 *(2020-02-10)*
+----------------------------
+
+ * Fixed image disappearing at using the Editor
+ * Properly copy over EXIF values after editing an image
+
+Version 6.12.2 *(2020-02-10)*
+----------------------------
+
+ * Fixed some sorting and thumbnail related issues
+
+Version 6.12.1 *(2020-02-10)*
+----------------------------
+
+ * Improved the performance of the initial screen loading
+ * Fixed some editor related glitches
+
+Version 6.12.0 *(2020-01-28)*
+----------------------------
+
+ * Properly handle sorting by date taken after using "Fix Date Taken values" on the wrong files
+ * Fixed some issues at copying files, when the source was on an SD card
+ * Change the way Favorite items are stored, to avoid accidental removal
+ * Improved video looping (by ForgottenUmbrella)
+ * Recognize a new type of panoramic photos
+ * Properly remember last video playback position if the video is paused on exit
+ * Properly color the top status bar icons at using light primary colors
+ * Other UX and translation improvements
+
+Version 6.11.8 *(2020-01-19)*
+----------------------------
+
+ * Reverted Glide to fix some crashes
+
+Version 6.11.7 *(2020-01-16)*
+----------------------------
+
+ * Do not convert every edited file into a JPG, keep PNGs intact
+ * Fixed a glitch with empty portrait photos being shown as grey thumbnails
+ * Show a FAQ/settings prompt once at pressing Rate Us in the About section
+ * Added a 16:10 editor crop aspect ratio, used mostly on tablets
+ * Do some preparations for better handling Date Taken values and Favorites
+ * Other stability and translation improvements
+
+Version 6.11.6 *(2020-01-11)*
+----------------------------
+
+ * Improved the image loading performance
+ * Allow excluding the root "/" folder
+ * Properly handle editing files with spaces in path
+ * Couple other UX, UI, translation and stability improvements
+
+Version 6.11.5 *(2020-01-04)*
+----------------------------
+
+ * Fixed a few SD card related issues
+ * Fixed some theming issues
+ * Added some UI and translation improvements
+
+Version 6.11.4 *(2019-12-27)*
+----------------------------
+
+ * Fixed a few SD card related issues
+ * Moved Focus in the editor as the last tool, to prioritize more popular tools
+ * Added a new Crop aspect ratio 37:18 to be used instead of 18.5x9
+ * Some translation improvements
+ * Last app update for a while now, wishing you a Happy New Year!
+
+Version 6.11.3 *(2019-12-25)*
+----------------------------
+
+ * Fixed various editor related glitches
+ * Some translation and other UX improvements
+
+Version 6.11.2 *(2019-12-21)*
+----------------------------
+
+ * Added a few more aspect ratios in the editor
+ * Remember the last used editor brush settings
+ * Properly refresh the cache of edited images
+
+Version 6.11.1 *(2019-12-18)*
+----------------------------
+
+ * Removing Text Design from the editor, it takes up too much space
+
+Version 6.11.0 *(2019-12-17)*
+----------------------------
+
+ * Fully replaced the photo editor with a powerful third party library
+ * Added some crashfixes and stability improvements
+
+Version 6.10.8 *(2019-12-17)*
+----------------------------
+
+ * Added some crashfixes and stability improvements
+
+Version 6.10.7 *(2019-12-12)*
+----------------------------
+
+ * Refreshed the thumbnails list views by removing the dividers
+ * Reordered some top menu items for consistency
+ * Added a Resize button to resize images directly from the fullscreen view
+ * Migrate album covers at export/import settings too
+ * Remember the last used path and file name at exporting settings
+ * Fixed a glitch with empty screen at direct subfolder grouping
+ * Many other stability, ux and translation improvements
+
+Version 6.10.6 *(2019-11-28)*
+----------------------------
+
+ * Fixed some smaller glitches
+ * Added some stability and translation improvements
+
+Version 6.10.5 *(2019-11-10)*
+----------------------------
+
+ * Remember the last used pattern at batch renaming
+ * Allow adding an incrementing number at pattern batch renaming
+ * Fixed some USB file related issues
+ * Fixed some fullscreen glitches at using split screen
+ * Allow using videos as custom folder covers
+ * Some stability and translation improvements
+
+Version 6.10.4 *(2019-11-05)*
+----------------------------
+
+ * Improved USB device handling
+ * Some smaller stability and translation improvements
+
+Version 6.10.3 *(2019-10-27)*
+----------------------------
+
+ * Adding some smaller stability, translation improvements and bugfixes
+
+Version 6.10.2 *(2019-10-13)*
+----------------------------
+
+ * Fixed a glitch with small letters in some cases
+ * Properly display SVG images
+ * Show a "Pro" label at the About sections' app version
+
+Version 6.10.1 *(2019-10-06)*
+----------------------------
+
+ * Fixed some Portrait photo related crashes
+
+Version 6.10.0 *(2019-10-04)*
+----------------------------
+
+ * Added initial support for Portrait images
+ * Updated some helper libraries
+ * Some stability and translation improvements
+
+Version 6.9.6 *(2019-09-12)*
+----------------------------
+
+ * Improved the performance of loading fullscreen images in some cases
+ * Properly handle some specific SD cards
+ * Properly fetch Date Taken value on Android 10
+
+Version 6.9.5 *(2019-09-08)*
+----------------------------
+
+ * Added optional thumbnail icons for showing GIF/SVG/RAW file types
+ * Properly handle Date Taken value at copy/move/edit
+ * Fixed a glitch with white top actionmenu at selecting items
+ * Fixed fullscreen mode toggling on Chromebooks
+
+Version 6.9.4 *(2019-08-21)*
+----------------------------
+
+ * Let's load a higher resolution image at the fullscreen view
+
+Version 6.9.3 *(2019-08-19)*
+----------------------------
+
+ * Added some light theme related improvements
+ * Properly keep the last_modified field at copy/move in some new cases
+ * Changed the way fullscreen images are loaded to fix some rotation issues
+ * Fixed some video playback aspect ratio glitches
+ * Few other improvements here and there
+
+Version 6.9.2 *(2019-08-11)*
+----------------------------
+
+ * Added some performance improvements at fullscreen media on weaker devices
+ * Allow long pressing Properties fields to copy values to the clipboard
+ * Show the errors occuring at file fetching with a toast
+ * Fixed a glitch at batch renaming using a pattern
+ * Try fixing Date Taken values automatically after copy/move
+ * Changed most of the icons to vectors for better quality and lower size
+ * Properly color the top menu icons
+ * Some other UX, performance and stability improvements
+
+Version 6.9.1 *(2019-08-03)*
+----------------------------
+
+ * Fixing a video player related crash
+
+Version 6.9.0 *(2019-08-02)*
+----------------------------
+
+ * Show a message at copy/move if the destination doesn't have enough space
+ * Rewrote the video playback to fix some glitches
+ * Improve the performance at loading initial screen folders
+ * Allow toggling between the old renaming of appending/prepending or using a pattern
+ * Some improvements related to folder un/hiding
+
+Version 6.8.4 *(2019-07-29)*
+----------------------------
+
+ * Share files in the order they were selected
+ * Allow customizing the bottom navigation bar color
+ * Fixed some UI glitches related to fullscreen view bottom buttons
+ * Many other stability and UX improvements
+
+Version 6.8.3 *(2019-07-14)*
+----------------------------
+
+ * Added support for HEIC/HEIF files
+ * Reverted back to the previous way of searching folders, with a button for searching all files instead
+ * Added some dark theme improvements
+ * Show some location related values at the Properties window, or at the Extended details
+ * Misc other stability, performance and translation improvements
+
+Version 6.8.2 *(2019-07-02)*
+----------------------------
+
+ * Allow password protecting individual folders
+ * Let's try using dark theme menu
+ * Fixed the performance of scrolling GIF thumbnails
+ * Fixed some video stucking issues
+ * Some other stability and translation improvements
+
+Version 6.8.1 *(2019-06-27)*
+----------------------------
+
+ * Improved Search on the main screen, allow using it for searching all files, not folders
+ * Added Print functionality at fullscreen images
+ * Fixed a glitch at PNGs getting deleted after rotating
+ * Other stability, translation and performance improvements
+
+Version 6.8.0 *(2019-06-21)*
+----------------------------
+
+ * Allow grouping files by date_taken or last_modified either daily, or monthly
+ * Allow selecting fade animation or no animation at all at slideshow transitions
+ * Improved the performance at loading fullscreen videos
+ * Use last_modified value at batch file renaming, if date_taken isn't available
+ * Some other stability and translation improvements
+
+Version 6.7.9 *(2019-06-12)*
+----------------------------
+
+ * Fixed a crash at zooming
+
+Version 6.7.8 *(2019-06-11)*
+----------------------------
+
+ * Improved the UX at zooming and panning at the fullscreen view
+ * Fixed unchecking Favorite items in some cases
+ * Show the available aspect ratios at the editor by default
+ * Couple stability, performance and translation improvements
+
+Version 6.7.7 *(2019-05-28)*
+----------------------------
+
+ * Fixed some file deleting related glitches
+ * Improved batch renaming, use the old file extension in case a new one is missing
+
+Version 6.7.6 *(2019-05-26)*
+----------------------------
+
+ * Improved batch renaming, allow using date time patterns in it
+ * Fixed empty folder deleting after deleting its content
+ * Improved new file cache updating in the background
+ * Improved the placeholder text in case no files are found
+ * Keep last_modified field at deleting and restoring files from the bin
+ * Increase the max image duration at slideshows
+ * Highlight the warning at deleting a folder
+ * Other stability, translation and performance improvements
+
+Version 6.7.5 *(2019-05-15)*
+----------------------------
+
+ * Hotfixing a glitch with opening third party intents
+
+Version 6.7.4 *(2019-05-15)*
+----------------------------
+
+ * Speeded up video deleting from fullscreen view
+ * Hotfixed some crashes
+
+Version 6.7.3 *(2019-05-14)*
+----------------------------
+
+ * Fixed folder sorting if used together with subfolder grouping
+ * Fixed some copy/move related progressbar issues
+ * Added many performance and stability improvements
+
+Version 6.7.2 *(2019-05-09)*
+----------------------------
+
+ * Allow creating file or folder shortcuts only from Android 8+
+
+Version 6.7.1 *(2019-05-08)*
+----------------------------
+
+ * Allow creating file or folder shortcuts on home screen on Android 7+
+ * Allow creating new folders on the file thumbnails screen too
+ * Added a checkbox at sorting by name/path to sort numbers by their actual numeric value
+ * Improve grouping direct subfolders, do not ignore parent folders without media files
+ * Show the Open Camera button at the menu on the main screen, instead of the Sort by button
+ * Other translation and stability improvements
+
+Version 6.7.0 *(2019-05-02)*
+----------------------------
+
+ * Moved the video duration field at the top right corner of thumbnails, if enabled
+ * Fixed some fullscreen image related glitches
+ * Misc translation and stability improvements
+
+Version 6.6.4 *(2019-04-09)*
+----------------------------
+
+ * Reverting to the previous way of sorting items by name/path
+ * Some stability and translation improvements
+
+Version 6.6.3 *(2019-04-02)*
+----------------------------
+
+ * Fixed some OTG devices and SD card related glitches
+ * Drastically increased the sorting performance by file path and name by simplifying it
+ * Fixed some third party related issues at opening images/videos
+ * Allow zooming raw images
+ * Try making "Fix Date Taken values" more reliable in some cases
+ * Added an explanation dialog if someone upgrades to Pro app from the free one
+ * Remember all video positions if enabled, not just the last one (by centic9)
+ * Added a new FAQ item about the app size
+
+Version 6.6.1 *(2019-03-21)*
+----------------------------
+
+ * Fixed recognizing of some SD cards
+ * Added some stability and translation improvements
+
+Version 6.6.0 *(2019-03-10)*
+----------------------------
+
+ * Further improved new file discovery
+ * Exclude some folders by default, like fb stickers
+ * Added other stability and ux improvements
+
+Version 6.5.5 *(2019-03-05)*
+----------------------------
+
+ * Improve new file discovery
+ * Fixed some third party intent related glitches
+ * Fixed some issues related to grouping thumbnails
+ * Added a note at Sorting and Grouping dialog to avoid some confusion
+ * Avoid deleting filtered out file types at deleting folders
+
+Version 6.5.4 *(2019-02-28)*
+----------------------------
+
+ * Allow customizing file loading priority
+ * Fixed the handling of some image picker intents
+ * Speeded up renaming files on SD cards
+ * Added some file loading performance improvements
+ * Some stability improvements
+
+Version 6.5.3 *(2019-02-22)*
+----------------------------
+
+ * Added main screen menu buttons for fast Recycle Bin showing/hiding
+ * Added a new setting item for changing date and time format
+ * Do not shuffle images with Random sorting that often
+ * Fixed some glitches related to file rename, delete, move
+ * Added many smaller bugfixes and UX improvements
+
+Version 6.5.2 *(2019-02-16)*
+----------------------------
+
+ * Added an option to disable rotating fullscreen images with gestures
+ * Improved OTG usb device handling
+ * Fixed Grouping by date taken
+ * Improved the performance at deleting files from the fullscreen view
+ * Some stability improvements
+
+Version 6.5.1 *(2019-02-11)*
+----------------------------
+
+ * Fixed a glitch with image panning
+ * Added a couple stability improvements
+
+Version 6.5.0 *(2019-02-07)*
+----------------------------
+
+ * Allow rotating fullscreen images with gestures, if "Allow deep zooming images" option is enabled
+ * Zoom out videos and gifs after device rotation
+
+Version 6.4.1 *(2019-01-29)*
+----------------------------
+
+ * Fixed some crashes related to zoomable videos
+ * Disable the Close Down gesture at GIFs and videos, if they are zoomed in
+
+Version 6.4.0 *(2019-01-29)*
+----------------------------
+
+ * Implemented export/importing for app settings and other preferences, like sorting
+ * Allow hiding Notch on fullscreen view on Android 9+
+ * Some gif/video zoom related improvements
+ * Autosave images zoomed at the fullscreen view
+ * Many other UX and stability improvements
+
+Version 6.3.2 *(2019-01-23)*
+----------------------------
+
+ * Fixed some fullscreen image and gif issues related to zooming
+ * Show directly included folders even if they contain a .nomedia file
+
+Version 6.3.1 *(2019-01-22)*
+----------------------------
+
+ * Fixed fullscreen images crashing when the app was installed on an SD card
+ * A couple other fullscreen image viewer improvements
+ * Allow batch rotating only images, ignore other file types
+
+Version 6.3.0 *(2019-01-17)*
+----------------------------
+
+ * Allow zooming GIFs and videos
+ * Allow sharing images directly from the editor
+ * Allow drawing in the editor
+ * If a folder is directly excluded, make it a higher priority than some included parent folder
+ * Added batch rotating from the thumbnails view
+ * Many other smaller improvements
+
+Version 6.2.2 *(2019-01-10)*
+----------------------------
+
+ * Reverted to the old way of playing videos, opening them on a separate screen can be enabled in the app settings
+ * Added some memory related improvements at displaying fullscreen images
+ * Allow showing videos in slideshows
+
+Version 6.2.1 *(2019-01-08)*
+----------------------------
+
+ * Fixed some menu buttons at the video player activity
+ * Added buttons to the videoplayer for going to the previous/next item
+ * Allow pressing play/pause at the video player at fullscreen mode
+ * Properly retain exif values after editing a file, when overwriting the source file
+
+Version 6.2.0 *(2019-01-04)*
+----------------------------
+
+ * Rewrote video playback, use a separate screen + added fast-forwarding with horizontal swiping
+ * Added optional 1:1 pixel ratio zooming with two double taps at fullscreen view
+ * Allow adding Copy at the fullscreen bottom actions
+ * Always include images at slideshows, never videos
+ * Fixed scanning of some predefined folders for images
+ * Some other stability/performance/translation improvements
+
+Version 6.1.3 *(2018-12-26)*
+----------------------------
+
+ * Fixed a glitch at zooming fullscreen images with double tap
+ * Hide favorite items from hidden folders, if showing hidden items is disabled
+
+Version 6.1.2 *(2018-12-24)*
+----------------------------
+
+ * Done a few performance improvements here and there
+ * Allow changing view type individually per folder
+ * Merry Christmas!
+
+Version 6.1.1 *(2018-12-18)*
+----------------------------
+
+ * Fixing some crashes
+
+Version 6.1.0 *(2018-12-17)*
+----------------------------
+
+ * Added an initial widget implementation for creating homescreen folder shortcuts
+ * Added optional grouping of direct subfolders, as a check at the "Change view type" dialog
+ * Added an option to set custom crop aspect ratio at the editor
+ * Save exif data at edited files on Android 7+
+ * Handle only Mass Storage USB devices, ignore the rest
+ * Many other smaller UX/stability/performance improvements
+
+Version 6.0.4 *(2018-12-04)*
+----------------------------
+
+ * Limit automatic spam folder exclusion to the "/Android/data" folder
+
+Version 6.0.3 *(2018-12-02)*
+----------------------------
+
+ * Added multiple predefined aspect ratios at the Editor + remember the last used ratio
+ * Fix some issue with deleted items not appearing in the Recycle Bin, causing the app to take up too much space
+ * At delete/copy/move operations on folders apply them only on the visible files, take filters/hiding into account
+ * Do not exclude whole Data folder by default, be smarter about filtering out spam folders
+ * Added support for Sony RAW ".arw" files
+ * Optimize video duration fetching at thumbnails
+
+Version 6.0.2 *(2018-11-19)*
+----------------------------
+
+ * Adding a crashfix related to showing video duration
+
+Version 6.0.1 *(2018-11-19)*
+----------------------------
+
+ * Added optional displaying video duration on thumbnails
+ * Fixed keeping last_modified value at copy/move in some cases
+ * Exclude the Data folder by default
+ * Many translation, UX and stability improvements
+
+Version 6.0.0 *(2018-11-04)*
+----------------------------
+
+ * Initial Pro version
+
+Version 5.1.4 *(2018-11-28)*
+----------------------------
+
+ * Make sure the "Upgrade to Pro" popup isn't shown at first launch
+ * This version of the app is no longer maintained, please upgrade to the Pro version. You can find the Upgrade button at the top of the app Settings.
+
+Version 5.1.3 *(2018-11-04)*
+----------------------------
+
+ * Adding an option to store last video playback position (by mathevs)
+ * Adding a "Keep both" conflict resolution at copy/move (by Doubl3MM)
+ * Improved panoramic video detection
+ * Remove some glitches related to third party file opening
+ * Do not exclude the Data folder by default
+ * Removed the "Avoid showing Whats New at app startup" option
+
+Version 5.1.2 *(2018-10-30)*
+----------------------------
+
+ * Added a new option for password protecting file deletion/move
+ * Improved panorama video detection
+ * Improved the opening of media files without file extension
+ * Disabled move operation on Recycle bin items, use Restore
+ * Fixed handling of some third party image picker intents
+ * Fixed slideshow looping and a couple other UX glitches
+ * Improved the stability of retrieving cached files
+ * Hi
+
+Version 5.1.1 *(2018-10-23)*
+----------------------------
+
+ * Fixing the inability to delete SD card files
+
+Version 5.1.0 *(2018-10-23)*
+----------------------------
+
+ * Added support for panorama videos
+ * Added an extra check to avoid trying deleting files without write permission
+ * Added an initial implementation of renaming multiple items at once
+ * Added some performance improvements at item de/selection
+ * Allow enabling hidden item visibility at the copy/move destination picker
+ * Allow closing fullscreen view with swipe down gestures (can be disabled in settings)
+ * Fixed a glitch with Favorite items getting unselected every day
+ * Fixed exposure time displayed at long exposure photos
+ * Fixed fullscreen images being sometimes totally zoomed in after device rotation
+ * Fixed slideshow direction
+ * Made loading initial fullscreen view quicker and fullscreen toggling more reliable
+ * Not sure what else, nobody reads this anyway
+
+Version 5.0.1 *(2018-10-17)*
+----------------------------
+
+ * Adding some crashfixes
+
+Version 5.0.0 *(2018-10-17)*
+----------------------------
+
+ * Increased the minimal required Android OS version to 5 (Lollipop)
+ * Rewrote file selection for more robustness
+ * Added a new option for showing the Recycle Bin as the last folder
+ * Added Search for searching folders by names
+ * Replaced the G+ button with Reddit
+ * Couple smaller glitch fixes and improvements
+
+Version 4.6.5 *(2018-10-02)*
+----------------------------
+
+ * Added notch support for Android 9
+ * Allow faster video seeking by dragging a finger at the bottom seekbar
+ * Use a different way of displaying fullscreen GIFs
+ * Added a new toggle for trying to show the best possible image quality
+ * Keep Favorite items marked after moving
+ * Fixed some glitches related to toggling fullscreen mode
+ * Many other smaller improvements
+
+Version 4.6.4 *(2018-09-22)*
+----------------------------
+
+ * Fixed lag at zooming fullscreen images on some devices
+
+Version 4.6.3 *(2018-09-21)*
+----------------------------
+
+ * Improved zooming performance at fullscreen view
+ * Fixed showing conflict resolution dialog at Move
+ * Fixed selection check icons at horizontal scrolling
+ * Fixed displaying some fullscreen images, where file path contained percentage sign or hashtag
+ * Optimized many database operations
+ * Fixed many other smaller issues
+
+Version 4.6.2 *(2018-09-05)*
+----------------------------
+
+ * Fixed opening some email client attachments and MMS images
+ * Attempt to fix lagging at zooming in on some devices
+ * Couple other smaller bugfixes and improvements
+
+Version 4.6.1 *(2018-08-21)*
+----------------------------
+
+ * Added a crashfix at loading fullscreen images
+
+Version 4.6.0 *(2018-08-20)*
+----------------------------
+
+ * Added support for SVGs
+ * Improved fullscreen image quality and performance
+ * Properly show files with hastags and percentage signs in their paths
+ * Many other smaller UX improvements
+
+Version 4.5.2 *(2018-08-08)*
+----------------------------
+
+ * Adding a toggle for disabling deep zoomable images
+ * Fix displaying third party images
+ * Couple smaller UX fixes
+
+Version 4.5.1 *(2018-08-07)*
+----------------------------
+
+ * Adding a crashfix
+
+Version 4.5.0 *(2018-08-07)*
+----------------------------
+
+ * Use real Move instead of the old copy/delete if both source and destination are on the internal storage
+ * Remake the fullscreen view, always use deep zoomable images with good quality
+ * Couple stability improvements
+
+Version 4.4.4 *(2018-08-02)*
+----------------------------
+
+ * Adding a crashfix
+
+Version 4.4.3 *(2018-08-01)*
+----------------------------
+
+ * Removed the More Donating Options from the Purchase Thank You dialog
+
+Version 4.4.2 *(2018-08-01)*
+----------------------------
+
+ * Removed the homepage from About section
+
+Version 4.4.1 *(2018-07-30)*
+----------------------------
+
+ * Hide both Play and Pause video buttons after 2 secs
+ * Improved Immersive mode fullscreen behaviour
+ * Some other stability improvements
+
+Version 4.4.0 *(2018-07-26)*
+----------------------------
+
+ * Reworked the editor, added some filters
+ * Allow hiding the Recycle Bin from the main screen folders
+ * Added a menu item for fixing file Date Taken
+ * Fixed some glitches around recycle bin item restoring
+ * Fixed some issues with video playback on resume
+ * Many other UX and stability improvements
+
+Version 4.3.5 *(2018-07-17)*
+----------------------------
+
+ * Fixed some Recycle bin related issues
+ * A few more UX and stability improvements
+
+Version 4.3.4 *(2018-07-15)*
+----------------------------
+
+ * Fixed disappearing launcher icon after changing its color on some devices
+ * Fixed some video related errors
+ * Added "Set as" as an available action at the fullscreen bottom actions
+ * Do the appropriate actions at trying to delete the Recycle Bin or Favorites folders
+ * Fixed a glitch with some panorama images not recognized properly
+ * Avoid blank screen at toggling "Temporarily show hidden"
+
+Version 4.3.3 *(2018-07-06)*
+----------------------------
+
+ * Couple stability improvements and glitch fixes
+
+Version 4.3.2 *(2018-07-04)*
+----------------------------
+
+ * Added Panorama photo support
+ * Allow customizing visible fullscreen bottom actions
+ * Allow forcing portrait/landscape modes at fullscreen view
+ * Use Exoplayer for playing videos
+ * Many smaller UX and stability improvements
+
+Version 4.3.1 *(2018-06-28)*
+----------------------------
+
+ * Adding some crashfixes
+
+Version 4.3.0 *(2018-06-28)*
+----------------------------
+
+ * Added a Recycle Bin
+ * Allow grouping media thumbnails by different criteria
+ * Fixed some calculation glitches around fastscroller
+ * Change the fullscreen Edit icon to a pencil
+ * Allow sorting "Show All" separately
+ * Many smaller stability and UX improvements
+
+Version 4.2.1 *(2018-06-20)*
+----------------------------
+
+ * Allow selecting Favorite items for easy access
+ * Fix sorting by Date Taken after files have been copied
+ * Couple other stability and UX improvements
+
+Version 4.2.0 *(2018-06-18)*
+----------------------------
+
+ * Move some actions at the fullscreen view to the bottom of the screen
+ * Allow filtering out RAW images separately
+ * Add a warning if the user tries deleting a folder
+ * Properly reset the temporary Skip Delete Confirmation dialog
+ * Show a Pause button over video if not in fullscreen mode
+ * Fix some glitches around inserting pin/pattern/fingerprint
+ * Many other stability and ux improvements
+
+Version 4.1.1 *(2018-05-26)*
+----------------------------
+
+ * Always set folder thumbnail based on folder content sorting
+ * Make sure hidden folders have the "(hidden)" appended
+
+Version 4.1.0 *(2018-05-25)*
+----------------------------
+
+ * Added sorting by Date Taken
+ * Fixed file renaming on Android Oreo
+ * Fixed some scrollbar glitches
+ * Fixed broken "Use english language" in some cases
+ * Make sure only the proper files are shown at "Show all folders content"
+ * Many other smaller UX, stability improvements and bugfixes
+
+Version 4.0.0 *(2018-05-13)*
+----------------------------
+
+ * Allow customizing the app launcher color
+ * Remove the top spinning circle at initial launch
+ * Many other bugfixes and UX/stability improvements
+
+Version 3.8.2 *(2018-04-26)*
+----------------------------
+
+ * Rewrote media caching and new file discovery for better performance
+ * Many OTG file handling improvements
+
+Version 3.8.1 *(2018-04-24)*
+----------------------------
+
+ * Rewrote media caching and new file discovery for better performance
+ * Some OTG file handling improvements
+
+Version 3.8.0 *(2018-04-22)*
+----------------------------
+
+ * Rewrote media caching for better performance
+ * Cache all media items, not just 80 per folder
+ * Some additional performance and stability improvements
+
+Version 3.7.3 *(2018-04-15)*
+----------------------------
+
+ * Show hidden folders when appropriate
+
+Version 3.7.2 *(2018-04-14)*
+----------------------------
+
+ * Fix Edit intent handled by other apps
+ * Hide folders containing ".nomedia" file, even if explicitly included
+ * Remove sorting by Date Taken until proper implementation
+
+Version 3.7.1 *(2018-04-12)*
+----------------------------
+
+ * Fix no media being shown to some people
+ * Fix some glitches at renaming files
+ * Show a count of files being deleted at the confirmation prompt
+
+Version 3.7.0 *(2018-04-10)*
+----------------------------
+
+ * Rewrote media file fetching for better performance and new item discovering
+ * Make un/hiding folders quicker
+ * Make automatic fullscreen toggling animation smoother by delaying it
+ * Many other smaller performance and UX improvements
+
+Version 3.6.3 *(2018-03-30)*
+----------------------------
+
+ * Couple file scanning and thumbnail displaying updates
+ * Show a dialog about the new Simple Clock app to some users
+
+Version 3.6.2 *(2018-03-23)*
+----------------------------
+
+ * Fixing some crashes related to file scanning
+ * Do not scan Download folder file by file, it can contain many items
+
+Version 3.6.1 *(2018-03-22)*
+----------------------------
+
+ * Set proper file mimetype after editing or other file operation
+ * Try scanning Screenshots and Download folders more thoroughly
+ * Couple stability improvements
+
+Version 3.6.0 *(2018-03-15)*
+----------------------------
+
+ * Fix duplicate files at renaming or hiding
+ * Improve some third party handling
+ * Optimize rotated image saving to avoid Out of memory errors
+ * Optimize new item discoveries or folder refreshing
+ * Many other smaller performance and UX improvements
+
+Version 3.5.3 *(2018-03-03)*
+----------------------------
+
+ * Properly keep last-modified at file copy/move if set so
+ * Misc other smaller glitch and translation improvements
+
+Version 3.5.2 *(2018-02-25)*
+----------------------------
+
+ * Fixed third party intent uri generation
+ * Properly handle files with colon in filename
+ * Fix copying whole folders
+
+Version 3.5.1 *(2018-02-25)*
+----------------------------
+
+ * Added a toggle for disabling pull-to-refresh
+ * Added a toggle for permanent Delete confirmation dialog skipping
+ * Fixed saving image after editing
+
+Version 3.5.0 *(2018-02-20)*
+----------------------------
+
+ * Added copy/move progress notification
+ * Fixed some glitches a round rotating media by aspect ratio
+ * Added FAQ
+ * Make explicit folder inclusion recursive
+ * Added initial OTG device support
+ * Rewrote third party intent handling and file handling, fixed some bugs along the way
+ * Probably added some new bugs
+
+Version 3.4.1 *(2018-02-09)*
+----------------------------
+
+ * Fix some glitches around swiping fullscreen media with instant media switch or gesture brightness change enabled
+ * Make changing image brightness with gestures disabled by default
+ * Allow skipping forward/backward videos by pressing max/current time
+ * Fix some cases of editing third party images
+ * Couple other stability improvements
+
+Version 3.4.0 *(2018-02-05)*
+----------------------------
+
+ * Allow changing the brightness by vertical gestures on images (by trubitsyn)
+ * Properly fetch all media files from recognized folders
+ * Make thumbnail info on the main screen a bit easier to read
+ * Fix seeing blank thumbnail after deleting files in some cases
+ * Reset zoom level on orientation change at fullscreen media
+ * Add an optional extra check to avoid showing invalid files
+ * Add a toggle to prevent showing What's new on startup
+ * Many other stability and performance improvements
+
+Version 3.3.1 *(2018-01-29)*
+----------------------------
+
+ * Added a toggle for replacing deep zoomable images with better quality ones
+ * Added a toggle for hiding Extended details when the statusbar is hidden
+ * Added a toggle for switching media files by clicking on screen sides
+ * Disable "Temporarily show hidden" after 10 minutes of backgrounding
+ * Split Settings in separate sections
+
+Version 3.3.0 *(2018-01-23)*
+----------------------------
+
+ * Added optional one-finger drag zoom at fullscreen media (by gh123man)
+ * Allow opening the app even without any media files (by gh123man)
+ * Refresh media files in the background when Simple Camera creates a new photo/video
+ * Improve fullscreen media rotation by "Device Rotation"
+
+Version 3.2.4 *(2018-01-17)*
+----------------------------
+
+ * An F-droid build only, trying to add screenshots there
+
+Version 3.2.3 *(2018-01-14)*
+----------------------------
+
+ * An F-droid build only, fixing a compile error
+
+Version 3.2.2 *(2018-01-09)*
+----------------------------
+
+ * Some scrolling issues fixed
+ * Improve new media file discovery
+
+Version 3.2.1 *(2018-01-08)*
+----------------------------
+
+ * Adding a crashfix
+ * Couple scrollbar glitch fixes
+
+Version 3.2.0 *(2018-01-07)*
+----------------------------
+
+ * Rewrote scrolling to improve the performance
+ * Disable "Delete empty folders" by default
+ * Added initial Search to media thumbnails screen
+ * Apply the hidden folder password protection to "Manage hidden folders"
+ * Replace Move with Copy/Delete on Android 7+
+ * Improve SD card file support
+
+Version 3.1.2 *(2017-12-30)*
+----------------------------
+
+ * Fixed some video related crashes
+
+Version 3.1.1 *(2017-12-29)*
+----------------------------
+
+ * Added a new setting item for managing folders hidden with .nomedia
+ * Speed up image loading
+ * Use copy/delete instead of move on Android 8.x
+ * Improved double-tap zoom ratios
+
+Version 3.1.0 *(2017-12-25)*
+----------------------------
+
+ * Fixed some issues around picking contact images
+ * Misc other improvements
+
+Version 3.0.3 *(2017-12-20)*
+----------------------------
+
+ * Added a new Black & White theme with special handling
+ * Fixed opening MMS attachments
+ * Fixed viewing properties/sharing etc at fullscreen media
+ * Apply "Dark background at fullscreen media" to the status bar too
+ * Misc performance/stability improvements
+
+Version 3.0.2 *(2017-12-17)*
+----------------------------
+
+ * Properly display email attachments
+ * Some crashfixes
+
+Version 3.0.1 *(2017-12-06)*
+----------------------------
+
+ * Fix missing launcher icon on some devices
+ * Added an info bubble at scrolling by dragging
+ * Allow zooming gifs
+ * Display raw .dng files
+
+Version 3.0.0 *(2017-12-04)*
+----------------------------
+
+ * Improved primary color customization
+ * Allow setting home and lock screen wallpapers separately on Android 7+
+ * Many smaller performance and stability improvements
+
+Version 2.19.0 *(2017-11-23)*
+----------------------------
+
+ * Rolled back to displaying images in RGB_565 quality for proper zoom and performance
+ * Load directory thumbnails faster if a new medium has been discovered
+ * Couple performance and stability improvements
+
+Version 2.18.1 *(2017-11-16)*
+----------------------------
+
+ * Fixed some double-tap zoom issues
+ * Misc smaller fixes and improvements here and there
+
+Version 2.18.0 *(2017-11-09)*
+----------------------------
+
+ * Added an option to use english language on non-english devices
+ * Added an option to password protect the whole app
+ * Added an option to lock screen orientation at fullscreen view
+ * Split the Rotate button to 3 buttons per degrees
+ * Changed the way fullscreen images are loaded for better quality
+ * Fixed many memory leaks and smaller issues
+
+Version 2.17.4 *(2017-11-06)*
+----------------------------
+
+ * Fixed some third party intent handling
+ * Increased max columns count to 20
+ * Allow rotating JPGs in a lossless way (by ltGuillaume)
+
+Version 2.17.3 *(2017-11-02)*
+----------------------------
+
+ * Fixed some corrupt gif file related crashes
+ * Rotate jpgs on the internal storage by exif
+ * Fixed some invisible SD card content
+
+Version 2.17.2 *(2017-10-29)*
+----------------------------
+
+ * Couple more minor fixes
+
+Version 2.17.1 *(2017-10-29)*
+----------------------------
+
+ * Show "Set As" and "Edit" menu buttons at videos and gifs too
+ * Couple other smaller issues fixed
+
+Version 2.17.0 *(2017-10-28)*
+----------------------------
+
+ * Added a toggle for keeping last-modified field at file copy/move/rename
+ * Improved GIF animation speed
+ * Implemented fileprovider support to third party intents
+ * Make rotation by "Device rotation" less sensitive
+ * Automatically append "_1" to filename after saving through the Editor
+ * Added support for Adaptive icons for Android 8 (by fiepi)
+ * Added Dutch translation (by ltGuillaume)
+ * Many other smaller improvements
+
+Version 2.16.1 *(2017-10-24)*
+----------------------------
+
+ * Added a toggle for hiding folder media count on the main screen
+ * Fixed SD card folders not being visible on some devices
+ * Fixed videos not playing properly in some cases
+ * Do not modify last_modified at copy/move/rename
+ * Added support for 3gpp videos
+
+Version 2.16.0 *(2017-10-19)*
+----------------------------
+
+ * Added sorting by path
+ * Added an option to show customizable extended details over fullscreen media
+ * Allow selecting Album cover photos from any folders
+ * Added a checkbox for skipping Delete confirmation dialog
+
+Version 2.15.2 *(2017-10-06)*
+----------------------------
+
+ * Properly display SD card content to Android 4 users
+ * Fix displaying some third party media, like Bluemail attachments
+ * Fix media picking intents if "Show all folders content" is enabled
+
+Version 2.15.1 *(2017-10-01)*
+----------------------------
+
+ * Updated commons library with minor fixes
+
+Version 2.15.0 *(2017-10-01)*
+----------------------------
+
+ * Added fingerprint to hidden item protection
+ * Added a new List view type
+ * Fixed an issue with some hidden items being shown at "Show all folders content"
+ * Fixed typing in color hex codes manually with some keyboards
+ * Do not autosave rotated images in any case
+ * Tons of other performance, stability and UX improvements
+
+Version 2.14.4 *(2017-09-18)*
+----------------------------
+
+ * Revert to the old way of loading fullscreen images to avoid issues on Android 7+
+
+Version 2.14.3 *(2017-09-17)*
+----------------------------
+
+ * Removed some error toast messages after delete, or if image loading failed
+ * Fixed some visual glitches at horizontal scrolling
+ * Disable pull-to-refresh at horizontal scrolling
+ * Many other smaller bugfixes and improvements
+
+Version 2.14.2 *(2017-09-11)*
+----------------------------
+
+ * Fixing some glitches with fullscreen images
+ * Add an extra check to avoid displaying non-existing media
+ * Fix opening media from third party intents
+
+Version 2.14.1 *(2017-09-07)*
+----------------------------
+
+ * Fixing some glitches around fullscreen view
+
+Version 2.14.0 *(2017-09-05)*
+----------------------------
+
+ * Simplified the way of creating new folders
+ * Added a loop option to slideshows, slowed down the swipe animation
+ * Added an option to filter out gifs from slideshows
+ * Improved the quality of fullscreen images
+ * Properly allow excluding the root folder
+
+Version 2.13.4 *(2017-09-01)*
+----------------------------
+
+ * Improved the image loading performance
+ * Added a switch for disabling video gestures
+ * Added a switch for deleting empty folders after deleting content
+ * Show excluded folder content at third party intent if needed
+
+Version 2.13.3 *(2017-08-29)*
+----------------------------
+
+ * Fixing copy/move actions on some devices
+
+Version 2.13.2 *(2017-08-28)*
+----------------------------
+
+ * Moved media type filter from Settings to the Action menu
+ * Allow filtering GIFs out
+ * Make sure we always show manually included folders
+ * Properly show hidden files, when open from some File Manager
+
+Version 2.13.1 *(2017-08-16)*
+----------------------------
+
+ * Show a folder if its both excluded and included
+ * Many translation improvements
+
+Version 2.13.0 *(2017-08-07)*
+----------------------------
+
+ * Allow changing the screen brightness and volume at videos by vertically dragging the screen sides
+ * Fixed sorting of numbers in filenames
+ * Fixed a glitch with hidden files sometimes temporarily visible
+ * Unified thumbnail corner icon sizes and style
+
+Version 2.12.6 *(2017-08-05)*
+----------------------------
+
+ * Added slideshow at the fullscreen view
+ * Replaced the foreground color of selected items with a check
+ * Made copy/move to SD card a lot faster
+
+Version 2.12.5 *(2017-08-03)*
+----------------------------
+
+ * Updating file operation on SD card
+
+Version 2.12.4 *(2017-08-03)*
+----------------------------
+
+ * Fixed SD card file operations
+
+Version 2.12.3 *(2017-08-02)*
+----------------------------
+
+ * Added pattern/pin protection for showing hidden items
+ * Hopefully fixed unintentional SD card file deleting
+
+Version 2.12.2 *(2017-07-09)*
+----------------------------
+
+ * Added a toggle for replacing Share with Rotate at fullscreen media
+ * Some crashfixes and translation updates
+
+Version 2.12.1 *(2017-07-02)*
+----------------------------
+
+ * Couple crashfixes
+
+Version 2.12.0 *(2017-07-01)*
+----------------------------
+
+ * Added a button for disabling "Temporarily show hidden"
+ * Updated Glide (library used for loading images) to 4.0.0
+ * Made playing gifs smooth
+
+Version 2.11.5 *(2017-06-29)*
+----------------------------
+
+ * Added an indicator of folders located on SD cards
+ * Improved the way of rotating jpg images on the internal storage by modifying the exif tags + added autosave
+
+Version 2.11.4 *(2017-06-26)*
+----------------------------
+
+ * Added an option for automatically hiding the system UI at entering fullscreen mode
+ * Fix deleting SD card files on some devices
+ * Couple crashfixes
+
+Version 2.11.3 *(2017-06-24)*
+----------------------------
+
+ * Added optional horizontal scrolling
+
+Version 2.11.1 *(2017-06-19)*
+----------------------------
+
+ * Fixed a crash at starting video
+
+Version 2.11.0 *(2017-06-18)*
+----------------------------
+
+ * Store column count separately for portrait and landscape modes
+ * Improve zooming at double taping fullscreen images
+ * Allow opening a third party editor from our Editor screen
+ * Many crashfixes and smaller improvements
+
Version 2.10.10 *(2017-06-07)*
----------------------------
diff --git a/LICENSE b/LICENSE
index 28c26588c..f288702d2 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,13 +1,674 @@
-Copyright 2016 SimpleMobileTools
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
- https://www.apache.org/licenses/LICENSE-2.0
+ Preamble
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 9d5d26e5c..501baa4b0 100644
--- a/README.md
+++ b/README.md
@@ -1,36 +1,114 @@
# Simple Gallery
-
+
-A gallery for viewing photos and videos.
+Simple Gallery Pro is a highly customizable lightweight gallery loved by millions of people for its great user experience. Organize and edit your photos, recover deleted files with the recycle bin, protect & hide files and easily view a huge variety of different photo and video formats including RAW, SVG, GIF, panoramic and much more.
-A simple tool usable for viewing photos and videos. Items can be sorted by date, size, name both ascending or descending, photos can be zoomed in. Media files are shown in multiple columns depending on the size of the display, you can change the column count by pinch gestures. They can be renamed, shared, deleted, copied, moved. Images can also be cropped, rotated, flipped or set as Wallpaper directly from the app.
+-------------------------------------------------
+SIMPLE GALLERY PRO – FEATURES
+-------------------------------------------------
-The Gallery is also offered for third party usage for previewing images / videos, adding attachments at email clients etc. It's perfect for everyday usage.
+• A beautiful modern gallery with no ads or popups
-Contains no ads or unnecessary permissions. It is fully opensource, provides customizable colors.
+• Photo editor – crop, rotate, resize, draw, filters & more
-This app is just one piece of a bigger series of apps. You can find the rest of them at http://www.simplemobiletools.com
+• No internet access needed, giving you more privacy, security and stability
-
-
+• No unnecessary permissions required
-
-
-
+• Quickly search images, videos & other files
-License
--------
- Copyright 2017 SimpleMobileTools
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- https://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
+• Open and view many different photo and video types (RAW, SVG, panoramic, GIF etc)
+
+• A variety of intuitive gestures to easily edit, rotate & organize files
+
+• Lots of ways to filter, group and sort files
+
+• Customize the appearance of Simple Gallery Pro
+
+• Available in over 30 languages
+
+• Mark files as favorites for quick access
+
+• Protect your photos & videos with a pattern, pin or fingerprint
+
+• Use pin, pattern & fingerprint to protect the app launch or specific functions too
+
+• Recover deleted photos & videos from the recycle bin
+
+• Toggle visibility of files to hide photos & videos
+
+• Create a customizable slideshow of your files with many options
+
+• View detailed information of your files (resolution, EXIF values etc)
+
+• Zoom high quality photos, videos and GIFs easily with gestures
+
+• Easily force portrait or landscape orientation for easy video viewing
+
+• Quick file share to social media, email or anywhere else
+
+• Print images or set them as wallpaper with a few clicks
+
+• Create home screen shortcuts or widgets to easily access any file or folder
+
+• Show the image location on a map, if available
+
+• Obvious presence of standard operations like rename, copy/move, un/hide, delete
+
+• Rewind videos with horizontal gestures
+
+• Change photo and video brightness, or volume with vertical gestures
+
+• Reorder, lock folders or change cover thumbnails anytime
+
+• Set any image as wallpaper without hassle
+
+… and much much more!
+
+ADVANCED PHOTO EDITOR
+Simple Gallery Pro makes it easy to edit your pictures on the fly. Crop, flip, rotate and resize your pictures. If you’re feeling a little more creative you can add filters and draw on your pictures!
+
+
+SUPPORT FOR MANY FILE TYPES
+Simple Gallery Pro supports a huge range of different file types including JPEG, PNG, MP4, MKV, RAW, SVG, GIF Panoramic photos, Panoramic videos and many more.
+
+
+HIGHLY CUSTOMIZABLE FILE MANAGER
+From the UI to the function buttons on the bottom toolbar, Simple Gallery Pro is highly customizable and works the way you want it to. No other gallery has this kind of flexibility! Thanks to being open source, we’re also available in over 30 languages!
+
+
+RECOVER DELETED PHOTOS & VIDEOS
+Accidentally deleted a precious photo or video? Don’t worry! Simple Gallery Pro features a handy recycle bin where you can recover deleted photos & videos easily.
+
+
+PROTECT & HIDE PHOTOS, VIDEOS & FILES
+Using pin, pattern or your device’s fingerprint scanner you can protect and hide photos, videos & entire albums. You can protect the app itself or place locks on specific functions of the app. For example, you can’t delete a file without a fingerprint scan, helping to protect your files from accidental deletion.
+
+
+Check out the full suite of Simple Tools here:
+https://www.simplemobiletools.com
+
+
+Standalone website of Simple Gallery Pro:
+https://www.simplemobiletools.com/gallery
+
+
+Facebook:
+https://www.facebook.com/simplemobiletools
+
+
+Reddit:
+https://www.reddit.com/r/SimpleMobileTools
+
+
+Don't forget that if you uninstall any paid app within 2 hours, you will automatically be refunded. If you want a refund anytime later, just contact us at hello@simplemobiletools.com and you will get it. That makes it easy to try it out :)
+
+
+
+
+
diff --git a/app/build.gradle b/app/build.gradle
index cd03e6b5f..096eddbd6 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -1,78 +1,143 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
+apply plugin: 'kotlin-kapt'
+
+def keystorePropertiesFile = rootProject.file("keystore.properties")
+def keystoreProperties = new Properties()
+if (keystorePropertiesFile.exists()) {
+ keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
+}
android {
- compileSdkVersion 25
- buildToolsVersion "25.0.2"
+ compileSdkVersion 29
+ buildToolsVersion "29.0.3"
defaultConfig {
- applicationId "com.simplemobiletools.gallery"
- minSdkVersion 16
- targetSdkVersion 23
- versionCode 109
- versionName "2.10.10"
+ applicationId "com.simplemobiletools.gallery.pro"
+ minSdkVersion 21
+ targetSdkVersion 29
+ versionCode 335
+ versionName "6.19.0"
+ setProperty("archivesBaseName", "gallery-$versionCode")
+ vectorDrawables.useSupportLibrary = true
}
signingConfigs {
- release
+ if (keystorePropertiesFile.exists()) {
+ release {
+ keyAlias keystoreProperties['keyAlias']
+ keyPassword keystoreProperties['keyPassword']
+ storeFile file(keystoreProperties['storeFile'])
+ storePassword keystoreProperties['storePassword']
+ }
+ }
}
buildTypes {
+ debug {
+ // we cannot change the original package name, else PhotoEditorSDK won't work
+ //applicationIdSuffix ".debug"
+ }
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- signingConfig signingConfigs.release
+ if (keystorePropertiesFile.exists()) {
+ signingConfig signingConfigs.release
+ }
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
+ if (is_proprietary) {
+ main.java.srcDirs += 'src/proprietary/kotlin'
+ }
+ }
+
+ flavorDimensions "licensing"
+ productFlavors {
+ proprietary {}
+ foss {}
+ }
+
+ lintOptions {
+ checkReleaseBuilds false
+ abortOnError false
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+
+ packagingOptions {
+ exclude 'META-INF/library_release.kotlin_module'
}
}
dependencies {
- compile 'com.simplemobiletools:commons:2.20.1'
- compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.6.0'
- compile 'com.theartofdev.edmodo:android-image-cropper:2.4.0'
- compile 'com.bignerdranch.android:recyclerview-multiselect:0.2'
- compile 'com.google.code.gson:gson:2.8.0'
- compile 'com.github.chrisbanes:PhotoView:1.3.1'
- compile 'it.sephiroth.android.exif:library:1.0.1'
- compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
+ implementation 'com.simplemobiletools:commons:5.33.7'
+ implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
+ implementation 'it.sephiroth.android.exif:library:1.0.1'
+ implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.19'
+ implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
+ implementation 'com.google.android.exoplayer:exoplayer-core:2.9.6'
+ implementation 'com.google.vr:sdk-panowidget:1.180.0'
+ implementation 'com.google.vr:sdk-videowidget:1.180.0'
+ implementation 'org.apache.sanselan:sanselan:0.97-incubator'
+ implementation 'info.androidhive:imagefilters:1.0.7'
+ implementation 'com.squareup.picasso:picasso:2.71828'
+ implementation 'com.caverock:androidsvg-aar:1.3'
+ implementation 'com.github.tibbi:gestureviews:512f929d82'
+ implementation 'com.github.tibbi:subsampling-scale-image-view:81c021514c'
+ implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
+ implementation 'com.github.penfeizhou.android.animation:awebp:2.5.1'
- debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
- releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
- testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
+ kapt 'com.github.bumptech.glide:compiler:4.10.0'
+
+ kapt 'androidx.room:room-compiler:2.2.6'
+ implementation 'androidx.room:room-runtime:2.2.6'
+ annotationProcessor 'androidx.room:room-compiler:2.2.6'
}
-buildscript {
- ext.kotlin_version = '1.1.2-3'
- repositories {
- mavenCentral()
- }
+// Apply the PESDKPlugin
+if (is_proprietary) {
+ apply plugin: 'ly.img.android.sdk'
- dependencies {
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
- classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
+ imglyConfig {
+ vesdk {
+ enabled true
+ licencePath 'vesdk_license'
+ }
+
+ pesdk {
+ enabled true
+ licencePath 'pesdk_license'
+ }
+
+ modules {
+ include 'ui:video-trim'
+ include 'ui:core'
+ include 'ui:text'
+ include 'ui:focus'
+ include 'ui:brush'
+ include 'ui:filter'
+ include 'ui:sticker'
+ include 'ui:overlay'
+ include 'ui:transform'
+ include 'ui:adjustment'
+
+ include 'backend:serializer'
+ include 'backend:sticker-smart'
+ include 'backend:sticker-animated'
+
+ include 'assets:font-basic'
+ include 'assets:filter-basic'
+ include 'assets:overlay-basic'
+ include 'assets:sticker-shapes'
+ include 'assets:sticker-emoticons'
+ include 'assets:sticker-animated'
+ }
}
}
-
-def Properties props = new Properties()
-def propFile = new File('signing.properties')
-if (propFile.canRead()) {
- props.load(new FileInputStream(propFile))
-
- if (props != null && props.containsKey('STORE_FILE') && props.containsKey('KEY_ALIAS') && props.containsKey('PASSWORD')) {
- android.signingConfigs.release.storeFile = file(props['STORE_FILE'])
- android.signingConfigs.release.storePassword = props['PASSWORD']
- android.signingConfigs.release.keyAlias = props['KEY_ALIAS']
- android.signingConfigs.release.keyPassword = props['PASSWORD']
- } else {
- println 'signing.properties found but some entries are missing'
- android.buildTypes.release.signingConfig = null
- }
-} else {
- println 'signing.properties not found'
- android.buildTypes.release.signingConfig = null
-}
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 34de0fb81..763f4ff3b 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -1,5 +1,20 @@
-keep class com.simplemobiletools.** { *; }
+-dontwarn android.graphics.Canvas
-dontwarn com.simplemobiletools.**
+-dontwarn org.apache.**
--renamesourcefileattribute SourceFile
--keepattributes SourceFile, LineNumberTable
+# Picasso
+-dontwarn javax.annotation.**
+-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
+-dontwarn org.codehaus.mojo.animal_sniffer.*
+-dontwarn okhttp3.internal.platform.ConscryptPlatform
+
+-keepclassmembers class * implements android.os.Parcelable {
+ static ** CREATOR;
+}
+
+# RenderScript
+-keepclasseswithmembernames class * {
+native ;
+}
+-keep class androidx.renderscript.** { *; }
diff --git a/app/src/debug/res/values/strings.xml b/app/src/debug/res/values/strings.xml
new file mode 100644
index 000000000..ebf8b9d2a
--- /dev/null
+++ b/app/src/debug/res/values/strings.xml
@@ -0,0 +1,4 @@
+
+
+ Gallery_debug
+
\ No newline at end of file
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 8c640a923..2cbbf2613 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -1,33 +1,59 @@
+ xmlns:tools="http://schemas.android.com/tools"
+ package="com.simplemobiletools.gallery.pro"
+ android:installLocation="auto">
+
+
+
-
+
+
+
+
+
+
+
+ android:theme="@style/AppTheme"
+ tools:replace="android:label">
-
-
-
-
-
-
+ android:theme="@style/SplashTheme"/>
+
+
+
+
+
+
@@ -53,13 +79,37 @@
+ android:parentActivityName=".activities.MainActivity">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ android:parentActivityName=".activities.MediaActivity">
@@ -82,18 +132,37 @@
android:label="@string/third_party_licences"
android:parentActivityName="com.simplemobiletools.commons.activities.AboutActivity"/>
-
-
+
+
+
+
+
+
+
+
+
+
@@ -107,10 +176,14 @@
android:label="@string/excluded_folders"
android:parentActivityName=".activities.SettingsActivity"/>
+
+
+ android:configChanges="orientation|keyboardHidden|screenSize">
@@ -123,8 +196,7 @@
+ android:configChanges="orientation|keyboardHidden|screenSize">
@@ -138,7 +210,10 @@
-
+
+
+
@@ -177,8 +252,17 @@
+
+
+
+
+
+
@@ -188,11 +272,283 @@
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/App.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/App.kt
deleted file mode 100644
index 9e46e19a9..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/App.kt
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.simplemobiletools.gallery
-
-import android.app.Application
-import com.squareup.leakcanary.LeakCanary
-
-class App : Application() {
- override fun onCreate() {
- super.onCreate()
- if (LeakCanary.isInAnalyzerProcess(this)) {
- return
- }
- LeakCanary.install(this)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/EditActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/EditActivity.kt
deleted file mode 100644
index d69eb1393..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/EditActivity.kt
+++ /dev/null
@@ -1,199 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.app.Activity
-import android.graphics.Bitmap
-import android.graphics.Bitmap.CompressFormat
-import android.graphics.Point
-import android.net.Uri
-import android.os.Bundle
-import android.provider.MediaStore
-import android.util.Log
-import android.view.Menu
-import android.view.MenuItem
-import com.simplemobiletools.commons.extensions.getCompressionFormat
-import com.simplemobiletools.commons.extensions.getFileOutputStream
-import com.simplemobiletools.commons.extensions.scanPath
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.dialogs.ResizeDialog
-import com.simplemobiletools.gallery.dialogs.SaveAsDialog
-import com.simplemobiletools.gallery.extensions.getRealPathFromURI
-import com.theartofdev.edmodo.cropper.CropImageView
-import kotlinx.android.synthetic.main.view_crop_image.*
-import java.io.*
-
-
-class EditActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener {
- val TAG = EditActivity::class.java.simpleName
- val ASPECT_X = "aspectX"
- val ASPECT_Y = "aspectY"
- val CROP = "crop"
-
- lateinit var uri: Uri
- var resizeWidth = 0
- var resizeHeight = 0
- var isCropIntent = false
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.view_crop_image)
-
- if (intent.data == null) {
- toast(R.string.invalid_image_path)
- finish()
- return
- }
-
- uri = intent.data
- if (uri.scheme != "file" && uri.scheme != "content") {
- toast(R.string.unknown_file_location)
- finish()
- return
- }
-
- isCropIntent = intent.extras?.get(CROP) == "true"
-
- crop_image_view.apply {
- setOnCropImageCompleteListener(this@EditActivity)
- setImageUriAsync(intent.data)
-
- if (isCropIntent && shouldCropSquare())
- setFixedAspectRatio(true)
- }
- }
-
- override fun onCreateOptionsMenu(menu: Menu): Boolean {
- menuInflater.inflate(R.menu.menu_editor, menu)
- menu.findItem(R.id.resize).isVisible = !isCropIntent
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.save_as -> crop_image_view.getCroppedImageAsync()
- R.id.rotate -> crop_image_view.rotateImage(90)
- R.id.resize -> resizeImage()
- R.id.flip_horizontally -> flipImage(true)
- R.id.flip_vertically -> flipImage(false)
- else -> return super.onOptionsItemSelected(item)
- }
- return true
- }
-
- private fun resizeImage() {
- val point = getAreaSize()
- if (point == null) {
- toast(R.string.unknown_error_occurred)
- return
- }
-
- ResizeDialog(this, point) {
- resizeWidth = it.x
- resizeHeight = it.y
- crop_image_view.getCroppedImageAsync()
- }
- }
-
- private fun shouldCropSquare(): Boolean {
- val extras = intent.extras
- return if (extras != null && extras.containsKey(ASPECT_X) && extras.containsKey(ASPECT_Y)) {
- extras.getInt(ASPECT_X) == extras.getInt(ASPECT_Y)
- } else {
- false
- }
- }
-
- private fun getAreaSize(): Point? {
- val rect = crop_image_view.cropRect ?: return null
- val rotation = crop_image_view.rotatedDegrees
- return if (rotation == 0 || rotation == 180) {
- Point(rect.width(), rect.height())
- } else {
- Point(rect.height(), rect.width())
- }
- }
-
- override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) {
- if (result.error == null) {
- if (isCropIntent && intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true) {
- val targetUri = intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri
- var inputStream: InputStream? = null
- var outputStream: OutputStream? = null
- try {
- val stream = ByteArrayOutputStream()
- result.bitmap.compress(CompressFormat.JPEG, 100, stream)
- inputStream = ByteArrayInputStream(stream.toByteArray())
- outputStream = contentResolver.openOutputStream(targetUri)
- inputStream.copyTo(outputStream)
- } finally {
- inputStream?.close()
- outputStream?.close()
- }
- setResult(RESULT_OK)
- finish()
- } else if (uri.scheme == "file") {
- SaveAsDialog(this, uri.path) {
- saveBitmapToFile(result.bitmap, it)
- }
- } else if (uri.scheme == "content") {
- val newPath = applicationContext.getRealPathFromURI(uri) ?: ""
- if (!newPath.isEmpty()) {
- SaveAsDialog(this, newPath) {
- saveBitmapToFile(result.bitmap, it)
- }
- } else {
- toast(R.string.image_editing_failed)
- finish()
- }
- } else {
- toast(R.string.unknown_file_location)
- finish()
- }
- } else {
- toast("${getString(R.string.image_editing_failed)}: ${result.error.message}")
- }
- }
-
- private fun saveBitmapToFile(bitmap: Bitmap, path: String) {
- val file = File(path)
-
- try {
- getFileOutputStream(file) {
- saveBitmap(file, bitmap, it)
- }
- } catch (e: Exception) {
- Log.e(TAG, "Crop compressing failed $path $e")
- toast(R.string.image_editing_failed)
- finish()
- } catch (e: OutOfMemoryError) {
- toast(R.string.out_of_memory_error)
- }
- }
-
- private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream) {
- if (resizeWidth > 0 && resizeHeight > 0) {
- val resized = Bitmap.createScaledBitmap(bitmap, resizeWidth, resizeHeight, false)
- resized.compress(file.getCompressionFormat(), 90, out)
- } else {
- bitmap.compress(file.getCompressionFormat(), 90, out)
- }
- setResult(Activity.RESULT_OK, intent)
- scanFinalPath(file.absolutePath)
- out.close()
- }
-
- private fun flipImage(horizontally: Boolean) {
- if (horizontally)
- crop_image_view.flipImageHorizontally()
- else
- crop_image_view.flipImageVertically()
- }
-
- private fun scanFinalPath(path: String) {
- scanPath(path) {
- setResult(Activity.RESULT_OK, intent)
- toast(R.string.file_saved)
- finish()
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/ExcludedFoldersActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/ExcludedFoldersActivity.kt
deleted file mode 100644
index a37f6d452..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/ExcludedFoldersActivity.kt
+++ /dev/null
@@ -1,64 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.graphics.PorterDuff
-import android.os.Bundle
-import android.view.Menu
-import android.view.MenuItem
-import com.simplemobiletools.commons.dialogs.FilePickerDialog
-import com.simplemobiletools.commons.extensions.beVisibleIf
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.extensions.config
-import kotlinx.android.synthetic.main.activity_excluded_folders.*
-import kotlinx.android.synthetic.main.item_manage_folder.view.*
-
-class ExcludedFoldersActivity : SimpleActivity() {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_excluded_folders)
- updateExcludedFolders()
- }
-
- private fun updateExcludedFolders() {
- excluded_folders_holder.removeAllViews()
- val folders = config.excludedFolders
- excluded_folders_placeholder.beVisibleIf(folders.isEmpty())
- excluded_folders_placeholder.setTextColor(config.textColor)
-
- for (folder in folders) {
- layoutInflater.inflate(R.layout.item_manage_folder, null, false).apply {
- managed_folder_title.apply {
- text = folder
- setTextColor(config.textColor)
- }
- managed_folders_icon.apply {
- setColorFilter(config.textColor, PorterDuff.Mode.SRC_IN)
- setOnClickListener {
- config.removeExcludedFolder(folder)
- updateExcludedFolders()
- }
- }
- excluded_folders_holder.addView(this)
- }
- }
- }
-
- override fun onCreateOptionsMenu(menu: Menu?): Boolean {
- menuInflater.inflate(R.menu.menu_excluded_folders, menu)
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.add_folder -> addExcludedFolder()
- else -> return super.onOptionsItemSelected(item)
- }
- return true
- }
-
- private fun addExcludedFolder() {
- FilePickerDialog(this, pickFile = false, showHidden = config.shouldShowHidden) {
- config.addExcludedFolder(it)
- updateExcludedFolders()
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/IncludedFoldersActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/IncludedFoldersActivity.kt
deleted file mode 100644
index f69f4f987..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/IncludedFoldersActivity.kt
+++ /dev/null
@@ -1,66 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.graphics.PorterDuff
-import android.os.Bundle
-import android.view.Menu
-import android.view.MenuItem
-import com.simplemobiletools.commons.dialogs.FilePickerDialog
-import com.simplemobiletools.commons.extensions.beVisibleIf
-import com.simplemobiletools.commons.extensions.scanPath
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.extensions.config
-import kotlinx.android.synthetic.main.activity_included_folders.*
-import kotlinx.android.synthetic.main.item_manage_folder.view.*
-
-class IncludedFoldersActivity : SimpleActivity() {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_included_folders)
- updateIncludedFolders()
- }
-
- private fun updateIncludedFolders() {
- included_folders_holder.removeAllViews()
- val folders = config.includedFolders
- included_folders_placeholder.beVisibleIf(folders.isEmpty())
- included_folders_placeholder.setTextColor(config.textColor)
-
- for (folder in folders) {
- layoutInflater.inflate(R.layout.item_manage_folder, null, false).apply {
- managed_folder_title.apply {
- text = folder
- setTextColor(config.textColor)
- }
- managed_folders_icon.apply {
- setColorFilter(config.textColor, PorterDuff.Mode.SRC_IN)
- setOnClickListener {
- config.removeIncludedFolder(folder)
- updateIncludedFolders()
- }
- }
- included_folders_holder.addView(this)
- }
- }
- }
-
- override fun onCreateOptionsMenu(menu: Menu?): Boolean {
- menuInflater.inflate(R.menu.menu_included_folders, menu)
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.add_folder -> addIncludedFolder()
- else -> return super.onOptionsItemSelected(item)
- }
- return true
- }
-
- private fun addIncludedFolder() {
- FilePickerDialog(this, pickFile = false, showHidden = config.shouldShowHidden) {
- config.addIncludedFolder(it)
- updateIncludedFolders()
- scanPath(it) {}
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/MainActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/MainActivity.kt
deleted file mode 100644
index 8e5c99539..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/MainActivity.kt
+++ /dev/null
@@ -1,441 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.Manifest
-import android.app.Activity
-import android.content.Intent
-import android.content.pm.PackageManager
-import android.net.Uri
-import android.os.AsyncTask
-import android.os.Build
-import android.os.Bundle
-import android.os.Handler
-import android.provider.MediaStore
-import android.support.v4.app.ActivityCompat
-import android.support.v7.widget.GridLayoutManager
-import android.view.Menu
-import android.view.MenuItem
-import com.google.gson.Gson
-import com.simplemobiletools.commons.extensions.*
-import com.simplemobiletools.commons.models.Release
-import com.simplemobiletools.gallery.BuildConfig
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.adapters.DirectoryAdapter
-import com.simplemobiletools.gallery.asynctasks.GetDirectoriesAsynctask
-import com.simplemobiletools.gallery.dialogs.ChangeSortingDialog
-import com.simplemobiletools.gallery.extensions.*
-import com.simplemobiletools.gallery.helpers.*
-import com.simplemobiletools.gallery.models.Directory
-import com.simplemobiletools.gallery.views.MyScalableRecyclerView
-import kotlinx.android.synthetic.main.activity_main.*
-import java.io.File
-import java.io.FileInputStream
-import java.io.InputStream
-import java.io.OutputStream
-import java.util.*
-
-class MainActivity : SimpleActivity(), DirectoryAdapter.DirOperationsListener {
- private val STORAGE_PERMISSION = 1
- private val PICK_MEDIA = 2
- private val PICK_WALLPAPER = 3
- private val LAST_MEDIA_CHECK_PERIOD = 3000L
-
- lateinit var mDirs: ArrayList
-
- private var mIsPickImageIntent = false
- private var mIsPickVideoIntent = false
- private var mIsGetImageContentIntent = false
- private var mIsGetVideoContentIntent = false
- private var mIsGetAnyContentIntent = false
- private var mIsSetWallpaperIntent = false
- private var mIsThirdPartyIntent = false
- private var mIsGettingDirs = false
- private var mStoredAnimateGifs = true
- private var mStoredCropThumbnails = true
- private var mLoadedInitialPhotos = false
- private var mLastMediaModified = 0
- private var mLastMediaHandler = Handler()
-
- private var mCurrAsyncTask: GetDirectoriesAsynctask? = null
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
-
- mIsPickImageIntent = isPickImageIntent(intent)
- mIsPickVideoIntent = isPickVideoIntent(intent)
- mIsGetImageContentIntent = isGetImageContentIntent(intent)
- mIsGetVideoContentIntent = isGetVideoContentIntent(intent)
- mIsGetAnyContentIntent = isGetAnyContentIntent(intent)
- mIsSetWallpaperIntent = isSetWallpaperIntent(intent)
- mIsThirdPartyIntent = mIsPickImageIntent || mIsPickVideoIntent || mIsGetImageContentIntent || mIsGetVideoContentIntent ||
- mIsGetAnyContentIntent || mIsSetWallpaperIntent
-
- directories_refresh_layout.setOnRefreshListener({ getDirectories() })
- mDirs = ArrayList()
- mStoredAnimateGifs = config.animateGifs
- mStoredCropThumbnails = config.cropThumbnails
- storeStoragePaths()
- checkWhatsNewDialog()
- }
-
- override fun onCreateOptionsMenu(menu: Menu): Boolean {
- if (mIsThirdPartyIntent) {
- menuInflater.inflate(R.menu.menu_main_intent, menu)
- } else {
- menuInflater.inflate(R.menu.menu_main, menu)
- menu.findItem(R.id.increase_column_count).isVisible = config.dirColumnCnt < 10
- menu.findItem(R.id.reduce_column_count).isVisible = config.dirColumnCnt > 1
- }
- menu.findItem(R.id.temporarily_show_hidden).isVisible = !config.showHiddenMedia
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.sort -> showSortingDialog()
- R.id.open_camera -> launchCamera()
- R.id.show_all -> showAllMedia()
- R.id.temporarily_show_hidden -> temporarilyShowHidden()
- R.id.increase_column_count -> increaseColumnCount()
- R.id.reduce_column_count -> reduceColumnCount()
- R.id.settings -> launchSettings()
- R.id.about -> launchAbout()
- else -> return super.onOptionsItemSelected(item)
- }
- return true
- }
-
- override fun onResume() {
- super.onResume()
- if (mStoredAnimateGifs != config.animateGifs) {
- mDirs.clear()
- }
-
- if (mStoredCropThumbnails != config.cropThumbnails) {
- mDirs.clear()
- }
- tryloadGallery()
- invalidateOptionsMenu()
- }
-
- override fun onPause() {
- super.onPause()
- mCurrAsyncTask?.shouldStop = true
- storeDirectories()
- directories_refresh_layout.isRefreshing = false
- mIsGettingDirs = false
- mStoredAnimateGifs = config.animateGifs
- mStoredCropThumbnails = config.cropThumbnails
- MyScalableRecyclerView.mListener = null
- mLastMediaHandler.removeCallbacksAndMessages(null)
- }
-
- override fun onDestroy() {
- super.onDestroy()
- config.temporarilyShowHidden = false
- }
-
- private fun tryloadGallery() {
- if (hasWriteStoragePermission()) {
- if (config.showAll)
- showAllMedia()
- else
- getDirectories()
- handleZooming()
- checkIfColorChanged()
- } else {
- ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_PERMISSION)
- }
- }
-
- override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults)
-
- if (requestCode == STORAGE_PERMISSION) {
- if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- getDirectories()
- } else {
- toast(R.string.no_storage_permissions)
- finish()
- }
- }
- }
-
- private fun getDirectories() {
- if (mIsGettingDirs)
- return
-
- mIsGettingDirs = true
- val dirs = getCachedDirectories()
- if (dirs.isNotEmpty() && !mLoadedInitialPhotos) {
- gotDirectories(dirs)
- }
-
- if (!mLoadedInitialPhotos) {
- directories_refresh_layout.isRefreshing = true
- }
-
- mLoadedInitialPhotos = true
- mCurrAsyncTask = GetDirectoriesAsynctask(applicationContext, mIsPickVideoIntent || mIsGetVideoContentIntent, mIsPickImageIntent || mIsGetImageContentIntent) {
- gotDirectories(it)
- }
- mCurrAsyncTask!!.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
- }
-
- private fun showSortingDialog() {
- ChangeSortingDialog(this, true, false) {
- getDirectories()
- }
- }
-
- private fun showAllMedia() {
- config.showAll = true
- Intent(this, MediaActivity::class.java).apply {
- putExtra(DIRECTORY, "/")
- startActivity(this)
- }
- finish()
- }
-
- private fun temporarilyShowHidden() {
- config.temporarilyShowHidden = true
- getDirectories()
- }
-
- private fun checkIfColorChanged() {
- if (directories_grid.adapter != null && getRecyclerAdapter().foregroundColor != config.primaryColor) {
- getRecyclerAdapter().updatePrimaryColor(config.primaryColor)
- directories_fastscroller.updateHandleColor()
- }
- }
-
- override fun tryDeleteFolders(folders: ArrayList) {
- for (file in folders) {
- deleteFolders(folders) {
- runOnUiThread {
- refreshItems()
- }
- }
- }
- }
-
- private fun getRecyclerAdapter() = (directories_grid.adapter as DirectoryAdapter)
-
- private fun handleZooming() {
- val layoutManager = directories_grid.layoutManager as GridLayoutManager
- layoutManager.spanCount = config.dirColumnCnt
- MyScalableRecyclerView.mListener = object : MyScalableRecyclerView.MyScalableRecyclerViewListener {
- override fun zoomIn() {
- if (layoutManager.spanCount > 1) {
- reduceColumnCount()
- getRecyclerAdapter().actMode?.finish()
- }
- }
-
- override fun zoomOut() {
- if (layoutManager.spanCount < 10) {
- increaseColumnCount()
- getRecyclerAdapter().actMode?.finish()
- }
- }
-
- override fun selectItem(position: Int) {
- getRecyclerAdapter().selectItem(position)
- }
-
- override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) {
- getRecyclerAdapter().selectRange(initialSelection, lastDraggedIndex, minReached, maxReached)
- }
- }
- }
-
- private fun increaseColumnCount() {
- config.dirColumnCnt = ++(directories_grid.layoutManager as GridLayoutManager).spanCount
- invalidateOptionsMenu()
- }
-
- private fun reduceColumnCount() {
- config.dirColumnCnt = --(directories_grid.layoutManager as GridLayoutManager).spanCount
- invalidateOptionsMenu()
- }
-
- private fun isPickImageIntent(intent: Intent) = isPickIntent(intent) && (hasImageContentData(intent) || isImageType(intent))
-
- private fun isPickVideoIntent(intent: Intent) = isPickIntent(intent) && (hasVideoContentData(intent) || isVideoType(intent))
-
- private fun isPickIntent(intent: Intent) = intent.action == Intent.ACTION_PICK
-
- private fun isGetContentIntent(intent: Intent) = intent.action == Intent.ACTION_GET_CONTENT && intent.type != null
-
- private fun isGetImageContentIntent(intent: Intent) = isGetContentIntent(intent) &&
- (intent.type.startsWith("image/") || intent.type == MediaStore.Images.Media.CONTENT_TYPE)
-
- private fun isGetVideoContentIntent(intent: Intent) = isGetContentIntent(intent) &&
- (intent.type.startsWith("video/") || intent.type == MediaStore.Video.Media.CONTENT_TYPE)
-
- private fun isGetAnyContentIntent(intent: Intent) = isGetContentIntent(intent) && intent.type == "*/*"
-
- private fun isSetWallpaperIntent(intent: Intent?) = intent?.action == Intent.ACTION_SET_WALLPAPER
-
- private fun hasImageContentData(intent: Intent) = (intent.data == MediaStore.Images.Media.EXTERNAL_CONTENT_URI ||
- intent.data == MediaStore.Images.Media.INTERNAL_CONTENT_URI)
-
- private fun hasVideoContentData(intent: Intent) = (intent.data == MediaStore.Video.Media.EXTERNAL_CONTENT_URI ||
- intent.data == MediaStore.Video.Media.INTERNAL_CONTENT_URI)
-
- private fun isImageType(intent: Intent) = (intent.type?.startsWith("image/") == true || intent.type == MediaStore.Images.Media.CONTENT_TYPE)
-
- private fun isVideoType(intent: Intent) = (intent.type?.startsWith("video/") == true || intent.type == MediaStore.Video.Media.CONTENT_TYPE)
-
- override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
- if (resultCode == Activity.RESULT_OK) {
- if (requestCode == PICK_MEDIA && resultData?.data != null) {
- Intent().apply {
- val path = resultData.data.path
- val uri = Uri.fromFile(File(path))
- if (mIsGetImageContentIntent || mIsGetVideoContentIntent || mIsGetAnyContentIntent) {
- if (intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true) {
- var inputStream: InputStream? = null
- var outputStream: OutputStream? = null
- try {
- val output = intent.extras.get(MediaStore.EXTRA_OUTPUT) as Uri
- inputStream = FileInputStream(File(path))
- outputStream = contentResolver.openOutputStream(output)
- inputStream.copyTo(outputStream)
- } finally {
- inputStream?.close()
- outputStream?.close()
- }
- } else {
- val type = File(path).getMimeType("image/jpeg")
- setDataAndTypeAndNormalize(uri, type)
- flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
- }
- } else if (mIsPickImageIntent || mIsPickVideoIntent) {
- data = uri
- flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
- }
-
- setResult(Activity.RESULT_OK, this)
- }
- finish()
- } else if (requestCode == PICK_WALLPAPER) {
- setResult(Activity.RESULT_OK)
- finish()
- }
- }
- super.onActivityResult(requestCode, resultCode, resultData)
- }
-
- private fun itemClicked(path: String) {
- Intent(this, MediaActivity::class.java).apply {
- putExtra(DIRECTORY, path)
-
- if (mIsSetWallpaperIntent) {
- putExtra(SET_WALLPAPER_INTENT, true)
- startActivityForResult(this, PICK_WALLPAPER)
- } else {
- putExtra(GET_IMAGE_INTENT, mIsPickImageIntent || mIsGetImageContentIntent)
- putExtra(GET_VIDEO_INTENT, mIsPickVideoIntent || mIsGetVideoContentIntent)
- putExtra(GET_ANY_INTENT, mIsGetAnyContentIntent)
- startActivityForResult(this, PICK_MEDIA)
- }
- }
- }
-
- private fun gotDirectories(dirs: ArrayList) {
- mLastMediaModified = getLastMediaModified()
- directories_refresh_layout.isRefreshing = false
- mIsGettingDirs = false
-
- checkLastMediaChanged()
- if (dirs.hashCode() == mDirs.hashCode())
- return
-
- mDirs = dirs
-
- setupAdapter()
- storeDirectories()
- }
-
- private fun storeDirectories() {
- if (!config.temporarilyShowHidden) {
- val directories = Gson().toJson(mDirs)
- config.directories = directories
- }
- }
-
- private fun setupAdapter() {
- val adapter = DirectoryAdapter(this, mDirs, this) {
- itemClicked(it.path)
- }
-
- val currAdapter = directories_grid.adapter
- if (currAdapter != null) {
- (currAdapter as DirectoryAdapter).updateDirs(mDirs)
- } else {
- directories_grid.adapter = adapter
- }
- directories_fastscroller.setViews(directories_grid, directories_refresh_layout)
- }
-
- private fun checkLastMediaChanged() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed)
- return
-
- mLastMediaHandler.removeCallbacksAndMessages(null)
- mLastMediaHandler.postDelayed({
- Thread({
- val lastModified = getLastMediaModified()
- if (mLastMediaModified != lastModified) {
- mLastMediaModified = lastModified
- runOnUiThread {
- getDirectories()
- }
- } else {
- checkLastMediaChanged()
- }
- }).start()
- }, LAST_MEDIA_CHECK_PERIOD)
- }
-
- override fun refreshItems() {
- getDirectories()
- }
-
- override fun itemLongClicked(position: Int) {
- directories_grid.setDragSelectActive(position)
- }
-
- private fun checkWhatsNewDialog() {
- arrayListOf().apply {
- add(Release(46, R.string.release_46))
- add(Release(47, R.string.release_47))
- add(Release(49, R.string.release_49))
- add(Release(50, R.string.release_50))
- add(Release(51, R.string.release_51))
- add(Release(52, R.string.release_52))
- add(Release(54, R.string.release_54))
- add(Release(58, R.string.release_58))
- add(Release(62, R.string.release_62))
- add(Release(65, R.string.release_65))
- add(Release(66, R.string.release_66))
- add(Release(69, R.string.release_69))
- add(Release(70, R.string.release_70))
- add(Release(72, R.string.release_72))
- add(Release(74, R.string.release_74))
- add(Release(76, R.string.release_76))
- add(Release(77, R.string.release_77))
- add(Release(83, R.string.release_83))
- add(Release(84, R.string.release_84))
- add(Release(88, R.string.release_88))
- add(Release(89, R.string.release_89))
- add(Release(93, R.string.release_93))
- add(Release(94, R.string.release_94))
- add(Release(97, R.string.release_97))
- add(Release(98, R.string.release_98))
- add(Release(108, R.string.release_108))
- checkWhatsNew(this, BuildConfig.VERSION_CODE)
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/MediaActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/MediaActivity.kt
deleted file mode 100644
index f6cefa981..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/MediaActivity.kt
+++ /dev/null
@@ -1,439 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.app.Activity
-import android.app.WallpaperManager
-import android.content.Intent
-import android.graphics.Bitmap
-import android.net.Uri
-import android.os.Build
-import android.os.Bundle
-import android.os.Handler
-import android.support.v7.widget.GridLayoutManager
-import android.util.Log
-import android.view.Menu
-import android.view.MenuItem
-import com.bumptech.glide.Glide
-import com.bumptech.glide.request.animation.GlideAnimation
-import com.bumptech.glide.request.target.SimpleTarget
-import com.google.gson.Gson
-import com.google.gson.reflect.TypeToken
-import com.simplemobiletools.commons.dialogs.ConfirmationDialog
-import com.simplemobiletools.commons.extensions.*
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.adapters.MediaAdapter
-import com.simplemobiletools.gallery.asynctasks.GetMediaAsynctask
-import com.simplemobiletools.gallery.dialogs.ChangeSortingDialog
-import com.simplemobiletools.gallery.dialogs.ExcludeFolderDialog
-import com.simplemobiletools.gallery.extensions.*
-import com.simplemobiletools.gallery.helpers.*
-import com.simplemobiletools.gallery.models.Medium
-import com.simplemobiletools.gallery.views.MyScalableRecyclerView
-import kotlinx.android.synthetic.main.activity_media.*
-import java.io.File
-import java.io.IOException
-
-class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
- private val TAG = MediaActivity::class.java.simpleName
- private val SAVE_MEDIA_CNT = 40
- private val LAST_MEDIA_CHECK_PERIOD = 3000L
-
- private var mPath = ""
- private var mIsGetImageIntent = false
- private var mIsGetVideoIntent = false
- private var mIsGetAnyIntent = false
- private var mIsGettingMedia = false
- private var mShowAll = false
- private var mLoadedInitialPhotos = false
- private var mStoredAnimateGifs = true
- private var mStoredCropThumbnails = true
- private var mLastDrawnHashCode = 0
- private var mLastMediaModified = 0
- private var mLastMediaHandler = Handler()
-
- companion object {
- var mMedia = ArrayList()
- }
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_media)
- intent.apply {
- mIsGetImageIntent = getBooleanExtra(GET_IMAGE_INTENT, false)
- mIsGetVideoIntent = getBooleanExtra(GET_VIDEO_INTENT, false)
- mIsGetAnyIntent = getBooleanExtra(GET_ANY_INTENT, false)
- }
-
- media_refresh_layout.setOnRefreshListener({ getMedia() })
- mPath = intent.getStringExtra(DIRECTORY)
- mStoredAnimateGifs = config.animateGifs
- mStoredCropThumbnails = config.cropThumbnails
- mShowAll = config.showAll
- if (mShowAll)
- supportActionBar?.setDisplayHomeAsUpEnabled(false)
- }
-
- override fun onResume() {
- super.onResume()
- if (mShowAll && mStoredAnimateGifs != config.animateGifs) {
- mMedia.clear()
- }
-
- if (mStoredCropThumbnails != config.cropThumbnails) {
- mMedia.clear()
- }
- tryloadGallery()
- invalidateOptionsMenu()
- }
-
- override fun onPause() {
- super.onPause()
- mIsGettingMedia = false
- media_refresh_layout.isRefreshing = false
- mStoredAnimateGifs = config.animateGifs
- mStoredCropThumbnails = config.cropThumbnails
- MyScalableRecyclerView.mListener = null
- mLastMediaHandler.removeCallbacksAndMessages(null)
- }
-
- override fun onDestroy() {
- super.onDestroy()
- if (config.showAll)
- config.temporarilyShowHidden = false
- mMedia.clear()
- }
-
- private fun tryloadGallery() {
- if (hasWriteStoragePermission()) {
- val dirName = getHumanizedFilename(mPath)
- title = if (mShowAll) resources.getString(R.string.all_folders) else dirName
- getMedia()
- handleZooming()
- checkIfColorChanged()
- } else {
- finish()
- }
- }
-
- private fun checkIfColorChanged() {
- if (media_grid.adapter != null && getRecyclerAdapter().foregroundColor != config.primaryColor) {
- getRecyclerAdapter().updatePrimaryColor(config.primaryColor)
- media_fastscroller.updateHandleColor()
- }
- }
-
- private fun setupAdapter() {
- if (isDirEmpty())
- return
-
- val adapter = MediaAdapter(this, mMedia, this) {
- itemClicked(it.path)
- }
-
- val currAdapter = media_grid.adapter
- if (currAdapter != null) {
- (currAdapter as MediaAdapter).updateMedia(mMedia)
- } else {
- media_grid.adapter = adapter
- }
- media_fastscroller.setViews(media_grid, media_refresh_layout)
- }
-
- private fun checkLastMediaChanged() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed)
- return
-
- mLastMediaHandler.removeCallbacksAndMessages(null)
- mLastMediaHandler.postDelayed({
- Thread({
- val lastModified = getLastMediaModified()
- if (mLastMediaModified != lastModified) {
- mLastMediaModified = lastModified
- runOnUiThread {
- getMedia()
- }
- } else {
- checkLastMediaChanged()
- }
- }).start()
- }, LAST_MEDIA_CHECK_PERIOD)
- }
-
- override fun onCreateOptionsMenu(menu: Menu): Boolean {
- menuInflater.inflate(R.menu.menu_media, menu)
-
- val isFolderHidden = File(mPath).containsNoMedia()
- menu.apply {
- findItem(R.id.hide_folder).isVisible = !isFolderHidden && !mShowAll
- findItem(R.id.unhide_folder).isVisible = isFolderHidden && !mShowAll
-
- findItem(R.id.folder_view).isVisible = mShowAll
- findItem(R.id.open_camera).isVisible = mShowAll
- findItem(R.id.about).isVisible = mShowAll
-
- findItem(R.id.temporarily_show_hidden).isVisible = !config.showHiddenMedia
-
- findItem(R.id.increase_column_count).isVisible = config.mediaColumnCnt < 10
- findItem(R.id.reduce_column_count).isVisible = config.mediaColumnCnt > 1
- }
-
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.sort -> showSortingDialog()
- R.id.toggle_filename -> toggleFilenameVisibility()
- R.id.open_camera -> launchCamera()
- R.id.folder_view -> switchToFolderView()
- R.id.hide_folder -> tryHideFolder()
- R.id.unhide_folder -> unhideFolder()
- R.id.exclude_folder -> tryExcludeFolder()
- R.id.temporarily_show_hidden -> temporarilyShowHidden()
- R.id.increase_column_count -> increaseColumnCount()
- R.id.reduce_column_count -> reduceColumnCount()
- R.id.settings -> launchSettings()
- R.id.about -> launchAbout()
- else -> return super.onOptionsItemSelected(item)
- }
- return true
- }
-
- private fun toggleFilenameVisibility() {
- config.displayFileNames = !config.displayFileNames
- if (media_grid.adapter != null)
- getRecyclerAdapter().updateDisplayFilenames(config.displayFileNames)
- }
-
- private fun showSortingDialog() {
- ChangeSortingDialog(this, false, !config.showAll, mPath) {
- getMedia()
- }
- }
-
- private fun switchToFolderView() {
- config.showAll = false
- startActivity(Intent(this, MainActivity::class.java))
- finish()
- }
-
- private fun tryHideFolder() {
- if (config.wasHideFolderTooltipShown) {
- hideFolder()
- } else {
- ConfirmationDialog(this, getString(R.string.hide_folder_description)) {
- config.wasHideFolderTooltipShown = true
- hideFolder()
- }
- }
- }
-
- private fun hideFolder() {
- addNoMedia(mPath) {
- runOnUiThread {
- if (!config.shouldShowHidden)
- finish()
- else
- invalidateOptionsMenu()
- }
- }
- }
-
- private fun unhideFolder() {
- removeNoMedia(mPath) {
- runOnUiThread {
- invalidateOptionsMenu()
- }
- }
- }
-
- private fun tryExcludeFolder() {
- ExcludeFolderDialog(this, arrayListOf(mPath)) {
- finish()
- }
- }
-
- private fun deleteDirectoryIfEmpty() {
- val file = File(mPath)
- if (!file.isDownloadsFolder() && file.isDirectory && file.listFiles()?.isEmpty() == true) {
- file.delete()
- }
- }
-
- private fun getMedia() {
- if (mIsGettingMedia)
- return
-
- mIsGettingMedia = true
- val token = object : TypeToken>() {}.type
- val media = Gson().fromJson>(config.loadFolderMedia(mPath), token) ?: ArrayList(1)
- if (media.isNotEmpty() && !mLoadedInitialPhotos) {
- gotMedia(media)
- } else {
- media_refresh_layout.isRefreshing = true
- }
-
- mLoadedInitialPhotos = true
- GetMediaAsynctask(applicationContext, mPath, mIsGetVideoIntent, mIsGetImageIntent, mShowAll) {
- gotMedia(it)
- }.execute()
- }
-
- private fun isDirEmpty(): Boolean {
- return if (mMedia.size <= 0) {
- deleteDirectoryIfEmpty()
- finish()
- true
- } else
- false
- }
-
- private fun temporarilyShowHidden() {
- config.temporarilyShowHidden = true
- getMedia()
- }
-
- private fun getRecyclerAdapter() = (media_grid.adapter as MediaAdapter)
-
- private fun handleZooming() {
- val layoutManager = media_grid.layoutManager as GridLayoutManager
- layoutManager.spanCount = config.mediaColumnCnt
- MyScalableRecyclerView.mListener = object : MyScalableRecyclerView.MyScalableRecyclerViewListener {
- override fun zoomIn() {
- if (layoutManager.spanCount > 1) {
- reduceColumnCount()
- getRecyclerAdapter().actMode?.finish()
- }
- }
-
- override fun zoomOut() {
- if (layoutManager.spanCount < 10) {
- increaseColumnCount()
- getRecyclerAdapter().actMode?.finish()
- }
- }
-
- override fun selectItem(position: Int) {
- getRecyclerAdapter().selectItem(position)
- }
-
- override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) {
- getRecyclerAdapter().selectRange(initialSelection, lastDraggedIndex, minReached, maxReached)
- }
- }
- }
-
- private fun increaseColumnCount() {
- config.mediaColumnCnt = ++(media_grid.layoutManager as GridLayoutManager).spanCount
- invalidateOptionsMenu()
- }
-
- private fun reduceColumnCount() {
- config.mediaColumnCnt = --(media_grid.layoutManager as GridLayoutManager).spanCount
- invalidateOptionsMenu()
- }
-
- private fun isSetWallpaperIntent() = intent.getBooleanExtra(SET_WALLPAPER_INTENT, false)
-
- override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
- if (requestCode == REQUEST_EDIT_IMAGE) {
- if (resultCode == Activity.RESULT_OK && resultData != null) {
- mMedia.clear()
- refreshItems()
- }
- }
- super.onActivityResult(requestCode, resultCode, resultData)
- }
-
- private fun itemClicked(path: String) {
- if (isSetWallpaperIntent()) {
- toast(R.string.setting_wallpaper)
-
- val wantedWidth = wallpaperDesiredMinimumWidth
- val wantedHeight = wallpaperDesiredMinimumHeight
- val ratio = wantedWidth.toFloat() / wantedHeight
- Glide.with(this)
- .load(File(path))
- .asBitmap()
- .override((wantedWidth * ratio).toInt(), wantedHeight)
- .fitCenter()
- .into(object : SimpleTarget() {
- override fun onResourceReady(bitmap: Bitmap?, glideAnimation: GlideAnimation?) {
- try {
- WallpaperManager.getInstance(applicationContext).setBitmap(bitmap)
- setResult(Activity.RESULT_OK)
- } catch (e: IOException) {
- Log.e(TAG, "item click $e")
- }
-
- finish()
- }
- })
- } else if (mIsGetImageIntent || mIsGetVideoIntent || mIsGetAnyIntent) {
- Intent().apply {
- data = Uri.parse(path)
- setResult(Activity.RESULT_OK, this)
- }
- finish()
- } else {
- val file = File(path)
- val isVideo = file.isVideoFast()
- if (isVideo) {
- openWith(file, false)
- } else {
- Intent(this, ViewPagerActivity::class.java).apply {
- putExtra(MEDIUM, path)
- putExtra(SHOW_ALL, mShowAll)
- startActivity(this)
- }
- }
- }
- }
-
- private fun gotMedia(media: ArrayList) {
- mLastMediaModified = getLastMediaModified()
- mIsGettingMedia = false
- media_refresh_layout.isRefreshing = false
-
- checkLastMediaChanged()
- if (mLastDrawnHashCode == 0)
- mLastDrawnHashCode = media.hashCode()
-
- if (media.hashCode() == mMedia.hashCode() && media.hashCode() == mLastDrawnHashCode)
- return
-
- mLastDrawnHashCode = media.hashCode()
- mMedia = media
- setupAdapter()
- storeFolder()
- }
-
- private fun storeFolder() {
- if (!config.temporarilyShowHidden) {
- val subList = mMedia.subList(0, Math.min(SAVE_MEDIA_CNT, mMedia.size))
- val json = Gson().toJson(subList)
- config.saveFolderMedia(mPath, json)
- }
- }
-
- override fun deleteFiles(files: ArrayList) {
- val filtered = files.filter { it.isImageVideoGif() } as ArrayList
- deleteFiles(filtered) {
- if (!it) {
- toast(R.string.unknown_error_occurred)
- } else if (mMedia.isEmpty()) {
- finish()
- }
- }
- }
-
- override fun refreshItems() {
- getMedia()
- Handler().postDelayed({
- getMedia()
- }, 1000)
- }
-
- override fun itemLongClicked(position: Int) {
- media_grid.setDragSelectActive(position)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/PhotoVideoActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/PhotoVideoActivity.kt
deleted file mode 100644
index 56e39f852..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/PhotoVideoActivity.kt
+++ /dev/null
@@ -1,166 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.Manifest
-import android.content.Intent
-import android.content.pm.PackageManager
-import android.database.Cursor
-import android.graphics.Color
-import android.graphics.drawable.ColorDrawable
-import android.net.Uri
-import android.os.Bundle
-import android.provider.MediaStore
-import android.support.v4.app.ActivityCompat
-import android.view.Menu
-import android.view.MenuItem
-import android.view.View
-import com.simplemobiletools.commons.extensions.hasWriteStoragePermission
-import com.simplemobiletools.commons.extensions.scanPath
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.extensions.*
-import com.simplemobiletools.gallery.fragments.PhotoFragment
-import com.simplemobiletools.gallery.fragments.VideoFragment
-import com.simplemobiletools.gallery.fragments.ViewPagerFragment
-import com.simplemobiletools.gallery.helpers.IS_VIEW_INTENT
-import com.simplemobiletools.gallery.helpers.MEDIUM
-import com.simplemobiletools.gallery.models.Medium
-import kotlinx.android.synthetic.main.fragment_holder.*
-import java.io.File
-
-open class PhotoVideoActivity : SimpleActivity(), ViewPagerFragment.FragmentListener {
- private val STORAGE_PERMISSION = 1
- private var mMedium: Medium? = null
- private var mIsFullScreen = false
-
- lateinit var mUri: Uri
- lateinit var mFragment: ViewPagerFragment
-
- companion object {
- var mIsVideo = false
- }
-
- public override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.fragment_holder)
-
- if (hasWriteStoragePermission()) {
- checkIntent(savedInstanceState)
- } else {
- ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_PERMISSION)
- }
- }
-
- private fun checkIntent(savedInstanceState: Bundle? = null) {
- mUri = intent.data ?: return
-
- if (mUri.scheme == "file") {
- scanPath(mUri.path) {}
- sendViewPagerIntent(mUri.path)
- finish()
- return
- } else {
- val path = applicationContext.getRealPathFromURI(mUri) ?: ""
- scanPath(mUri.path) {}
- if (path.isNotEmpty()) {
- sendViewPagerIntent(path)
- finish()
- return
- }
- }
-
- showSystemUI()
- val bundle = Bundle()
- val file = File(mUri.toString())
- mMedium = Medium(file.name, mUri.toString(), mIsVideo, 0, 0, file.length())
- bundle.putSerializable(MEDIUM, mMedium)
-
- if (savedInstanceState == null) {
- mFragment = if (mIsVideo) VideoFragment() else PhotoFragment()
- mFragment.listener = this
- mFragment.arguments = bundle
- supportFragmentManager.beginTransaction().replace(R.id.fragment_holder, mFragment).commit()
- }
-
- if (config.darkBackground)
- fragment_holder.background = ColorDrawable(Color.BLACK)
-
- val proj = arrayOf(MediaStore.Images.Media.TITLE)
- var cursor: Cursor? = null
- try {
- cursor = contentResolver.query(mUri, proj, null, null, null)
- if (cursor != null && cursor.count != 0) {
- val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE)
- cursor.moveToFirst()
- title = cursor.getString(columnIndex)
- }
- } catch (e: Exception) {
- title = mMedium?.name ?: ""
- } finally {
- cursor?.close()
- }
- }
-
- override fun onResume() {
- super.onResume()
- supportActionBar?.setBackgroundDrawable(resources.getDrawable(R.drawable.actionbar_gradient_background))
- }
-
- override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults)
-
- if (requestCode == STORAGE_PERMISSION) {
- if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- checkIntent()
- } else {
- toast(R.string.no_storage_permissions)
- finish()
- }
- }
- }
-
- private fun sendViewPagerIntent(path: String) {
- Intent(this, ViewPagerActivity::class.java).apply {
- putExtra(IS_VIEW_INTENT, true)
- putExtra(MEDIUM, path)
- startActivity(this)
- }
- }
-
- override fun onCreateOptionsMenu(menu: Menu): Boolean {
- menuInflater.inflate(R.menu.photo_video_menu, menu)
-
- menu.findItem(R.id.menu_set_as_wallpaper).isVisible = mMedium?.isImage() == true
- menu.findItem(R.id.menu_edit).isVisible = mMedium?.isImage() == true
-
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.menu_set_as_wallpaper -> trySetAsWallpaper(File(mMedium!!.path))
- R.id.menu_open_with -> openWith(File(mMedium!!.path))
- R.id.menu_share -> shareUri(mMedium!!, mUri)
- R.id.menu_edit -> openEditor(File(mMedium!!.path))
- else -> return super.onOptionsItemSelected(item)
- }
- return true
- }
-
- override fun fragmentClicked() {
- mIsFullScreen = !mIsFullScreen
- if (mIsFullScreen) {
- hideSystemUI()
- } else {
- showSystemUI()
- }
- }
-
- override fun systemUiVisibilityChanged(visibility: Int) {
- if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
- mIsFullScreen = false
- showSystemUI()
- } else {
- mIsFullScreen = true
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SettingsActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SettingsActivity.kt
deleted file mode 100644
index dfcb59d95..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SettingsActivity.kt
+++ /dev/null
@@ -1,156 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.content.Intent
-import android.content.res.Resources
-import android.os.Bundle
-import com.simplemobiletools.commons.dialogs.RadioGroupDialog
-import com.simplemobiletools.commons.extensions.updateTextColors
-import com.simplemobiletools.commons.models.RadioItem
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.extensions.config
-import com.simplemobiletools.gallery.helpers.*
-import kotlinx.android.synthetic.main.activity_settings.*
-
-class SettingsActivity : SimpleActivity() {
- lateinit var res: Resources
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_settings)
- res = resources
- }
-
- override fun onResume() {
- super.onResume()
-
- setupCustomizeColors()
- setupManageIncludedFolders()
- setupManageExcludedFolders()
- setupShowHiddenFolders()
- setupAutoplayVideos()
- setupLoopVideos()
- setupAnimateGifs()
- setupMaxBrightness()
- setupCropThumbnails()
- setupDarkBackground()
- setupScreenRotation()
- setupShowMedia()
- updateTextColors(settings_holder)
- }
-
- private fun setupCustomizeColors() {
- settings_customize_colors_holder.setOnClickListener {
- startCustomizationActivity()
- }
- }
-
- private fun setupManageIncludedFolders() {
- settings_manage_included_folders_holder.setOnClickListener {
- startActivity(Intent(this, IncludedFoldersActivity::class.java))
- }
- }
-
- private fun setupManageExcludedFolders() {
- settings_manage_excluded_folders_holder.setOnClickListener {
- startActivity(Intent(this, ExcludedFoldersActivity::class.java))
- }
- }
-
- private fun setupShowHiddenFolders() {
- settings_show_hidden_folders.isChecked = config.showHiddenMedia
- settings_show_hidden_folders_holder.setOnClickListener {
- settings_show_hidden_folders.toggle()
- config.showHiddenMedia = settings_show_hidden_folders.isChecked
- }
- }
-
- private fun setupAutoplayVideos() {
- settings_autoplay_videos.isChecked = config.autoplayVideos
- settings_autoplay_videos_holder.setOnClickListener {
- settings_autoplay_videos.toggle()
- config.autoplayVideos = settings_autoplay_videos.isChecked
- }
- }
-
- private fun setupLoopVideos() {
- settings_loop_videos.isChecked = config.loopVideos
- settings_loop_videos_holder.setOnClickListener {
- settings_loop_videos.toggle()
- config.loopVideos = settings_loop_videos.isChecked
- }
- }
-
- private fun setupAnimateGifs() {
- settings_animate_gifs.isChecked = config.animateGifs
- settings_animate_gifs_holder.setOnClickListener {
- settings_animate_gifs.toggle()
- config.animateGifs = settings_animate_gifs.isChecked
- }
- }
-
- private fun setupMaxBrightness() {
- settings_max_brightness.isChecked = config.maxBrightness
- settings_max_brightness_holder.setOnClickListener {
- settings_max_brightness.toggle()
- config.maxBrightness = settings_max_brightness.isChecked
- }
- }
-
- private fun setupCropThumbnails() {
- settings_crop_thumbnails.isChecked = config.cropThumbnails
- settings_crop_thumbnails_holder.setOnClickListener {
- settings_crop_thumbnails.toggle()
- config.cropThumbnails = settings_crop_thumbnails.isChecked
- }
- }
-
- private fun setupDarkBackground() {
- settings_dark_background.isChecked = config.darkBackground
- settings_dark_background_holder.setOnClickListener {
- settings_dark_background.toggle()
- config.darkBackground = settings_dark_background.isChecked
- }
- }
-
- private fun setupScreenRotation() {
- settings_screen_rotation.text = getScreenRotationText()
- settings_screen_rotation_holder.setOnClickListener {
- val items = arrayListOf(
- RadioItem(ROTATE_BY_SYSTEM_SETTING, res.getString(R.string.screen_rotation_system_setting)),
- RadioItem(ROTATE_BY_DEVICE_ROTATION, res.getString(R.string.screen_rotation_device_rotation)),
- RadioItem(ROTATE_BY_ASPECT_RATIO, res.getString(R.string.screen_rotation_aspect_ratio)))
-
- RadioGroupDialog(this@SettingsActivity, items, config.screenRotation) {
- config.screenRotation = it as Int
- settings_screen_rotation.text = getScreenRotationText()
- }
- }
- }
-
- private fun getScreenRotationText() = getString(when (config.screenRotation) {
- ROTATE_BY_SYSTEM_SETTING -> R.string.screen_rotation_system_setting
- ROTATE_BY_DEVICE_ROTATION -> R.string.screen_rotation_device_rotation
- else -> R.string.screen_rotation_aspect_ratio
- })
-
- private fun setupShowMedia() {
- settings_show_media.text = getShowMediaText()
- settings_show_media_holder.setOnClickListener {
- val items = arrayListOf(
- RadioItem(IMAGES_AND_VIDEOS, res.getString(R.string.images_and_videos)),
- RadioItem(IMAGES, res.getString(R.string.images)),
- RadioItem(VIDEOS, res.getString(R.string.videos)))
-
- RadioGroupDialog(this@SettingsActivity, items, config.showMedia) {
- config.showMedia = it as Int
- settings_show_media.text = getShowMediaText()
- }
- }
- }
-
- private fun getShowMediaText() = getString(when (config.showMedia) {
- IMAGES_AND_VIDEOS -> R.string.images_and_videos
- IMAGES -> R.string.images
- else -> R.string.videos
- })
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SimpleActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SimpleActivity.kt
deleted file mode 100644
index 6cfd6eb38..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SimpleActivity.kt
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import com.simplemobiletools.commons.activities.BaseSimpleActivity
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.dialogs.PickDirectoryDialog
-import java.io.File
-import java.util.*
-
-open class SimpleActivity : BaseSimpleActivity() {
- fun tryCopyMoveFilesTo(files: ArrayList, isCopyOperation: Boolean, callback: () -> Unit) {
- if (files.isEmpty()) {
- toast(R.string.unknown_error_occurred)
- return
- }
-
- val source = if (files[0].isFile) files[0].parent else files[0].absolutePath
- PickDirectoryDialog(this, source) {
- copyMoveFilesTo(files, source.trimEnd('/'), it, isCopyOperation, true, callback)
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SplashActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SplashActivity.kt
deleted file mode 100644
index 13e968dcf..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SplashActivity.kt
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.content.Intent
-import android.os.Bundle
-import android.support.v7.app.AppCompatActivity
-
-class SplashActivity : AppCompatActivity() {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- startActivity(Intent(this, MainActivity::class.java))
- finish()
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/ViewPagerActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/activities/ViewPagerActivity.kt
deleted file mode 100644
index fbd122166..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/ViewPagerActivity.kt
+++ /dev/null
@@ -1,543 +0,0 @@
-package com.simplemobiletools.gallery.activities
-
-import android.app.Activity
-import android.content.Intent
-import android.content.pm.ActivityInfo
-import android.content.res.Configuration
-import android.database.Cursor
-import android.graphics.Bitmap
-import android.graphics.BitmapFactory
-import android.graphics.Color
-import android.graphics.Matrix
-import android.graphics.drawable.ColorDrawable
-import android.hardware.SensorManager
-import android.media.ExifInterface
-import android.net.Uri
-import android.os.Build
-import android.os.Bundle
-import android.provider.MediaStore
-import android.support.v4.view.ViewPager
-import android.util.DisplayMetrics
-import android.view.Menu
-import android.view.MenuItem
-import android.view.OrientationEventListener
-import android.view.View
-import com.simplemobiletools.commons.dialogs.ConfirmationDialog
-import com.simplemobiletools.commons.dialogs.PropertiesDialog
-import com.simplemobiletools.commons.dialogs.RenameItemDialog
-import com.simplemobiletools.commons.extensions.*
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.MediaActivity.Companion.mMedia
-import com.simplemobiletools.gallery.adapters.MyPagerAdapter
-import com.simplemobiletools.gallery.asynctasks.GetMediaAsynctask
-import com.simplemobiletools.gallery.dialogs.SaveAsDialog
-import com.simplemobiletools.gallery.extensions.*
-import com.simplemobiletools.gallery.fragments.PhotoFragment
-import com.simplemobiletools.gallery.fragments.ViewPagerFragment
-import com.simplemobiletools.gallery.helpers.*
-import com.simplemobiletools.gallery.models.Medium
-import kotlinx.android.synthetic.main.activity_medium.*
-import java.io.File
-import java.io.OutputStream
-import java.util.*
-
-class ViewPagerActivity : SimpleActivity(), ViewPager.OnPageChangeListener, ViewPagerFragment.FragmentListener {
- lateinit var mOrientationEventListener: OrientationEventListener
- private var mPath = ""
- private var mDirectory = ""
-
- private var mIsFullScreen = false
- private var mPos = -1
- private var mShowAll = false
- private var mRotationDegrees = 0f
- private var mLastHandledOrientation = 0
- private var mPrevHashcode = 0
-
- companion object {
- var screenWidth = 0
- var screenHeight = 0
- }
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_medium)
-
- if (!hasWriteStoragePermission()) {
- finish()
- return
- }
-
- measureScreen()
- val uri = intent.data
- if (uri != null) {
- var cursor: Cursor? = null
- try {
- val proj = arrayOf(MediaStore.Images.Media.DATA)
- cursor = contentResolver.query(uri, proj, null, null, null)
- if (cursor?.moveToFirst() == true) {
- mPath = cursor.getStringValue(MediaStore.Images.Media.DATA)
- }
- } finally {
- cursor?.close()
- }
- } else {
- mPath = intent.getStringExtra(MEDIUM)
- mShowAll = config.showAll
- }
-
- if (mPath.isEmpty()) {
- toast(R.string.unknown_error_occurred)
- finish()
- return
- }
-
- if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) {
- config.temporarilyShowHidden = true
- }
-
- showSystemUI()
-
- mDirectory = File(mPath).parent
- title = mPath.getFilenameFromPath()
-
- if (mMedia.isNotEmpty()) {
- gotMedia(mMedia)
- }
-
- reloadViewPager()
- scanPath(mPath) {}
- setupOrientationEventListener()
-
- if (config.darkBackground)
- view_pager.background = ColorDrawable(Color.BLACK)
- }
-
- override fun onDestroy() {
- super.onDestroy()
- if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) {
- config.temporarilyShowHidden = false
- }
- }
-
- private fun setupOrientationEventListener() {
- mOrientationEventListener = object : OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
- override fun onOrientationChanged(orientation: Int) {
- val currOrient = if (orientation in 45..134) {
- ORIENT_LANDSCAPE_RIGHT
- } else if (orientation in 225..314) {
- ORIENT_LANDSCAPE_LEFT
- } else {
- ORIENT_PORTRAIT
- }
-
- if (mLastHandledOrientation != currOrient) {
- mLastHandledOrientation = currOrient
-
- if (currOrient == ORIENT_LANDSCAPE_LEFT) {
- requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
- } else if (currOrient == ORIENT_LANDSCAPE_RIGHT) {
- requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
- } else {
- requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
- }
- }
- }
- }
- }
-
- override fun onResume() {
- super.onResume()
- if (!hasWriteStoragePermission()) {
- finish()
- }
- supportActionBar?.setBackgroundDrawable(resources.getDrawable(R.drawable.actionbar_gradient_background))
-
- if (config.maxBrightness) {
- val attributes = window.attributes
- attributes.screenBrightness = 1f
- window.attributes = attributes
- }
-
- if (config.screenRotation == ROTATE_BY_DEVICE_ROTATION && mOrientationEventListener.canDetectOrientation()) {
- mOrientationEventListener.enable()
- } else if (config.screenRotation == ROTATE_BY_SYSTEM_SETTING) {
- requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
- }
- }
-
- override fun onPause() {
- super.onPause()
- mOrientationEventListener.disable()
- }
-
- override fun onCreateOptionsMenu(menu: Menu): Boolean {
- menuInflater.inflate(R.menu.menu_viewpager, menu)
- if (getCurrentMedium() == null)
- return true
-
- menu.apply {
- findItem(R.id.menu_set_as_wallpaper).isVisible = getCurrentMedium()!!.isImage() == true
- findItem(R.id.menu_edit).isVisible = getCurrentMedium()!!.isImage() == true
- findItem(R.id.menu_rotate).isVisible = getCurrentMedium()!!.isImage() == true
- findItem(R.id.menu_save_as).isVisible = mRotationDegrees != 0f
- findItem(R.id.menu_hide).isVisible = !getCurrentMedium()!!.name.startsWith('.')
- findItem(R.id.menu_unhide).isVisible = getCurrentMedium()!!.name.startsWith('.')
-
- findItem(R.id.menu_rotate).subMenu.apply {
- clearHeader()
- findItem(R.id.rotate_right).icon = resources.getColoredDrawable(R.drawable.ic_rotate_right, R.color.actionbar_menu_icon)
- findItem(R.id.rotate_left).icon = resources.getColoredDrawable(R.drawable.ic_rotate_left, R.color.actionbar_menu_icon)
- findItem(R.id.rotate_one_eighty).icon = resources.getColoredDrawable(R.drawable.ic_rotate_one_eighty, R.color.actionbar_menu_icon)
- }
- }
-
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- if (getCurrentMedium() == null)
- return true
-
- when (item.itemId) {
- R.id.menu_set_as_wallpaper -> trySetAsWallpaper(getCurrentFile())
- R.id.menu_copy_to -> copyMoveTo(true)
- R.id.menu_move_to -> copyMoveTo(false)
- R.id.menu_open_with -> openWith(getCurrentFile())
- R.id.menu_hide -> toggleFileVisibility(true)
- R.id.menu_unhide -> toggleFileVisibility(false)
- R.id.menu_share -> shareMedium(getCurrentMedium()!!)
- R.id.menu_delete -> askConfirmDelete()
- R.id.menu_rename -> renameFile()
- R.id.menu_edit -> openEditor(getCurrentFile())
- R.id.menu_properties -> showProperties()
- R.id.menu_save_as -> saveImageAs()
- R.id.show_on_map -> showOnMap()
- R.id.rotate_right -> rotateImage(90f)
- R.id.rotate_left -> rotateImage(-90f)
- R.id.rotate_one_eighty -> rotateImage(180f)
- R.id.settings -> launchSettings()
- else -> return super.onOptionsItemSelected(item)
- }
- return true
- }
-
- private fun updatePagerItems() {
- val pagerAdapter = MyPagerAdapter(this, supportFragmentManager, mMedia)
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !isDestroyed) {
- view_pager.apply {
- adapter = pagerAdapter
- currentItem = mPos
- addOnPageChangeListener(this@ViewPagerActivity)
- }
- }
- }
-
- private fun copyMoveTo(isCopyOperation: Boolean) {
- val files = ArrayList(1).apply { add(getCurrentFile()) }
- tryCopyMoveFilesTo(files, isCopyOperation) {
- if (!isCopyOperation) {
- reloadViewPager()
- }
- }
- }
-
- private fun toggleFileVisibility(hide: Boolean) {
- toggleFileVisibility(getCurrentFile(), hide) {
- val newFileName = it.absolutePath.getFilenameFromPath()
- title = newFileName
-
- getCurrentMedium()!!.apply {
- name = newFileName
- path = it.absolutePath
- mMedia[mPos] = this
- }
- invalidateOptionsMenu()
- }
- }
-
- private fun saveImageAs() {
- val currPath = getCurrentPath()
- SaveAsDialog(this, currPath) {
- Thread({
- toast(R.string.saving)
- val selectedFile = File(it)
- val tmpFile = File(selectedFile.parent, "tmp_${it.getFilenameFromPath()}")
- try {
- val bitmap = BitmapFactory.decodeFile(currPath)
- getFileOutputStream(tmpFile) {
- saveFile(tmpFile, bitmap, it)
- if (needsStupidWritePermissions(selectedFile.absolutePath)) {
- deleteFile(selectedFile) {}
- }
-
- renameFile(tmpFile, selectedFile) {
- deleteFile(tmpFile) {}
- }
- }
- } catch (e: OutOfMemoryError) {
- toast(R.string.out_of_memory_error)
- deleteFile(tmpFile) {}
- } catch (e: Exception) {
- toast(R.string.unknown_error_occurred)
- deleteFile(tmpFile) {}
- }
- }).start()
- }
- }
-
- private fun saveFile(file: File, bitmap: Bitmap, out: OutputStream) {
- val matrix = Matrix()
- matrix.postRotate(mRotationDegrees)
- val bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
- bmp.compress(file.getCompressionFormat(), 90, out)
- out.flush()
- toast(R.string.file_saved)
- out.close()
- }
-
- private fun rotateImage(degrees: Float) {
- mRotationDegrees = (mRotationDegrees + degrees) % 360
- getCurrentFragment()?.rotateImageViewBy(mRotationDegrees)
- supportInvalidateOptionsMenu()
- }
-
- private fun getCurrentFragment(): PhotoFragment? {
- val fragment = (view_pager.adapter as MyPagerAdapter).getCurrentFragment(view_pager.currentItem)
- return if (fragment is PhotoFragment)
- fragment
- else
- null
- }
-
- private fun showProperties() {
- if (getCurrentMedium() != null)
- PropertiesDialog(this, getCurrentPath(), false)
- }
-
- private fun showOnMap() {
- val exif = ExifInterface(getCurrentPath())
- val lat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE)
- val lat_ref = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF)
- val lon = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)
- val lon_ref = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF)
-
- if (lat == null || lat_ref == null || lon == null || lon_ref == null) {
- toast(R.string.unknown_location)
- } else {
- val geoLat = if (lat_ref == "N") {
- convertToDegree(lat)
- } else {
- 0 - convertToDegree(lat)
- }
-
- val geoLon = if (lon_ref == "E") {
- convertToDegree(lon)
- } else {
- 0 - convertToDegree(lon)
- }
-
- val uriBegin = "geo:$geoLat,$geoLon"
- val query = "$geoLat, $geoLon"
- val encodedQuery = Uri.encode(query)
- val uriString = "$uriBegin?q=$encodedQuery&z=16"
- val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uriString))
- val packageManager = packageManager
- if (intent.resolveActivity(packageManager) != null) {
- startActivity(intent)
- } else {
- toast(R.string.no_map_application)
- }
- }
- }
-
- private fun convertToDegree(stringDMS: String): Float {
- val dms = stringDMS.split(",".toRegex(), 3).toTypedArray()
-
- val stringD = dms[0].split("/".toRegex(), 2).toTypedArray()
- val d0 = stringD[0].toDouble()
- val d1 = stringD[1].toDouble()
- val floatD = d0 / d1
-
- val stringM = dms[1].split("/".toRegex(), 2).toTypedArray()
- val m0 = stringM[0].toDouble()
- val m1 = stringM[1].toDouble()
- val floatM = m0 / m1
-
- val stringS = dms[2].split("/".toRegex(), 2).toTypedArray()
- val s0 = stringS[0].toDouble()
- val s1 = stringS[1].toDouble()
- val floatS = s0 / s1
-
- return (floatD + floatM / 60 + floatS / 3600).toFloat()
- }
-
- override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
- if (requestCode == REQUEST_EDIT_IMAGE) {
- if (resultCode == Activity.RESULT_OK && resultData != null) {
- mPos = -1
- reloadViewPager()
- }
- } else if (requestCode == REQUEST_SET_WALLPAPER) {
- if (resultCode == Activity.RESULT_OK) {
- toast(R.string.wallpaper_set_successfully)
- }
- }
- super.onActivityResult(requestCode, resultCode, resultData)
- }
-
- private fun askConfirmDelete() {
- ConfirmationDialog(this) {
- deleteFileBg(File(mMedia[mPos].path)) {
- reloadViewPager()
- }
- }
- }
-
- private fun isDirEmpty(media: ArrayList): Boolean {
- return if (media.isEmpty()) {
- deleteDirectoryIfEmpty()
- finish()
- true
- } else
- false
- }
-
- private fun renameFile() {
- RenameItemDialog(this, getCurrentPath()) {
- mMedia[mPos].path = it
- updateActionbarTitle()
- }
- }
-
- override fun onConfigurationChanged(newConfig: Configuration?) {
- super.onConfigurationChanged(newConfig)
- measureScreen()
- }
-
- private fun measureScreen() {
- val metrics = DisplayMetrics()
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
- windowManager.defaultDisplay.getRealMetrics(metrics)
- screenWidth = metrics.widthPixels
- screenHeight = metrics.heightPixels
- } else {
- windowManager.defaultDisplay.getMetrics(metrics)
- screenWidth = metrics.widthPixels
- screenHeight = metrics.heightPixels
- }
- }
-
- private fun reloadViewPager() {
- GetMediaAsynctask(applicationContext, mDirectory, false, false, mShowAll) {
- gotMedia(it)
- }.execute()
- }
-
- private fun gotMedia(media: ArrayList) {
- if (isDirEmpty(media) || media.hashCode() == mPrevHashcode) {
- return
- }
-
- mPrevHashcode = media.hashCode()
- mMedia = media
- if (mPos == -1) {
- mPos = getProperPosition()
- } else {
- mPos = Math.min(mPos, mMedia.size - 1)
- }
-
- updateActionbarTitle()
- updatePagerItems()
- invalidateOptionsMenu()
- checkOrientation()
- }
-
- private fun getProperPosition(): Int {
- mPos = 0
- var i = 0
- for (medium in mMedia) {
- if (medium.path == mPath) {
- return i
- }
- i++
- }
- return mPos
- }
-
- private fun deleteDirectoryIfEmpty() {
- val file = File(mDirectory)
- if (!file.isDownloadsFolder() && file.isDirectory && file.listFiles()?.isEmpty() == true) {
- file.delete()
- }
-
- scanPath(mDirectory) {}
- }
-
- private fun checkOrientation() {
- if (config.screenRotation == ROTATE_BY_ASPECT_RATIO) {
- val res = getCurrentFile().getResolution()
- if (res.x > res.y) {
- requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
- } else if (res.x < res.y) {
- requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
- }
- }
- }
-
- override fun fragmentClicked() {
- mIsFullScreen = !mIsFullScreen
- if (mIsFullScreen) {
- hideSystemUI()
- } else {
- showSystemUI()
- }
- }
-
- override fun systemUiVisibilityChanged(visibility: Int) {
- if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
- mIsFullScreen = false
- showSystemUI()
- } else {
- mIsFullScreen = true
- }
- }
-
- private fun updateActionbarTitle() {
- runOnUiThread {
- if (mPos < mMedia.size) {
- title = mMedia[mPos].path.getFilenameFromPath()
- }
- }
- }
-
- private fun getCurrentMedium(): Medium? {
- return if (mMedia.isEmpty() || mPos == -1)
- null
- else
- mMedia[Math.min(mPos, mMedia.size - 1)]
- }
-
- private fun getCurrentPath() = getCurrentMedium()!!.path
-
- private fun getCurrentFile() = File(getCurrentPath())
-
- override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
-
- }
-
- override fun onPageSelected(position: Int) {
- if (view_pager.offscreenPageLimit == 1) {
- view_pager.offscreenPageLimit = 2
- }
- mPos = position
- updateActionbarTitle()
- mRotationDegrees = 0f
- supportInvalidateOptionsMenu()
- }
-
- override fun onPageScrollStateChanged(state: Int) {
- if (state == ViewPager.SCROLL_STATE_IDLE) {
- checkOrientation()
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/DirectoryAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/DirectoryAdapter.kt
deleted file mode 100644
index 7b76fb7a9..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/DirectoryAdapter.kt
+++ /dev/null
@@ -1,479 +0,0 @@
-package com.simplemobiletools.gallery.adapters
-
-import android.os.Build
-import android.support.v7.view.ActionMode
-import android.support.v7.widget.RecyclerView
-import android.util.SparseArray
-import android.view.*
-import android.widget.FrameLayout
-import com.bignerdranch.android.multiselector.ModalMultiSelectorCallback
-import com.bignerdranch.android.multiselector.MultiSelector
-import com.bignerdranch.android.multiselector.SwappingHolder
-import com.bumptech.glide.Glide
-import com.google.gson.Gson
-import com.simplemobiletools.commons.dialogs.ConfirmationDialog
-import com.simplemobiletools.commons.dialogs.PropertiesDialog
-import com.simplemobiletools.commons.dialogs.RenameItemDialog
-import com.simplemobiletools.commons.extensions.isAStorageRootFolder
-import com.simplemobiletools.commons.extensions.isImageVideoGif
-import com.simplemobiletools.commons.extensions.needsStupidWritePermissions
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import com.simplemobiletools.gallery.dialogs.ExcludeFolderDialog
-import com.simplemobiletools.gallery.dialogs.PickMediumDialog
-import com.simplemobiletools.gallery.extensions.*
-import com.simplemobiletools.gallery.models.AlbumCover
-import com.simplemobiletools.gallery.models.Directory
-import kotlinx.android.synthetic.main.directory_item.view.*
-import kotlinx.android.synthetic.main.directory_tmb.view.*
-import java.io.File
-import java.util.*
-
-class DirectoryAdapter(val activity: SimpleActivity, var dirs: MutableList, val listener: DirOperationsListener?, val itemClick: (Directory) -> Unit) :
- RecyclerView.Adapter() {
-
- val multiSelector = MultiSelector()
- val config = activity.config
-
- var actMode: ActionMode? = null
- var itemViews = SparseArray()
- val selectedPositions = HashSet()
- var foregroundColor = 0
- var pinnedFolders = config.pinnedFolders
-
- fun toggleItemSelection(select: Boolean, pos: Int) {
- if (itemViews[pos] != null)
- getProperView(itemViews[pos]!!).isSelected = select
-
- if (select)
- selectedPositions.add(pos)
- else
- selectedPositions.remove(pos)
-
- if (selectedPositions.isEmpty()) {
- actMode?.finish()
- return
- }
-
- updateTitle(selectedPositions.size)
- actMode?.invalidate()
- }
-
- fun getProperView(itemView: View): View {
- return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
- itemView.dir_frame
- else
- itemView.dir_thumbnail
- }
-
- fun updateTitle(cnt: Int) {
- actMode?.title = "$cnt / ${dirs.size}"
- }
-
- fun updatePrimaryColor(color: Int) {
- foregroundColor = color
- (0..itemViews.size() - 1).mapNotNull { itemViews[it] }
- .forEach { setupItemViewForeground(it) }
- }
-
- private fun setupItemViewForeground(itemView: View) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
- (getProperView(itemView) as FrameLayout).foreground = foregroundColor.createSelector()
- else
- getProperView(itemView).foreground = foregroundColor.createSelector()
- }
-
- val adapterListener = object : MyAdapterListener {
- override fun toggleItemSelectionAdapter(select: Boolean, position: Int) {
- toggleItemSelection(select, position)
- }
-
- override fun setupItemForeground(itemView: View) {
- setupItemViewForeground(itemView)
- }
-
- override fun getSelectedPositions(): HashSet = selectedPositions
- }
-
- init {
- foregroundColor = config.primaryColor
- }
-
- val multiSelectorMode = object : ModalMultiSelectorCallback(multiSelector) {
- override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.cab_properties -> showProperties()
- R.id.cab_rename -> renameDir()
- R.id.cab_pin -> pinFolders(true)
- R.id.cab_unpin -> pinFolders(false)
- R.id.cab_hide -> toggleFoldersVisibility(true)
- R.id.cab_unhide -> toggleFoldersVisibility(false)
- R.id.cab_exclude -> tryExcludeFolder()
- R.id.cab_copy_to -> copyMoveTo(true)
- R.id.cab_move_to -> copyMoveTo(false)
- R.id.cab_select_all -> selectAll()
- R.id.cab_delete -> askConfirmDelete()
- R.id.cab_select_photo -> changeAlbumCover(false)
- R.id.cab_use_default -> changeAlbumCover(true)
- else -> return false
- }
- return true
- }
-
- override fun onCreateActionMode(actionMode: ActionMode?, menu: Menu?): Boolean {
- super.onCreateActionMode(actionMode, menu)
- actMode = actionMode
- activity.menuInflater.inflate(R.menu.cab_directories, menu)
- return true
- }
-
- override fun onPrepareActionMode(actionMode: ActionMode?, menu: Menu): Boolean {
- menu.findItem(R.id.cab_rename).isVisible = selectedPositions.size <= 1
- menu.findItem(R.id.cab_change_cover_image).isVisible = selectedPositions.size <= 1
-
- checkHideBtnVisibility(menu)
- checkPinBtnVisibility(menu)
-
- return true
- }
-
- override fun onDestroyActionMode(actionMode: ActionMode?) {
- super.onDestroyActionMode(actionMode)
- selectedPositions.forEach {
- if (itemViews[it] != null)
- getProperView(itemViews[it]!!).isSelected = false
- }
- selectedPositions.clear()
- actMode = null
- }
-
- fun checkHideBtnVisibility(menu: Menu) {
- var hiddenCnt = 0
- var unhiddenCnt = 0
- selectedPositions.map { dirs.getOrNull(it)?.path }.filterNotNull().forEach {
- if (File(it).containsNoMedia())
- hiddenCnt++
- else
- unhiddenCnt++
- }
-
- menu.findItem(R.id.cab_hide).isVisible = unhiddenCnt > 0
- menu.findItem(R.id.cab_unhide).isVisible = hiddenCnt > 0
- }
-
- fun checkPinBtnVisibility(menu: Menu) {
- val pinnedFolders = config.pinnedFolders
- var pinnedCnt = 0
- var unpinnedCnt = 0
- selectedPositions.map { dirs.getOrNull(it)?.path }.filterNotNull().forEach {
- if (pinnedFolders.contains(it))
- pinnedCnt++
- else
- unpinnedCnt++
- }
-
- menu.findItem(R.id.cab_pin).isVisible = unpinnedCnt > 0
- menu.findItem(R.id.cab_unpin).isVisible = pinnedCnt > 0
- }
- }
-
- private fun showProperties() {
- if (selectedPositions.size <= 1) {
- PropertiesDialog(activity, dirs[selectedPositions.first()].path, config.shouldShowHidden)
- } else {
- val paths = ArrayList()
- selectedPositions.forEach { paths.add(dirs[it].path) }
- PropertiesDialog(activity, paths, config.shouldShowHidden)
- }
- }
-
- private fun renameDir() {
- val path = dirs[selectedPositions.first()].path
- val dir = File(path)
- if (activity.isAStorageRootFolder(dir.absolutePath)) {
- activity.toast(R.string.rename_folder_root)
- return
- }
-
- RenameItemDialog(activity, dir.absolutePath) {
- activity.runOnUiThread {
- listener?.refreshItems()
- actMode?.finish()
- }
- }
- }
-
- private fun toggleFoldersVisibility(hide: Boolean) {
- getSelectedPaths().forEach {
- if (hide) {
- if (config.wasHideFolderTooltipShown) {
- hideFolder(it)
- } else {
- config.wasHideFolderTooltipShown = true
- ConfirmationDialog(activity, activity.getString(R.string.hide_folder_description)) {
- hideFolder(it)
- }
- }
- } else {
- activity.removeNoMedia(it) {
- noMediaHandled()
- }
- }
- }
- }
-
- private fun hideFolder(path: String) {
- activity.addNoMedia(path) {
- noMediaHandled()
- }
- }
-
- private fun tryExcludeFolder() {
- ExcludeFolderDialog(activity, getSelectedPaths().toList()) {
- listener?.refreshItems()
- actMode?.finish()
- }
- }
-
- private fun noMediaHandled() {
- activity.runOnUiThread {
- listener?.refreshItems()
- actMode?.finish()
- }
- }
-
- private fun pinFolders(pin: Boolean) {
- if (pin)
- config.addPinnedFolders(getSelectedPaths())
- else
- config.removePinnedFolders(getSelectedPaths())
-
- pinnedFolders = config.pinnedFolders
- listener?.refreshItems()
- notifyDataSetChanged()
- actMode?.finish()
- }
-
- private fun copyMoveTo(isCopyOperation: Boolean) {
- if (selectedPositions.isEmpty())
- return
-
- val files = ArrayList()
- selectedPositions.forEach {
- val dir = File(dirs[it].path)
- files.addAll(dir.listFiles().filter { it.isFile && it.isImageVideoGif() })
- }
-
- activity.tryCopyMoveFilesTo(files, isCopyOperation) {
- listener?.refreshItems()
- actMode?.finish()
- }
- }
-
- fun selectAll() {
- val cnt = dirs.size
- for (i in 0..cnt - 1) {
- selectedPositions.add(i)
- notifyItemChanged(i)
- }
- updateTitle(cnt)
- actMode?.invalidate()
- }
-
- private fun askConfirmDelete() {
- ConfirmationDialog(activity) {
- deleteFiles()
- actMode?.finish()
- }
- }
-
- private fun deleteFiles() {
- val folders = ArrayList(selectedPositions.size)
- val removeFolders = ArrayList(selectedPositions.size)
-
- var needPermissionForPath = ""
- selectedPositions.forEach {
- val path = dirs[it].path
- if (activity.needsStupidWritePermissions(path) && config.treeUri.isEmpty()) {
- needPermissionForPath = path
- }
- }
-
- activity.handleSAFDialog(File(needPermissionForPath)) {
- selectedPositions.sortedDescending().forEach {
- val directory = dirs[it]
- folders.add(File(directory.path))
- removeFolders.add(directory)
- notifyItemRemoved(it)
- itemViews.put(it, null)
- }
-
- dirs.removeAll(removeFolders)
- selectedPositions.clear()
- listener?.tryDeleteFolders(folders)
-
- val newItems = SparseArray()
- var curIndex = 0
- for (i in 0..itemViews.size() - 1) {
- if (itemViews[i] != null) {
- newItems.put(curIndex, itemViews[i])
- curIndex++
- }
- }
-
- itemViews = newItems
- }
- }
-
- private fun changeAlbumCover(useDefault: Boolean) {
- if (selectedPositions.size != 1)
- return
-
- val path = dirs[selectedPositions.first()].path
- var albumCovers = config.parseAlbumCovers()
-
- if (useDefault) {
- albumCovers = albumCovers.filterNot { it.path == path } as ArrayList
- storeCovers(albumCovers)
- } else {
- PickMediumDialog(activity, path) {
- albumCovers = albumCovers.filterNot { it.path == path } as ArrayList
- albumCovers.add(AlbumCover(path, it))
- storeCovers(albumCovers)
- }
- }
- }
-
- private fun storeCovers(albumCovers: ArrayList) {
- activity.config.albumCovers = Gson().toJson(albumCovers)
- actMode?.finish()
- listener?.refreshItems()
- }
-
- private fun getSelectedPaths(): HashSet {
- val paths = HashSet(selectedPositions.size)
- selectedPositions.forEach { paths.add(dirs[it].path) }
- return paths
- }
-
- override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
- val view = LayoutInflater.from(parent?.context).inflate(R.layout.directory_item, parent, false)
- return ViewHolder(view, adapterListener, itemClick)
- }
-
- override fun onBindViewHolder(holder: ViewHolder, position: Int) {
- val dir = dirs[position]
- itemViews.put(position, holder.bindView(activity, multiSelectorMode, multiSelector, dir, pinnedFolders.contains(dir.path), listener))
- toggleItemSelection(selectedPositions.contains(position), position)
- holder.itemView.tag = holder
- }
-
- override fun onViewRecycled(holder: ViewHolder?) {
- super.onViewRecycled(holder)
- holder?.stopLoad()
- }
-
- override fun getItemCount() = dirs.size
-
- fun updateDirs(newDirs: ArrayList) {
- dirs = newDirs
- notifyDataSetChanged()
- }
-
- fun selectItem(pos: Int) {
- toggleItemSelection(true, pos)
- }
-
- fun selectRange(from: Int, to: Int, min: Int, max: Int) {
- if (from == to) {
- (min..max).filter { it != from }
- .forEach { toggleItemSelection(false, it) }
- return
- }
-
- if (to < from) {
- for (i in to..from)
- toggleItemSelection(true, i)
-
- if (min > -1 && min < to) {
- (min..to - 1).filter { it != from }
- .forEach { toggleItemSelection(false, it) }
- }
- if (max > -1) {
- for (i in from + 1..max)
- toggleItemSelection(false, i)
- }
- } else {
- for (i in from..to)
- toggleItemSelection(true, i)
-
- if (max > -1 && max > to) {
- (to + 1..max).filter { it != from }
- .forEach { toggleItemSelection(false, it) }
- }
-
- if (min > -1) {
- for (i in min..from - 1)
- toggleItemSelection(false, i)
- }
- }
- }
-
- class ViewHolder(val view: View, val adapter: MyAdapterListener, val itemClick: (Directory) -> (Unit)) : SwappingHolder(view, MultiSelector()) {
- fun bindView(activity: SimpleActivity, multiSelectorCallback: ModalMultiSelectorCallback, multiSelector: MultiSelector, directory: Directory,
- isPinned: Boolean, listener: DirOperationsListener?): View {
- itemView.apply {
- dir_name.text = directory.name
- photo_cnt.text = directory.mediaCnt.toString()
- dir_pin.visibility = if (isPinned) View.VISIBLE else View.GONE
- activity.loadImage(directory.tmb, dir_thumbnail)
-
- setOnClickListener { viewClicked(multiSelector, directory) }
- setOnLongClickListener {
- if (listener != null) {
- if (!multiSelector.isSelectable) {
- activity.startSupportActionMode(multiSelectorCallback)
- adapter.toggleItemSelectionAdapter(true, layoutPosition)
- }
-
- listener.itemLongClicked(layoutPosition)
- }
- true
- }
-
- adapter.setupItemForeground(this)
- }
- return itemView
- }
-
- fun viewClicked(multiSelector: MultiSelector, directory: Directory) {
- if (multiSelector.isSelectable) {
- val isSelected = adapter.getSelectedPositions().contains(layoutPosition)
- adapter.toggleItemSelectionAdapter(!isSelected, layoutPosition)
- } else {
- itemClick(directory)
- }
- }
-
- fun stopLoad() {
- Glide.clear(view.dir_thumbnail)
- }
- }
-
- interface MyAdapterListener {
- fun toggleItemSelectionAdapter(select: Boolean, position: Int)
-
- fun setupItemForeground(itemView: View)
-
- fun getSelectedPositions(): HashSet
- }
-
- interface DirOperationsListener {
- fun refreshItems()
-
- fun tryDeleteFolders(folders: ArrayList)
-
- fun itemLongClicked(position: Int)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MediaAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MediaAdapter.kt
deleted file mode 100644
index b0d7be70d..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MediaAdapter.kt
+++ /dev/null
@@ -1,394 +0,0 @@
-package com.simplemobiletools.gallery.adapters
-
-import android.os.Build
-import android.support.v7.view.ActionMode
-import android.support.v7.widget.RecyclerView
-import android.util.SparseArray
-import android.view.*
-import android.widget.FrameLayout
-import com.bignerdranch.android.multiselector.ModalMultiSelectorCallback
-import com.bignerdranch.android.multiselector.MultiSelector
-import com.bignerdranch.android.multiselector.SwappingHolder
-import com.bumptech.glide.Glide
-import com.simplemobiletools.commons.dialogs.ConfirmationDialog
-import com.simplemobiletools.commons.dialogs.PropertiesDialog
-import com.simplemobiletools.commons.dialogs.RenameItemDialog
-import com.simplemobiletools.commons.extensions.beVisibleIf
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import com.simplemobiletools.gallery.extensions.*
-import com.simplemobiletools.gallery.models.Medium
-import kotlinx.android.synthetic.main.photo_video_item.view.*
-import kotlinx.android.synthetic.main.photo_video_tmb.view.*
-import java.io.File
-import java.util.*
-
-class MediaAdapter(val activity: SimpleActivity, var media: MutableList, val listener: MediaOperationsListener?, val itemClick: (Medium) -> Unit) :
- RecyclerView.Adapter() {
-
- val multiSelector = MultiSelector()
- val config = activity.config
-
- var actMode: ActionMode? = null
- var itemViews = SparseArray()
- val selectedPositions = HashSet()
- var foregroundColor = 0
- var displayFilenames = config.displayFileNames
-
- fun toggleItemSelection(select: Boolean, pos: Int) {
- if (itemViews[pos] != null)
- getProperView(itemViews[pos]!!).isSelected = select
-
- if (select)
- selectedPositions.add(pos)
- else
- selectedPositions.remove(pos)
-
- if (selectedPositions.isEmpty()) {
- actMode?.finish()
- return
- }
-
- updateTitle(selectedPositions.size)
- actMode?.invalidate()
- }
-
- fun getProperView(itemView: View): View {
- return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
- itemView.medium_thumbnail_holder
- else
- itemView.medium_thumbnail
- }
-
- fun updateTitle(cnt: Int) {
- actMode?.title = "$cnt / ${media.size}"
- }
-
- fun updatePrimaryColor(color: Int) {
- foregroundColor = color
- (0..itemViews.size() - 1).mapNotNull { itemViews[it] }
- .forEach { setupItemViewForeground(it) }
- }
-
- private fun setupItemViewForeground(itemView: View) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
- (getProperView(itemView) as FrameLayout).foreground = foregroundColor.createSelector()
- else
- getProperView(itemView).foreground = foregroundColor.createSelector()
- }
-
- val adapterListener = object : MyAdapterListener {
- override fun toggleItemSelectionAdapter(select: Boolean, position: Int) {
- toggleItemSelection(select, position)
- }
-
- override fun setupItemForeground(itemView: View) {
- setupItemViewForeground(itemView)
- }
-
- override fun getSelectedPositions(): HashSet = selectedPositions
- }
-
- init {
- foregroundColor = config.primaryColor
- }
-
- val multiSelectorMode = object : ModalMultiSelectorCallback(multiSelector) {
- override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.cab_properties -> showProperties()
- R.id.cab_rename -> renameFile()
- R.id.cab_edit -> editFile()
- R.id.cab_hide -> toggleFileVisibility(true)
- R.id.cab_unhide -> toggleFileVisibility(false)
- R.id.cab_share -> shareMedia()
- R.id.cab_copy_to -> copyMoveTo(true)
- R.id.cab_move_to -> copyMoveTo(false)
- R.id.cab_select_all -> selectAll()
- R.id.cab_delete -> askConfirmDelete()
- else -> return false
- }
- return true
- }
-
- override fun onCreateActionMode(actionMode: ActionMode?, menu: Menu?): Boolean {
- super.onCreateActionMode(actionMode, menu)
- actMode = actionMode
- activity.menuInflater.inflate(R.menu.cab_media, menu)
- return true
- }
-
- override fun onPrepareActionMode(actionMode: ActionMode?, menu: Menu): Boolean {
- menu.findItem(R.id.cab_rename).isVisible = selectedPositions.size <= 1
- menu.findItem(R.id.cab_edit).isVisible = selectedPositions.size == 1 && media[selectedPositions.first()].isImage()
-
- checkHideBtnVisibility(menu)
-
- return true
- }
-
- override fun onDestroyActionMode(actionMode: ActionMode?) {
- super.onDestroyActionMode(actionMode)
- selectedPositions.forEach {
- if (itemViews[it] != null)
- getProperView(itemViews[it]!!).isSelected = false
- }
- selectedPositions.clear()
- actMode = null
- }
-
- fun checkHideBtnVisibility(menu: Menu) {
- var hiddenCnt = 0
- var unhiddenCnt = 0
- selectedPositions.map { media.getOrNull(it) }.filterNotNull().forEach {
- if (it.name.startsWith('.'))
- hiddenCnt++
- else
- unhiddenCnt++
- }
-
- menu.findItem(R.id.cab_hide).isVisible = unhiddenCnt > 0
- menu.findItem(R.id.cab_unhide).isVisible = hiddenCnt > 0
- }
- }
-
- private fun showProperties() {
- if (selectedPositions.size <= 1) {
- PropertiesDialog(activity, media[selectedPositions.first()].path, config.shouldShowHidden)
- } else {
- val paths = ArrayList()
- selectedPositions.forEach { paths.add(media[it].path) }
- PropertiesDialog(activity, paths, config.shouldShowHidden)
- }
- }
-
- private fun renameFile() {
- RenameItemDialog(activity, getCurrentFile().absolutePath) {
- activity.runOnUiThread {
- listener?.refreshItems()
- actMode?.finish()
- }
- }
- }
-
- private fun editFile() {
- activity.openEditor(getCurrentFile())
- actMode?.finish()
- }
-
- private fun toggleFileVisibility(hide: Boolean) {
- Thread({
- getSelectedMedia().forEach {
- val oldFile = File(it.path)
- activity.toggleFileVisibility(oldFile, hide) {}
- }
- activity.runOnUiThread {
- listener?.refreshItems()
- actMode?.finish()
- }
- }).start()
- }
-
- private fun shareMedia() {
- if (selectedPositions.size <= 1) {
- activity.shareMedium(getSelectedMedia()[0])
- } else {
- activity.shareMedia(getSelectedMedia())
- }
- }
-
- private fun copyMoveTo(isCopyOperation: Boolean) {
- val files = ArrayList()
- selectedPositions.forEach { files.add(File(media[it].path)) }
-
- activity.tryCopyMoveFilesTo(files, isCopyOperation) {
- if (!isCopyOperation) {
- listener?.refreshItems()
- }
- actMode?.finish()
- }
- }
-
- fun selectAll() {
- val cnt = media.size
- for (i in 0..cnt - 1) {
- selectedPositions.add(i)
- multiSelector.setSelected(i, 0, true)
- notifyItemChanged(i)
- }
- updateTitle(cnt)
- actMode?.invalidate()
- }
-
- private fun askConfirmDelete() {
- ConfirmationDialog(activity) {
- deleteFiles()
- actMode?.finish()
- }
- }
-
- private fun getCurrentFile() = File(media[selectedPositions.first()].path)
-
- private fun deleteFiles() {
- if (selectedPositions.isEmpty())
- return
-
- val files = ArrayList(selectedPositions.size)
- val removeMedia = ArrayList(selectedPositions.size)
-
- activity.handleSAFDialog(File(media[selectedPositions.first()].path)) {
- selectedPositions.sortedDescending().forEach {
- val medium = media[it]
- files.add(File(medium.path))
- removeMedia.add(medium)
- notifyItemRemoved(it)
- itemViews.put(it, null)
- }
-
- media.removeAll(removeMedia)
- selectedPositions.clear()
- listener?.deleteFiles(files)
-
- val newItems = SparseArray()
- var curIndex = 0
- for (i in 0..itemViews.size() - 1) {
- if (itemViews[i] != null) {
- newItems.put(curIndex, itemViews[i])
- curIndex++
- }
- }
-
- itemViews = newItems
- }
- }
-
- private fun getSelectedMedia(): List {
- val selectedMedia = ArrayList(selectedPositions.size)
- selectedPositions.forEach { selectedMedia.add(media[it]) }
- return selectedMedia
- }
-
- override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
- val view = LayoutInflater.from(parent?.context).inflate(R.layout.photo_video_item, parent, false)
- return ViewHolder(view, adapterListener, itemClick)
- }
-
- override fun onBindViewHolder(holder: ViewHolder, position: Int) {
- itemViews.put(position, holder.bindView(activity, multiSelectorMode, multiSelector, media[position], listener, displayFilenames))
- toggleItemSelection(selectedPositions.contains(position), position)
- holder.itemView.tag = holder
- }
-
- override fun onViewRecycled(holder: ViewHolder?) {
- super.onViewRecycled(holder)
- holder?.stopLoad()
- }
-
- override fun getItemCount() = media.size
-
- fun updateMedia(newMedia: ArrayList) {
- media = newMedia
- notifyDataSetChanged()
- }
-
- fun updateDisplayFilenames(display: Boolean) {
- displayFilenames = display
- notifyDataSetChanged()
- }
-
- fun selectItem(pos: Int) {
- toggleItemSelection(true, pos)
- }
-
- fun selectRange(from: Int, to: Int, min: Int, max: Int) {
- if (from == to) {
- (min..max).filter { it != from }
- .forEach { toggleItemSelection(false, it) }
- return
- }
-
- if (to < from) {
- for (i in to..from)
- toggleItemSelection(true, i)
-
- if (min > -1 && min < to) {
- (min..to - 1).filter { it != from }
- .forEach { toggleItemSelection(false, it) }
- }
- if (max > -1) {
- for (i in from + 1..max)
- toggleItemSelection(false, i)
- }
- } else {
- for (i in from..to)
- toggleItemSelection(true, i)
-
- if (max > -1 && max > to) {
- (to + 1..max).filter { it != from }
- .forEach { toggleItemSelection(false, it) }
- }
-
- if (min > -1) {
- for (i in min..from - 1)
- toggleItemSelection(false, i)
- }
- }
- }
-
- class ViewHolder(val view: View, val adapter: MyAdapterListener, val itemClick: (Medium) -> (Unit)) : SwappingHolder(view, MultiSelector()) {
- fun bindView(activity: SimpleActivity, multiSelectorCallback: ModalMultiSelectorCallback, multiSelector: MultiSelector, medium: Medium,
- listener: MediaOperationsListener?, displayFilenames: Boolean): View {
- itemView.apply {
- play_outline.visibility = if (medium.video) View.VISIBLE else View.GONE
- photo_name.beVisibleIf(displayFilenames)
- photo_name.text = medium.name
- activity.loadImage(medium.path, medium_thumbnail)
-
- setOnClickListener { viewClicked(multiSelector, medium) }
- setOnLongClickListener {
- if (listener != null) {
- if (!multiSelector.isSelectable) {
- activity.startSupportActionMode(multiSelectorCallback)
- adapter.toggleItemSelectionAdapter(true, layoutPosition)
- }
-
- listener.itemLongClicked(layoutPosition)
- }
- true
- }
-
- adapter.setupItemForeground(this)
- }
- return itemView
- }
-
- fun viewClicked(multiSelector: MultiSelector, medium: Medium) {
- if (multiSelector.isSelectable) {
- val isSelected = adapter.getSelectedPositions().contains(layoutPosition)
- adapter.toggleItemSelectionAdapter(!isSelected, layoutPosition)
- } else {
- itemClick(medium)
- }
- }
-
- fun stopLoad() {
- Glide.clear(view.medium_thumbnail)
- }
- }
-
- interface MyAdapterListener {
- fun toggleItemSelectionAdapter(select: Boolean, position: Int)
-
- fun setupItemForeground(itemView: View)
-
- fun getSelectedPositions(): HashSet
- }
-
- interface MediaOperationsListener {
- fun refreshItems()
-
- fun deleteFiles(files: ArrayList)
-
- fun itemLongClicked(position: Int)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MyPagerAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MyPagerAdapter.kt
deleted file mode 100644
index fbd05d975..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MyPagerAdapter.kt
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.simplemobiletools.gallery.adapters
-
-import android.os.Bundle
-import android.support.v4.app.Fragment
-import android.support.v4.app.FragmentManager
-import android.support.v4.app.FragmentStatePagerAdapter
-import android.support.v4.view.PagerAdapter
-import android.util.SparseArray
-import android.view.ViewGroup
-import com.simplemobiletools.gallery.activities.ViewPagerActivity
-import com.simplemobiletools.gallery.fragments.PhotoFragment
-import com.simplemobiletools.gallery.fragments.VideoFragment
-import com.simplemobiletools.gallery.fragments.ViewPagerFragment
-import com.simplemobiletools.gallery.helpers.MEDIUM
-import com.simplemobiletools.gallery.models.Medium
-
-class MyPagerAdapter(val activity: ViewPagerActivity, fm: FragmentManager, val media: MutableList) : FragmentStatePagerAdapter(fm) {
- private val mFragments = SparseArray()
- override fun getCount() = media.size
-
- override fun getItem(position: Int): Fragment {
- val medium = media[position]
- val bundle = Bundle()
- bundle.putSerializable(MEDIUM, medium)
- val fragment: ViewPagerFragment
-
- if (medium.video) {
- fragment = VideoFragment()
- } else {
- fragment = PhotoFragment()
- }
-
- fragment.arguments = bundle
- fragment.listener = activity
- return fragment
- }
-
- override fun getItemPosition(item: Any?) = PagerAdapter.POSITION_NONE
-
- override fun instantiateItem(container: ViewGroup?, position: Int): Any {
- val fragment = super.instantiateItem(container, position) as ViewPagerFragment
- mFragments.put(position, fragment)
- return fragment
- }
-
- override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) {
- mFragments.remove(position)
- super.destroyItem(container, position, `object`)
- }
-
- fun getCurrentFragment(position: Int) = mFragments.get(position)
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/asynctasks/GetDirectoriesAsynctask.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/asynctasks/GetDirectoriesAsynctask.kt
deleted file mode 100644
index 539e78e1e..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/asynctasks/GetDirectoriesAsynctask.kt
+++ /dev/null
@@ -1,124 +0,0 @@
-package com.simplemobiletools.gallery.asynctasks
-
-import android.content.Context
-import android.os.AsyncTask
-import com.simplemobiletools.commons.extensions.getFilenameFromPath
-import com.simplemobiletools.commons.extensions.hasWriteStoragePermission
-import com.simplemobiletools.commons.extensions.internalStoragePath
-import com.simplemobiletools.commons.extensions.sdCardPath
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.extensions.config
-import com.simplemobiletools.gallery.extensions.containsNoMedia
-import com.simplemobiletools.gallery.extensions.getFilesFrom
-import com.simplemobiletools.gallery.models.Directory
-import com.simplemobiletools.gallery.models.Medium
-import java.io.File
-import java.util.*
-
-class GetDirectoriesAsynctask(val context: Context, val isPickVideo: Boolean, val isPickImage: Boolean,
- val callback: (dirs: ArrayList) -> Unit) : AsyncTask>() {
- var config = context.config
- var shouldStop = false
- val showHidden = config.shouldShowHidden
-
- override fun doInBackground(vararg params: Void): ArrayList {
- if (!context.hasWriteStoragePermission())
- return ArrayList()
-
- val media = context.getFilesFrom("", isPickImage, isPickVideo)
- val excludedPaths = config.excludedFolders
- val directories = groupDirectories(media)
- val dirs = ArrayList(directories.values.filter { File(it.path).exists() }).filter { shouldFolderBeVisible(it.path, excludedPaths) } as ArrayList
- Directory.sorting = config.directorySorting
- dirs.sort()
- return movePinnedToFront(dirs)
- }
-
- private fun groupDirectories(media: ArrayList): Map {
- val albumCovers = config.parseAlbumCovers()
- val hidden = context.resources.getString(R.string.hidden)
- val directories = LinkedHashMap()
- for ((name, path, isVideo, dateModified, dateTaken, size) in media) {
- if (shouldStop)
- cancel(true)
-
- val parentDir = File(path).parent ?: continue
- if (directories.containsKey(parentDir)) {
- val directory = directories[parentDir]!!
- val newImageCnt = directory.mediaCnt + 1
- directory.mediaCnt = newImageCnt
- directory.addSize(size)
- } else {
- var dirName = parentDir.getFilenameFromPath()
- if (parentDir == context.internalStoragePath) {
- dirName = context.getString(R.string.internal)
- } else if (parentDir == context.sdCardPath) {
- dirName = context.getString(R.string.sd_card)
- }
-
- if (File(parentDir).containsNoMedia()) {
- dirName += " $hidden"
-
- if (!showHidden)
- continue
- }
-
- var thumbnail = path
- albumCovers.forEach {
- if (it.path == parentDir && File(it.tmb).exists()) {
- thumbnail = it.tmb
- }
- }
-
- val directory = Directory(parentDir, thumbnail, dirName, 1, dateModified, dateTaken, size)
- directories.put(parentDir, directory)
- }
- }
- return directories
- }
-
- private fun shouldFolderBeVisible(path: String, excludedPaths: MutableSet): Boolean {
- val file = File(path)
- return if (isThisOrParentExcluded(path, excludedPaths))
- false
- else if (!config.shouldShowHidden && file.isDirectory && file.canonicalFile == file.absoluteFile) {
- var containsNoMediaOrDot = file.containsNoMedia() || path.contains("/.")
- if (!containsNoMediaOrDot) {
- containsNoMediaOrDot = checkParentHasNoMedia(file.parentFile)
- }
- !containsNoMediaOrDot
- } else {
- true
- }
- }
-
- private fun checkParentHasNoMedia(file: File): Boolean {
- var curFile = file
- while (true) {
- if (curFile.containsNoMedia()) {
- return true
- }
- curFile = curFile.parentFile
- if (curFile.absolutePath == "/")
- break
- }
- return false
- }
-
- private fun isThisOrParentExcluded(path: String, excludedPaths: MutableSet) = excludedPaths.any { path.startsWith(it) }
-
- private fun movePinnedToFront(dirs: ArrayList): ArrayList {
- val foundFolders = ArrayList()
- val pinnedFolders = config.pinnedFolders
-
- dirs.forEach { if (pinnedFolders.contains(it.path)) foundFolders.add(it) }
- dirs.removeAll(foundFolders)
- dirs.addAll(0, foundFolders)
- return dirs
- }
-
- override fun onPostExecute(dirs: ArrayList) {
- super.onPostExecute(dirs)
- callback.invoke(dirs)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/asynctasks/GetMediaAsynctask.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/asynctasks/GetMediaAsynctask.kt
deleted file mode 100644
index 89342dc00..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/asynctasks/GetMediaAsynctask.kt
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.simplemobiletools.gallery.asynctasks
-
-import android.content.Context
-import android.os.AsyncTask
-import com.simplemobiletools.gallery.extensions.getFilesFrom
-import com.simplemobiletools.gallery.models.Medium
-import java.util.*
-
-class GetMediaAsynctask(val context: Context, val mPath: String, val isPickVideo: Boolean = false, val isPickImage: Boolean = false,
- val showAll: Boolean, val callback: (media: ArrayList) -> Unit) :
- AsyncTask>() {
-
- override fun doInBackground(vararg params: Void): ArrayList {
- val path = if (showAll) "" else mPath
- return context.getFilesFrom(path, isPickImage, isPickVideo)
- }
-
- override fun onPostExecute(media: ArrayList) {
- super.onPostExecute(media)
- callback.invoke(media)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/ChangeSortingDialog.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/ChangeSortingDialog.kt
deleted file mode 100644
index f6516ee9b..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/ChangeSortingDialog.kt
+++ /dev/null
@@ -1,90 +0,0 @@
-package com.simplemobiletools.gallery.dialogs
-
-import android.content.DialogInterface
-import android.support.v7.app.AlertDialog
-import android.view.LayoutInflater
-import android.view.View
-import com.simplemobiletools.commons.extensions.beVisibleIf
-import com.simplemobiletools.commons.extensions.setupDialogStuff
-import com.simplemobiletools.commons.helpers.*
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import com.simplemobiletools.gallery.extensions.config
-import com.simplemobiletools.gallery.helpers.Config
-import kotlinx.android.synthetic.main.dialog_change_sorting.view.*
-
-class ChangeSortingDialog(val activity: SimpleActivity, val isDirectorySorting: Boolean, showFolderCheckbox: Boolean,
- val path: String = "", val callback: () -> Unit) :
- DialogInterface.OnClickListener {
- private var currSorting = 0
- private var config: Config = activity.config
- private var view: View
-
- init {
- view = LayoutInflater.from(activity).inflate(R.layout.dialog_change_sorting, null).apply {
- use_for_this_folder_divider.beVisibleIf(showFolderCheckbox)
- sorting_dialog_use_for_this_folder.beVisibleIf(showFolderCheckbox)
- sorting_dialog_use_for_this_folder.isChecked = config.hasCustomSorting(path)
- }
-
- AlertDialog.Builder(activity)
- .setPositiveButton(R.string.ok, this)
- .setNegativeButton(R.string.cancel, null)
- .create().apply {
- activity.setupDialogStuff(view, this, R.string.sort_by)
- }
-
- currSorting = if (isDirectorySorting) config.directorySorting else config.getFileSorting(path)
- setupSortRadio()
- setupOrderRadio()
- }
-
- private fun setupSortRadio() {
- val sortingRadio = view.sorting_dialog_radio_sorting
- var sortBtn = sortingRadio.sorting_dialog_radio_name
-
- if (currSorting and SORT_BY_SIZE != 0) {
- sortBtn = sortingRadio.sorting_dialog_radio_size
- } else if (currSorting and SORT_BY_DATE_MODIFIED != 0) {
- sortBtn = sortingRadio.sorting_dialog_radio_last_modified
- } else if (currSorting and SORT_BY_DATE_TAKEN != 0)
- sortBtn = sortingRadio.sorting_dialog_radio_date_taken
- sortBtn.isChecked = true
- }
-
- private fun setupOrderRadio() {
- val orderRadio = view.sorting_dialog_radio_order
- var orderBtn = orderRadio.sorting_dialog_radio_ascending
-
- if (currSorting and SORT_DESCENDING != 0) {
- orderBtn = orderRadio.sorting_dialog_radio_descending
- }
- orderBtn.isChecked = true
- }
-
- override fun onClick(dialog: DialogInterface, which: Int) {
- val sortingRadio = view.sorting_dialog_radio_sorting
- var sorting = when (sortingRadio.checkedRadioButtonId) {
- R.id.sorting_dialog_radio_name -> SORT_BY_NAME
- R.id.sorting_dialog_radio_size -> SORT_BY_SIZE
- R.id.sorting_dialog_radio_last_modified -> SORT_BY_DATE_MODIFIED
- else -> SORT_BY_DATE_TAKEN
- }
-
- if (view.sorting_dialog_radio_order.checkedRadioButtonId == R.id.sorting_dialog_radio_descending) {
- sorting = sorting or SORT_DESCENDING
- }
-
- if (isDirectorySorting) {
- config.directorySorting = sorting
- } else {
- if (view.sorting_dialog_use_for_this_folder.isChecked) {
- config.saveFileSorting(path, sorting)
- } else {
- config.removeFileSorting(path)
- config.fileSorting = sorting
- }
- }
- callback.invoke()
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/PickDirectoryDialog.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/PickDirectoryDialog.kt
deleted file mode 100644
index cf384829e..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/PickDirectoryDialog.kt
+++ /dev/null
@@ -1,68 +0,0 @@
-package com.simplemobiletools.gallery.dialogs
-
-import android.support.v7.app.AlertDialog
-import android.support.v7.widget.RecyclerView
-import android.view.LayoutInflater
-import com.simplemobiletools.commons.dialogs.FilePickerDialog
-import com.simplemobiletools.commons.extensions.setupDialogStuff
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import com.simplemobiletools.gallery.adapters.DirectoryAdapter
-import com.simplemobiletools.gallery.asynctasks.GetDirectoriesAsynctask
-import com.simplemobiletools.gallery.extensions.config
-import com.simplemobiletools.gallery.extensions.getCachedDirectories
-import com.simplemobiletools.gallery.models.Directory
-import kotlinx.android.synthetic.main.dialog_directory_picker.view.*
-
-class PickDirectoryDialog(val activity: SimpleActivity, val sourcePath: String, val callback: (path: String) -> Unit) {
- var dialog: AlertDialog
- var directoriesGrid: RecyclerView
- var shownDirectories: ArrayList = ArrayList()
-
- init {
- val view = LayoutInflater.from(activity).inflate(R.layout.dialog_directory_picker, null)
- directoriesGrid = view.directories_grid
-
- dialog = AlertDialog.Builder(activity)
- .setPositiveButton(R.string.ok, null)
- .setNegativeButton(R.string.cancel, null)
- .setNeutralButton(R.string.other_folder, { dialogInterface, i -> showOtherFolder() })
- .create().apply {
- activity.setupDialogStuff(view, this, R.string.select_destination)
-
- val dirs = activity.getCachedDirectories()
- if (dirs.isNotEmpty()) {
- gotDirectories(dirs)
- }
-
- GetDirectoriesAsynctask(activity, false, false) {
- gotDirectories(it)
- }.execute()
- }
- }
-
- fun showOtherFolder() {
- val showHidden = activity.config.shouldShowHidden
- FilePickerDialog(activity, sourcePath, false, showHidden, true) {
- callback.invoke(it)
- }
- }
-
- private fun gotDirectories(directories: ArrayList) {
- if (directories.hashCode() == shownDirectories.hashCode())
- return
-
- shownDirectories = directories
- val adapter = DirectoryAdapter(activity, directories, null) {
- if (it.path.trimEnd('/') == sourcePath) {
- activity.toast(R.string.source_and_destination_same)
- return@DirectoryAdapter
- } else {
- callback.invoke(it.path)
- dialog.dismiss()
- }
- }
- directoriesGrid.adapter = adapter
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/PickMediumDialog.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/PickMediumDialog.kt
deleted file mode 100644
index 8d2bacf2b..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/PickMediumDialog.kt
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.simplemobiletools.gallery.dialogs
-
-import android.support.v7.app.AlertDialog
-import android.support.v7.widget.RecyclerView
-import android.view.LayoutInflater
-import com.google.gson.Gson
-import com.google.gson.reflect.TypeToken
-import com.simplemobiletools.commons.extensions.setupDialogStuff
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import com.simplemobiletools.gallery.adapters.MediaAdapter
-import com.simplemobiletools.gallery.asynctasks.GetMediaAsynctask
-import com.simplemobiletools.gallery.extensions.config
-import com.simplemobiletools.gallery.models.Medium
-import kotlinx.android.synthetic.main.dialog_medium_picker.view.*
-
-class PickMediumDialog(val activity: SimpleActivity, val path: String, val callback: (path: String) -> Unit) {
- var dialog: AlertDialog
- var mediaGrid: RecyclerView
- var shownMedia: ArrayList = ArrayList()
-
- init {
- val view = LayoutInflater.from(activity).inflate(R.layout.dialog_medium_picker, null)
- mediaGrid = view.media_grid
-
- dialog = AlertDialog.Builder(activity)
- .setPositiveButton(R.string.ok, null)
- .setNegativeButton(R.string.cancel, null)
- .create().apply {
- activity.setupDialogStuff(view, this, R.string.select_photo)
-
- val token = object : TypeToken>() {}.type
- val media = Gson().fromJson>(activity.config.loadFolderMedia(path), token) ?: ArrayList(1)
-
- if (media.isNotEmpty()) {
- gotMedia(media)
- }
-
- GetMediaAsynctask(activity, path, false, true, false) {
- gotMedia(it)
- }.execute()
- }
- }
-
- private fun gotMedia(media: ArrayList) {
- if (media.hashCode() == shownMedia.hashCode())
- return
-
- shownMedia = media
- val adapter = MediaAdapter(activity, media, null) {
- callback(it.path)
- dialog.dismiss()
- }
- mediaGrid.adapter = adapter
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/ResizeDialog.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/ResizeDialog.kt
deleted file mode 100644
index 0d339dcc8..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/ResizeDialog.kt
+++ /dev/null
@@ -1,97 +0,0 @@
-package com.simplemobiletools.gallery.dialogs
-
-import android.graphics.Point
-import android.support.v7.app.AlertDialog
-import android.text.Editable
-import android.text.TextWatcher
-import android.view.LayoutInflater
-import android.view.WindowManager
-import android.widget.EditText
-import com.simplemobiletools.commons.extensions.setupDialogStuff
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.commons.extensions.value
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import kotlinx.android.synthetic.main.resize_image.view.*
-
-class ResizeDialog(val activity: SimpleActivity, val size: Point, val callback: (newSize: Point) -> Unit) {
- init {
- val view = LayoutInflater.from(activity).inflate(R.layout.resize_image, null)
- val widthView = view.image_width
- val heightView = view.image_height
-
- widthView.setText(size.x.toString())
- heightView.setText(size.y.toString())
-
- val ratio = size.x / size.y.toFloat()
-
- widthView.addTextChangedListener(object : TextWatcher {
- override fun afterTextChanged(s: Editable?) {
- if (widthView.hasFocus()) {
- var width = getViewValue(widthView)
- if (width > size.x) {
- widthView.setText(size.x.toString())
- width = size.x
- }
-
- if (view.keep_aspect_ratio.isChecked) {
- heightView.setText((width / ratio).toInt().toString())
- }
- }
- }
-
- override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
- }
-
- override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
- }
- })
-
- heightView.addTextChangedListener(object : TextWatcher {
- override fun afterTextChanged(s: Editable?) {
- if (heightView.hasFocus()) {
- var height = getViewValue(heightView)
- if (height > size.y) {
- heightView.setText(size.y.toString())
- height = size.y
- }
-
- if (view.keep_aspect_ratio.isChecked) {
- widthView.setText((height * ratio).toInt().toString())
- }
- }
- }
-
- override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
- }
-
- override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
- }
- })
-
- AlertDialog.Builder(activity)
- .setPositiveButton(R.string.ok, null)
- .setNegativeButton(R.string.cancel, null)
- .create().apply {
- window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
- activity.setupDialogStuff(view, this, R.string.resize_and_save)
- getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener({
- val width = getViewValue(widthView)
- val height = getViewValue(heightView)
- if (width <= 0 || height <= 0) {
- activity.toast(R.string.invalid_values)
- return@setOnClickListener
- }
-
- val newSize = Point(getViewValue(widthView), getViewValue(heightView))
- callback.invoke(newSize)
- dismiss()
- })
- }
- }
-
- fun getViewValue(view: EditText): Int {
- val textValue = view.value
- return if (textValue.isEmpty()) 0 else textValue.toInt()
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/SaveAsDialog.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/SaveAsDialog.kt
deleted file mode 100644
index 3a5bd3320..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/SaveAsDialog.kt
+++ /dev/null
@@ -1,79 +0,0 @@
-package com.simplemobiletools.gallery.dialogs
-
-import android.support.v7.app.AlertDialog
-import android.view.LayoutInflater
-import android.view.WindowManager
-import com.simplemobiletools.commons.dialogs.ConfirmationDialog
-import com.simplemobiletools.commons.dialogs.FilePickerDialog
-import com.simplemobiletools.commons.extensions.*
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import kotlinx.android.synthetic.main.dialog_save_as.view.*
-import java.io.File
-
-class SaveAsDialog(val activity: SimpleActivity, val path: String, val callback: (savePath: String) -> Unit) {
-
- init {
- var realPath = File(path).parent.trimEnd('/')
- val view = LayoutInflater.from(activity).inflate(R.layout.dialog_save_as, null).apply {
- save_as_path.text = activity.humanizePath(realPath)
-
- val fullName = path.getFilenameFromPath()
- val dotAt = fullName.lastIndexOf(".")
- var name = fullName
-
- if (dotAt > 0) {
- name = fullName.substring(0, dotAt)
- val extension = fullName.substring(dotAt + 1)
- save_as_extension.setText(extension)
- }
-
- save_as_name.setText(name)
- save_as_path.setOnClickListener {
- FilePickerDialog(activity, realPath, false, false, true) {
- save_as_path.text = activity.humanizePath(it)
- realPath = it
- }
- }
- }
-
- AlertDialog.Builder(activity)
- .setPositiveButton(R.string.ok, null)
- .setNegativeButton(R.string.cancel, null)
- .create().apply {
- window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
- activity.setupDialogStuff(view, this, R.string.save_as)
- getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener({
- val filename = view.save_as_name.value
- val extension = view.save_as_extension.value
-
- if (filename.isEmpty()) {
- activity.toast(R.string.filename_cannot_be_empty)
- return@setOnClickListener
- }
-
- if (extension.isEmpty()) {
- activity.toast(R.string.extension_cannot_be_empty)
- return@setOnClickListener
- }
-
- val newFile = File(realPath, "$filename.$extension")
- if (!newFile.name.isAValidFilename()) {
- activity.toast(R.string.filename_invalid_characters)
- return@setOnClickListener
- }
-
- if (newFile.exists()) {
- val title = String.format(activity.getString(R.string.file_already_exists_overwrite), newFile.name)
- ConfirmationDialog(activity, title) {
- callback.invoke(newFile.absolutePath)
- dismiss()
- }
- } else {
- callback.invoke(newFile.absolutePath)
- dismiss()
- }
- })
- }
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/Int.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/Int.kt
deleted file mode 100644
index 064c348b6..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/Int.kt
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.simplemobiletools.gallery.extensions
-
-import android.content.res.ColorStateList
-import android.graphics.Color
-import android.graphics.drawable.ColorDrawable
-import android.graphics.drawable.RippleDrawable
-import android.graphics.drawable.StateListDrawable
-import android.os.Build
-import com.simplemobiletools.commons.extensions.adjustAlpha
-
-fun Int.createSelector(): StateListDrawable {
- val statelist = StateListDrawable()
- val selectedDrawable = ColorDrawable(adjustAlpha(0.5f))
- statelist.addState(intArrayOf(android.R.attr.state_selected), selectedDrawable)
-
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
- val pressedDrawable = ColorDrawable(adjustAlpha(0.2f))
- statelist.addState(intArrayOf(android.R.attr.state_pressed), pressedDrawable)
- } else {
- val pressedDrawable = RippleDrawable(ColorStateList.valueOf(adjustAlpha(0.2f)), null, ColorDrawable(Color.WHITE))
- statelist.addState(intArrayOf(), pressedDrawable)
- }
- return statelist
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/activity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/activity.kt
deleted file mode 100644
index b1663b850..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/activity.kt
+++ /dev/null
@@ -1,328 +0,0 @@
-package com.simplemobiletools.gallery.extensions
-
-import android.app.Activity
-import android.content.Intent
-import android.database.Cursor
-import android.net.Uri
-import android.os.Build
-import android.provider.MediaStore
-import android.support.v7.app.AppCompatActivity
-import android.util.DisplayMetrics
-import android.view.KeyCharacterMap
-import android.view.KeyEvent
-import android.view.View
-import android.view.ViewConfiguration
-import com.bumptech.glide.Glide
-import com.bumptech.glide.load.DecodeFormat
-import com.bumptech.glide.load.engine.DiskCacheStrategy
-import com.bumptech.glide.signature.StringSignature
-import com.google.gson.Gson
-import com.google.gson.reflect.TypeToken
-import com.simplemobiletools.commons.extensions.*
-import com.simplemobiletools.commons.helpers.*
-import com.simplemobiletools.gallery.BuildConfig
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.SimpleActivity
-import com.simplemobiletools.gallery.helpers.NOMEDIA
-import com.simplemobiletools.gallery.helpers.REQUEST_EDIT_IMAGE
-import com.simplemobiletools.gallery.helpers.REQUEST_SET_WALLPAPER
-import com.simplemobiletools.gallery.models.Directory
-import com.simplemobiletools.gallery.models.Medium
-import com.simplemobiletools.gallery.views.MySquareImageView
-import java.io.File
-import java.util.*
-
-fun Activity.shareUri(medium: Medium, uri: Uri) {
- val shareTitle = resources.getString(R.string.share_via)
- Intent().apply {
- action = Intent.ACTION_SEND
- putExtra(Intent.EXTRA_STREAM, uri)
- type = medium.getMimeType()
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- startActivity(Intent.createChooser(this, shareTitle))
- }
-}
-
-fun Activity.shareMedium(medium: Medium) {
- val shareTitle = resources.getString(R.string.share_via)
- val file = File(medium.path)
- val uri = Uri.fromFile(file)
- Intent().apply {
- action = Intent.ACTION_SEND
- putExtra(Intent.EXTRA_STREAM, uri)
- type = medium.getMimeType()
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- startActivity(Intent.createChooser(this, shareTitle))
- }
-}
-
-fun Activity.shareMedia(media: List) {
- val shareTitle = resources.getString(R.string.share_via)
- val uris = ArrayList(media.size)
- Intent().apply {
- action = Intent.ACTION_SEND_MULTIPLE
- type = "image/* video/*"
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- media.map { File(it.path) }
- .mapTo(uris) { Uri.fromFile(it) }
-
- putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
- startActivity(Intent.createChooser(this, shareTitle))
- }
-}
-
-fun Activity.trySetAsWallpaper(file: File) {
- try {
- var uri = Uri.fromFile(file)
- if (!setAsWallpaper(uri, file)) {
- uri = getFileContentUri(file)
- setAsWallpaper(uri, file, false)
- }
- } catch (e: Exception) {
- toast(R.string.unknown_error_occurred)
- }
-}
-
-fun Activity.setAsWallpaper(uri: Uri, file: File, showToast: Boolean = true): Boolean {
- var success = false
- Intent().apply {
- action = Intent.ACTION_ATTACH_DATA
- setDataAndType(uri, file.getMimeType("image/*"))
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- val chooser = Intent.createChooser(this, getString(R.string.set_as_wallpaper_with))
-
- if (resolveActivity(packageManager) != null) {
- startActivityForResult(chooser, REQUEST_SET_WALLPAPER)
- success = true
- } else {
- if (showToast) {
- toast(R.string.no_wallpaper_setter_found)
- }
- success = false
- }
- }
-
- return success
-}
-
-fun Activity.getFileContentUri(file: File): Uri? {
- val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
- val projection = arrayOf(MediaStore.Images.Media._ID)
- val selection = "${MediaStore.Images.Media.DATA} = ?"
- val selectionArgs = arrayOf(file.absolutePath)
-
- var cursor: Cursor? = null
- try {
- cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
- if (cursor?.moveToFirst() == true) {
- val id = cursor.getIntValue(MediaStore.Images.Media._ID)
- return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "$id")
- }
- } finally {
- cursor?.close()
- }
- return null
-}
-
-fun Activity.openWith(file: File, forceChooser: Boolean = true) {
- val uri = Uri.fromFile(file)
- Intent().apply {
- action = Intent.ACTION_VIEW
- setDataAndType(uri, file.getMimeType())
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- val chooser = Intent.createChooser(this, getString(R.string.open_with))
-
- if (resolveActivity(packageManager) != null) {
- startActivity(if (forceChooser) chooser else this)
- } else {
- toast(R.string.no_app_found)
- }
- }
-}
-
-fun Activity.openEditor(file: File) {
- val uri = Uri.fromFile(file)
- Intent().apply {
- action = Intent.ACTION_EDIT
- setDataAndType(uri, "image/*")
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
-
- if (resolveActivity(packageManager) != null) {
- startActivityForResult(this, REQUEST_EDIT_IMAGE)
- } else {
- toast(R.string.no_editor_found)
- }
- }
-}
-
-fun Activity.hasNavBar(): Boolean {
- return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
- val display = windowManager.defaultDisplay
-
- val realDisplayMetrics = DisplayMetrics()
- display.getRealMetrics(realDisplayMetrics)
-
- val realHeight = realDisplayMetrics.heightPixels
- val realWidth = realDisplayMetrics.widthPixels
-
- val displayMetrics = DisplayMetrics()
- display.getMetrics(displayMetrics)
-
- val displayHeight = displayMetrics.heightPixels
- val displayWidth = displayMetrics.widthPixels
-
- realWidth - displayWidth > 0 || realHeight - displayHeight > 0
- } else {
- val hasMenuKey = ViewConfiguration.get(applicationContext).hasPermanentMenuKey()
- val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
- !hasMenuKey && !hasBackKey
- }
-}
-
-fun Activity.launchCamera() {
- val intent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
- if (intent.resolveActivity(packageManager) != null) {
- startActivity(intent)
- } else {
- toast(R.string.no_camera_app_found)
- }
-}
-
-fun SimpleActivity.launchAbout() {
- startAboutActivity(R.string.app_name, LICENSE_KOTLIN or LICENSE_GLIDE or LICENSE_CROPPER or LICENSE_MULTISELECT or LICENSE_RTL
- or LICENSE_PHOTOVIEW or LICENSE_SUBSAMPLING, BuildConfig.VERSION_NAME)
-}
-
-fun AppCompatActivity.showSystemUI() {
- supportActionBar?.show()
- window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
- View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
- View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
-}
-
-fun AppCompatActivity.hideSystemUI() {
- supportActionBar?.hide()
- window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
- View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
- View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
- View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
- View.SYSTEM_UI_FLAG_LOW_PROFILE or
- View.SYSTEM_UI_FLAG_FULLSCREEN or
- View.SYSTEM_UI_FLAG_IMMERSIVE
-}
-
-fun SimpleActivity.addNoMedia(path: String, callback: () -> Unit) {
- val file = File(path, NOMEDIA)
- if (file.exists())
- return
-
- if (needsStupidWritePermissions(path)) {
- handleSAFDialog(file) {
- try {
- getFileDocument(path)?.createFile("", NOMEDIA)
- } catch (e: Exception) {
- toast(R.string.unknown_error_occurred)
- }
- }
- } else {
- try {
- file.createNewFile()
- } catch (e: Exception) {
- toast(R.string.unknown_error_occurred)
- }
- }
- scanFile(file) {
- callback()
- }
-}
-
-fun SimpleActivity.removeNoMedia(path: String, callback: () -> Unit) {
- val file = File(path, NOMEDIA)
- deleteFile(file) {
- callback()
- }
-}
-
-fun SimpleActivity.toggleFileVisibility(oldFile: File, hide: Boolean, callback: (newFile: File) -> Unit) {
- val path = oldFile.parent
- var filename = oldFile.name
- if (hide) {
- filename = ".${filename.trimStart('.')}"
- } else {
- filename = filename.substring(1, filename.length)
- }
- val newFile = File(path, filename)
- renameFile(oldFile, newFile) {
- newFile.setLastModified(System.currentTimeMillis())
- callback(newFile)
- }
-}
-
-fun Activity.getFileSignature(path: String) = StringSignature(File(path).lastModified().toString())
-
-fun Activity.loadImage(path: String, target: MySquareImageView) {
- if (path.isImageFast() || path.isVideoFast()) {
- if (path.isPng()) {
- loadPng(path, target)
- } else {
- loadJpg(path, target)
- }
- } else if (path.isGif()) {
- if (config.animateGifs) {
- loadAnimatedGif(path, target)
- } else {
- loadStaticGif(path, target)
- }
- }
-}
-
-fun Activity.loadPng(path: String, target: MySquareImageView) {
- val builder = Glide.with(applicationContext)
- .load(path)
- .asBitmap()
- .signature(getFileSignature(path))
- .diskCacheStrategy(DiskCacheStrategy.RESULT)
- .format(DecodeFormat.PREFER_ARGB_8888)
-
- if (config.cropThumbnails) builder.centerCrop() else builder.fitCenter()
- builder.into(target)
-}
-
-fun Activity.loadJpg(path: String, target: MySquareImageView) {
- val builder = Glide.with(applicationContext)
- .load(path)
- .signature(getFileSignature(path))
- .diskCacheStrategy(DiskCacheStrategy.RESULT)
- .crossFade()
-
- if (config.cropThumbnails) builder.centerCrop() else builder.fitCenter()
- builder.into(target)
-}
-
-fun Activity.loadAnimatedGif(path: String, target: MySquareImageView) {
- val builder = Glide.with(applicationContext)
- .load(path)
- .asGif()
- .signature(getFileSignature(path))
- .diskCacheStrategy(DiskCacheStrategy.SOURCE)
- .crossFade()
-
- if (config.cropThumbnails) builder.centerCrop() else builder.fitCenter()
- builder.into(target)
-}
-
-fun Activity.loadStaticGif(path: String, target: MySquareImageView) {
- val builder = Glide.with(applicationContext)
- .load(path)
- .asBitmap()
- .signature(getFileSignature(path))
- .diskCacheStrategy(DiskCacheStrategy.SOURCE)
-
- if (config.cropThumbnails) builder.centerCrop() else builder.fitCenter()
- builder.into(target)
-}
-
-fun Activity.getCachedDirectories(): ArrayList {
- val token = object : TypeToken>() {}.type
- return Gson().fromJson>(config.directories, token) ?: ArrayList(1)
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/context.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/context.kt
deleted file mode 100644
index 9df154732..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/context.kt
+++ /dev/null
@@ -1,236 +0,0 @@
-package com.simplemobiletools.gallery.extensions
-
-import android.content.Context
-import android.content.Intent
-import android.database.Cursor
-import android.net.Uri
-import android.provider.MediaStore
-import com.simplemobiletools.commons.extensions.*
-import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
-import com.simplemobiletools.commons.helpers.SORT_BY_NAME
-import com.simplemobiletools.commons.helpers.SORT_BY_SIZE
-import com.simplemobiletools.commons.helpers.SORT_DESCENDING
-import com.simplemobiletools.gallery.activities.SettingsActivity
-import com.simplemobiletools.gallery.helpers.Config
-import com.simplemobiletools.gallery.helpers.IMAGES
-import com.simplemobiletools.gallery.helpers.NOMEDIA
-import com.simplemobiletools.gallery.helpers.VIDEOS
-import com.simplemobiletools.gallery.models.Medium
-import java.io.File
-import java.util.*
-
-fun Context.getRealPathFromURI(uri: Uri): String? {
- var cursor: Cursor? = null
- try {
- val projection = arrayOf(MediaStore.Images.Media.DATA)
- cursor = contentResolver.query(uri, projection, null, null, null)
- if (cursor?.moveToFirst() == true) {
- val index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
- return cursor.getString(index)
- }
- } catch (e: Exception) {
- } finally {
- cursor?.close()
- }
- return null
-}
-
-fun Context.getHumanizedFilename(path: String): String {
- val humanized = humanizePath(path)
- return humanized.substring(humanized.lastIndexOf("/") + 1)
-}
-
-fun Context.launchSettings() {
- startActivity(Intent(this, SettingsActivity::class.java))
-}
-
-val Context.config: Config get() = Config.newInstance(this)
-
-fun Context.getFilesFrom(curPath: String, isPickImage: Boolean, isPickVideo: Boolean): ArrayList {
- val projection = arrayOf(MediaStore.Images.Media._ID,
- MediaStore.Images.Media.DISPLAY_NAME,
- MediaStore.Images.Media.DATE_TAKEN,
- MediaStore.Images.Media.DATE_MODIFIED,
- MediaStore.Images.Media.DATA,
- MediaStore.Images.Media.SIZE)
- val uri = MediaStore.Files.getContentUri("external")
- val selection = if (curPath.isEmpty()) null else "(${MediaStore.Images.Media.DATA} LIKE ? AND ${MediaStore.Images.Media.DATA} NOT LIKE ?)"
- val selectionArgs = if (curPath.isEmpty()) null else arrayOf("$curPath/%", "$curPath/%/%")
-
- try {
- val cur = contentResolver.query(uri, projection, selection, selectionArgs, getSortingForFolder(curPath))
- return parseCursor(this, cur, isPickImage, isPickVideo, curPath)
- } catch (e: Exception) {
- return ArrayList()
- }
-}
-
-private fun parseCursor(context: Context, cur: Cursor, isPickImage: Boolean, isPickVideo: Boolean, curPath: String): ArrayList {
- val curMedia = ArrayList()
- val config = context.config
- val showMedia = config.showMedia
- val showHidden = config.shouldShowHidden
- val excludedFolders = config.excludedFolders
- val noMediaFolders = context.getNoMediaFolders()
-
- cur.use { cur ->
- if (cur.moveToFirst()) {
- do {
- try {
- val path = cur.getStringValue(MediaStore.Images.Media.DATA)
- var size = cur.getLongValue(MediaStore.Images.Media.SIZE)
- if (size == 0L) {
- size = File(path).length()
- }
-
- if (size <= 0L) {
- continue
- }
-
- var filename = cur.getStringValue(MediaStore.Images.Media.DISPLAY_NAME) ?: ""
- if (filename.isEmpty())
- filename = path.getFilenameFromPath()
-
- val isImage = filename.isImageFast() || filename.isGif()
- val isVideo = if (isImage) false else filename.isVideoFast()
-
- if (!isImage && !isVideo)
- continue
-
- if (isVideo && (isPickImage || showMedia == IMAGES))
- continue
-
- if (isImage && (isPickVideo || showMedia == VIDEOS))
- continue
-
- if (!showHidden && filename.startsWith('.'))
- continue
-
- var isExcluded = false
- excludedFolders.forEach {
- if (path.startsWith(it)) {
- isExcluded = true
- }
- }
-
- if (!isExcluded && !showHidden) {
- noMediaFolders.forEach {
- if (path.startsWith(it)) {
- isExcluded = true
- }
- }
- }
-
- if (!isExcluded && !showHidden && path.contains("/.")) {
- isExcluded = true
- }
-
- if (!isExcluded) {
- val dateTaken = cur.getLongValue(MediaStore.Images.Media.DATE_TAKEN)
- val dateModified = cur.getIntValue(MediaStore.Images.Media.DATE_MODIFIED) * 1000L
-
- val medium = Medium(filename, path, isVideo, dateModified, dateTaken, size)
- curMedia.add(medium)
- }
- } catch (e: Exception) {
- continue
- }
- } while (cur.moveToNext())
- }
- }
-
- config.includedFolders.filter { it.isEmpty() || it == curPath }.mapNotNull { File(it).listFiles() }.forEach {
- for (file in it) {
- val size = file.length()
- if (size <= 0L) {
- continue
- }
-
- val filename = file.name
- val isImage = filename.isImageFast() || filename.isGif()
- val isVideo = if (isImage) false else filename.isVideoFast()
-
- if (!isImage && !isVideo)
- continue
-
- if (isVideo && (isPickImage || showMedia == IMAGES))
- continue
-
- if (isImage && (isPickVideo || showMedia == VIDEOS))
- continue
-
- val dateTaken = file.lastModified()
- val dateModified = file.lastModified()
-
- val medium = Medium(filename, file.absolutePath, isVideo, dateModified, dateTaken, size)
- val isAlreadyAdded = curMedia.any { it.path == file.absolutePath }
- if (!isAlreadyAdded)
- curMedia.add(medium)
- }
- }
-
- Medium.sorting = config.getFileSorting(curPath)
- curMedia.sort()
-
- return curMedia
-}
-
-fun Context.getSortingForFolder(path: String): String {
- val sorting = config.getFileSorting(path)
- val sortValue = if (sorting and SORT_BY_NAME > 0)
- MediaStore.Images.Media.DISPLAY_NAME
- else if (sorting and SORT_BY_SIZE > 0)
- MediaStore.Images.Media.SIZE
- else if (sorting and SORT_BY_DATE_MODIFIED > 0)
- MediaStore.Images.Media.DATE_MODIFIED
- else
- MediaStore.Images.Media.DATE_TAKEN
-
- return if (sorting and SORT_DESCENDING > 0)
- "$sortValue DESC"
- else
- "$sortValue ASC"
-}
-
-fun Context.getNoMediaFolders(): ArrayList {
- val folders = ArrayList()
- val noMediaCondition = "${MediaStore.Files.FileColumns.MEDIA_TYPE} = ${MediaStore.Files.FileColumns.MEDIA_TYPE_NONE}"
-
- val uri = MediaStore.Files.getContentUri("external")
- val columns = arrayOf(MediaStore.Files.FileColumns.DATA)
- val where = "$noMediaCondition AND ${MediaStore.Files.FileColumns.TITLE} LIKE ?"
- val args = arrayOf("%$NOMEDIA%")
- var cursor: Cursor? = null
-
- try {
- cursor = contentResolver.query(uri, columns, where, args, null)
- if (cursor?.moveToFirst() == true) {
- do {
- val path = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)) ?: continue
- val noMediaFile = File(path)
- if (noMediaFile.exists())
- folders.add(noMediaFile.parent)
- } while (cursor.moveToNext())
- }
- } finally {
- cursor?.close()
- }
-
- return folders
-}
-
-fun Context.getLastMediaModified(): Int {
- val max = "max"
- val uri = MediaStore.Files.getContentUri("external")
- val projection = arrayOf(MediaStore.Images.Media._ID, "MAX(${MediaStore.Images.Media.DATE_MODIFIED}) AS $max")
- var cursor: Cursor? = null
- try {
- cursor = contentResolver.query(uri, projection, null, null, null)
- if (cursor?.moveToFirst() == true) {
- return cursor.getIntValue(max)
- }
- } finally {
- cursor?.close()
- }
- return 0
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/file.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/file.kt
deleted file mode 100644
index 668c3acb5..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/extensions/file.kt
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.simplemobiletools.gallery.extensions
-
-import android.os.Environment
-import com.simplemobiletools.gallery.helpers.NOMEDIA
-import java.io.File
-
-fun File.containsNoMedia() = isDirectory && File(this, NOMEDIA).exists()
-
-fun File.isDownloadsFolder() = absolutePath == Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/PhotoFragment.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/PhotoFragment.kt
deleted file mode 100644
index eaa7bfc91..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/PhotoFragment.kt
+++ /dev/null
@@ -1,268 +0,0 @@
-package com.simplemobiletools.gallery.fragments
-
-import android.content.res.Configuration
-import android.graphics.Bitmap
-import android.graphics.BitmapFactory
-import android.graphics.Color
-import android.graphics.Matrix
-import android.graphics.drawable.ColorDrawable
-import android.net.Uri
-import android.os.Bundle
-import android.view.LayoutInflater
-import android.view.View
-import android.view.ViewGroup
-import com.bumptech.glide.Glide
-import com.bumptech.glide.Priority
-import com.bumptech.glide.load.DecodeFormat
-import com.bumptech.glide.load.engine.DiskCacheStrategy
-import com.bumptech.glide.request.RequestListener
-import com.bumptech.glide.request.target.Target
-import com.davemorrissey.labs.subscaleview.ImageSource
-import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
-import com.simplemobiletools.commons.extensions.beGone
-import com.simplemobiletools.commons.extensions.beVisible
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.activities.ViewPagerActivity
-import com.simplemobiletools.gallery.extensions.config
-import com.simplemobiletools.gallery.extensions.getFileSignature
-import com.simplemobiletools.gallery.extensions.getRealPathFromURI
-import com.simplemobiletools.gallery.helpers.GlideRotateTransformation
-import com.simplemobiletools.gallery.helpers.MEDIUM
-import com.simplemobiletools.gallery.models.Medium
-import it.sephiroth.android.library.exif2.ExifInterface
-import kotlinx.android.synthetic.main.pager_photo_item.view.*
-import uk.co.senab.photoview.PhotoViewAttacher
-import java.io.File
-import java.io.FileOutputStream
-import java.io.IOException
-
-class PhotoFragment : ViewPagerFragment() {
- lateinit var medium: Medium
- lateinit var view: ViewGroup
- private var isFragmentVisible = false
- private var wasInit = false
- private var RATIO_THRESHOLD = 0.1
-
- override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
- view = inflater.inflate(R.layout.pager_photo_item, container, false) as ViewGroup
-
- medium = arguments.getSerializable(MEDIUM) as Medium
-
- if (medium.path.startsWith("content://")) {
- val originalPath = medium.path
- medium.path = context.getRealPathFromURI(Uri.parse(medium.path)) ?: ""
-
- if (medium.path.isEmpty()) {
- var out: FileOutputStream? = null
- try {
- var inputStream = context.contentResolver.openInputStream(Uri.parse(originalPath))
- val exif = ExifInterface()
- exif.readExif(inputStream, ExifInterface.Options.OPTION_ALL)
- val tag = exif.getTag(ExifInterface.TAG_ORIENTATION)
- val orientation = tag?.getValueAsInt(-1) ?: -1
-
- inputStream = context.contentResolver.openInputStream(Uri.parse(originalPath))
- val original = BitmapFactory.decodeStream(inputStream)
- val rotated = rotateViaMatrix(original, orientation)
- exif.setTagValue(ExifInterface.TAG_ORIENTATION, 1)
- exif.removeCompressedThumbnail()
-
- val file = File(context.externalCacheDir, Uri.parse(originalPath).lastPathSegment)
- out = FileOutputStream(file)
- rotated.compress(Bitmap.CompressFormat.JPEG, 100, out)
- medium.path = file.absolutePath
- } catch (e: Exception) {
- activity.toast(R.string.unknown_error_occurred)
- return view
- } finally {
- try {
- out?.close()
- } catch (e: IOException) {
- }
- }
- }
- }
-
- view.subsampling_view.setOnClickListener({ photoClicked() })
- view.photo_view.apply {
- maximumScale = 8f
- mediumScale = 3f
- setOnPhotoTapListener(object : PhotoViewAttacher.OnPhotoTapListener {
- override fun onPhotoTap(view: View?, x: Float, y: Float) {
- photoClicked()
- }
-
- override fun onOutsidePhotoTap() {
- photoClicked()
- }
- })
- }
- loadImage()
-
- activity.window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
- listener?.systemUiVisibilityChanged(visibility)
- }
- wasInit = true
-
- return view
- }
-
- override fun setMenuVisibility(menuVisible: Boolean) {
- super.setMenuVisibility(menuVisible)
- isFragmentVisible = menuVisible
- if (wasInit) {
- if (menuVisible) {
- addZoomableView()
- } else {
- view.subsampling_view.apply {
- recycle()
- beGone()
- background = ColorDrawable(Color.TRANSPARENT)
- }
- }
- }
- }
-
- private fun degreesForRotation(orientation: Int): Int {
- return when (orientation) {
- 8 -> 270
- 3 -> 180
- 6 -> 90
- else -> 0
- }
- }
-
- private fun rotateViaMatrix(original: Bitmap, orientation: Int): Bitmap {
- val degrees = degreesForRotation(orientation).toFloat()
- return if (degrees == 0f) {
- original
- } else {
- val matrix = Matrix()
- matrix.setRotate(degrees)
- Bitmap.createBitmap(original, 0, 0, original.width, original.height, matrix, true)
- }
- }
-
- private fun loadImage() {
- if (medium.isGif()) {
- Glide.with(this)
- .load(medium.path)
- .asGif()
- .crossFade()
- .priority(if (isFragmentVisible) Priority.IMMEDIATE else Priority.LOW)
- .diskCacheStrategy(DiskCacheStrategy.SOURCE)
- .into(view.photo_view)
- } else {
- loadBitmap()
- }
- }
-
- private fun loadBitmap(degrees: Float = 0f) {
- if (degrees == 0f) {
- val targetWidth = if (ViewPagerActivity.screenWidth == 0) Target.SIZE_ORIGINAL else ViewPagerActivity.screenWidth
- val targetHeight = if (ViewPagerActivity.screenHeight == 0) Target.SIZE_ORIGINAL else ViewPagerActivity.screenHeight
-
- Glide.with(this)
- .load(medium.path)
- .asBitmap()
- .signature(activity.getFileSignature(medium.path))
- .format(if (medium.isPng()) DecodeFormat.PREFER_ARGB_8888 else DecodeFormat.PREFER_RGB_565)
- .diskCacheStrategy(DiskCacheStrategy.NONE)
- .override(targetWidth, targetHeight)
- .listener(object : RequestListener {
- override fun onException(e: Exception?, model: String?, target: Target?, isFirstResource: Boolean): Boolean {
- return false
- }
-
- override fun onResourceReady(resource: Bitmap, model: String?, target: Target?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
- if (isFragmentVisible)
- addZoomableView()
- return false
- }
- }).into(view.photo_view)
- } else {
- Glide.with(this)
- .load(medium.path)
- .asBitmap()
- .transform(GlideRotateTransformation(context, degrees))
- .thumbnail(0.2f)
- .diskCacheStrategy(DiskCacheStrategy.NONE)
- .into(view.photo_view)
- }
- }
-
- private fun addZoomableView() {
- if ((medium.isImage()) && isFragmentVisible && view.subsampling_view.visibility == View.GONE) {
- view.subsampling_view.apply {
- maxScale = 10f
- beVisible()
- setImage(ImageSource.uri(medium.path))
- orientation = SubsamplingScaleImageView.ORIENTATION_USE_EXIF
- setOnImageEventListener(object : SubsamplingScaleImageView.OnImageEventListener {
- override fun onImageLoaded() {
- }
-
- override fun onReady() {
- background = ColorDrawable(if (context.config.darkBackground) Color.BLACK else context.config.backgroundColor)
- setDoubleTapZoomScale(getDoubleTapZoomScale())
- }
-
- override fun onTileLoadError(e: Exception?) {
- }
-
- override fun onPreviewReleased() {
- }
-
- override fun onImageLoadError(e: Exception?) {
- background = ColorDrawable(Color.TRANSPARENT)
- beGone()
- }
-
- override fun onPreviewLoadError(e: Exception?) {
- background = ColorDrawable(Color.TRANSPARENT)
- beGone()
- }
- })
- }
- }
- }
-
- private fun getDoubleTapZoomScale(): Float {
- val displayAspectRatio = ViewPagerActivity.screenHeight / (ViewPagerActivity.screenWidth).toFloat()
-
- val bitmapOptions = BitmapFactory.Options()
- bitmapOptions.inJustDecodeBounds = true
- BitmapFactory.decodeFile(medium.path, bitmapOptions)
- val width = bitmapOptions.outWidth
- val height = bitmapOptions.outHeight
- val bitmapAspectRatio = height / (width).toFloat()
-
- return if (Math.abs(displayAspectRatio - bitmapAspectRatio) < RATIO_THRESHOLD) {
- 2f
- } else if (bitmapAspectRatio > 1f) {
- width / (height).toFloat()
- } else {
- bitmapAspectRatio
- }
- }
-
- override fun onDestroyView() {
- super.onDestroyView()
- Glide.clear(view.photo_view)
- }
-
- fun rotateImageViewBy(degrees: Float) {
- view.subsampling_view.beGone()
- loadBitmap(degrees)
- }
-
- override fun onConfigurationChanged(newConfig: Configuration?) {
- super.onConfigurationChanged(newConfig)
- loadImage()
- }
-
- private fun photoClicked() {
- listener?.fragmentClicked()
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/VideoFragment.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/VideoFragment.kt
deleted file mode 100644
index 5359bcc67..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/VideoFragment.kt
+++ /dev/null
@@ -1,364 +0,0 @@
-package com.simplemobiletools.gallery.fragments
-
-import android.content.res.Configuration
-import android.media.AudioManager
-import android.media.MediaPlayer
-import android.net.Uri
-import android.os.Build
-import android.os.Bundle
-import android.os.Handler
-import android.util.DisplayMetrics
-import android.util.Log
-import android.view.*
-import android.view.animation.AnimationUtils
-import android.widget.SeekBar
-import android.widget.TextView
-import com.simplemobiletools.commons.extensions.getFormattedDuration
-import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.commons.extensions.updateTextColors
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.extensions.config
-import com.simplemobiletools.gallery.extensions.getNavBarHeight
-import com.simplemobiletools.gallery.extensions.hasNavBar
-import com.simplemobiletools.gallery.helpers.MEDIUM
-import com.simplemobiletools.gallery.models.Medium
-import kotlinx.android.synthetic.main.pager_video_item.view.*
-import java.io.IOException
-
-class VideoFragment : ViewPagerFragment(), SurfaceHolder.Callback, SeekBar.OnSeekBarChangeListener {
-
- private var mMediaPlayer: MediaPlayer? = null
- private var mSurfaceView: SurfaceView? = null
- private var mSurfaceHolder: SurfaceHolder? = null
- private var mCurrTimeView: TextView? = null
- private var mTimerHandler: Handler? = null
- private var mSeekBar: SeekBar? = null
- private var mTimeHolder: View? = null
-
- private var mIsPlaying = false
- private var mIsDragged = false
- private var mIsFullscreen = false
- private var mIsFragmentVisible = false
- private var mCurrTime = 0
- private var mDuration = 0
-
- lateinit var mView: View
- lateinit var medium: Medium
-
- companion object {
- private val TAG = VideoFragment::class.java.simpleName
- private val PROGRESS = "progress"
- }
-
- override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
- mView = inflater.inflate(R.layout.pager_video_item, container, false)
- setupPlayer()
-
- medium = arguments.getSerializable(MEDIUM) as Medium
- if (savedInstanceState != null) {
- mCurrTime = savedInstanceState.getInt(PROGRESS)
- }
-
- mIsFullscreen = activity.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == View.SYSTEM_UI_FLAG_FULLSCREEN
-
- activity.window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
- val fullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
- mIsFullscreen = fullscreen
- checkFullscreen()
- listener?.systemUiVisibilityChanged(visibility)
- }
-
- return mView
- }
-
- override fun onResume() {
- super.onResume()
- activity.updateTextColors(mView.video_holder)
- }
-
- private fun setupPlayer() {
- if (activity == null)
- return
-
- mView.video_play_outline.setOnClickListener { togglePlayPause() }
-
- mSurfaceView = mView.video_surface
- mSurfaceHolder = mSurfaceView!!.holder
- mSurfaceHolder!!.addCallback(this)
- mSurfaceView!!.setOnClickListener({ toggleFullscreen() })
- mView.video_holder.setOnClickListener { toggleFullscreen() }
-
- initTimeHolder()
- }
-
- override fun setMenuVisibility(menuVisible: Boolean) {
- super.setMenuVisibility(menuVisible)
- mIsFragmentVisible = menuVisible
- if (menuVisible) {
- if (context?.config?.autoplayVideos == true) {
- playVideo()
- }
- } else if (mIsPlaying) {
- pauseVideo()
- }
- }
-
- override fun onConfigurationChanged(newConfig: Configuration?) {
- super.onConfigurationChanged(newConfig)
- setVideoSize()
- initTimeHolder()
- }
-
- private fun toggleFullscreen() {
- mIsFullscreen = !mIsFullscreen
- checkFullscreen()
- listener?.fragmentClicked()
- }
-
- private fun initTimeHolder() {
- mTimeHolder = mView.video_time_holder
- val res = resources
- val height = res.getNavBarHeight()
- val left = mTimeHolder!!.paddingLeft
- val top = mTimeHolder!!.paddingTop
- var right = res.getDimension(R.dimen.timer_padding).toInt()
- var bottom = 0
-
- if (activity.hasNavBar()) {
- if (res.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
- bottom += height
- } else {
- right += height
- }
- mTimeHolder!!.setPadding(left, top, right, bottom)
- }
-
- mCurrTimeView = mView.video_curr_time
- mSeekBar = mView.video_seekbar
- mSeekBar!!.setOnSeekBarChangeListener(this)
-
- if (mIsFullscreen)
- mTimeHolder!!.visibility = View.INVISIBLE
- }
-
- private fun setupTimeHolder() {
- mSeekBar!!.max = mDuration
- mView.video_duration.text = mDuration.getFormattedDuration()
- mTimerHandler = Handler()
- setupTimer()
- }
-
- private fun setupTimer() {
- activity.runOnUiThread(object : Runnable {
- override fun run() {
- if (mMediaPlayer != null && !mIsDragged && mIsPlaying) {
- mCurrTime = mMediaPlayer!!.currentPosition / 1000
- mSeekBar!!.progress = mCurrTime
- mCurrTimeView!!.text = mCurrTime.getFormattedDuration()
- }
-
- mTimerHandler!!.postDelayed(this, 1000)
- }
- })
- }
-
- override fun onSaveInstanceState(outState: Bundle) {
- super.onSaveInstanceState(outState)
- outState.putInt(PROGRESS, mCurrTime)
- }
-
- private fun checkFullscreen() {
- if (activity == null)
- return
-
- var anim = android.R.anim.fade_in
- if (mIsFullscreen) {
- anim = android.R.anim.fade_out
- mSeekBar!!.setOnSeekBarChangeListener(null)
- } else {
- mSeekBar!!.setOnSeekBarChangeListener(this)
- }
-
- AnimationUtils.loadAnimation(activity, anim).apply {
- duration = 150
- fillAfter = true
- mTimeHolder!!.startAnimation(this)
- }
- }
-
- private fun togglePlayPause() {
- if (activity == null || !isAdded)
- return
-
- mIsPlaying = !mIsPlaying
- if (mIsPlaying) {
- playVideo()
- } else {
- pauseVideo()
- }
- }
-
- private fun playVideo() {
- mIsPlaying = true
- mMediaPlayer?.start()
- mView.video_play_outline.setImageDrawable(null)
- activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
- }
-
- private fun pauseVideo() {
- mIsPlaying = false
- mMediaPlayer?.pause()
- mView.video_play_outline.setImageDrawable(resources.getDrawable(R.drawable.img_play_outline_big))
- activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
- }
-
- private fun initMediaPlayer() {
- if (mMediaPlayer != null)
- return
-
- try {
- mMediaPlayer = MediaPlayer().apply {
- setDataSource(context, Uri.parse(medium.path))
- setDisplay(mSurfaceHolder)
- setOnCompletionListener { videoCompleted() }
- setOnVideoSizeChangedListener({ mediaPlayer, width, height -> setVideoSize() })
- setOnPreparedListener { videoPrepared(it) }
- setAudioStreamType(AudioManager.STREAM_MUSIC)
- prepareAsync()
- }
- } catch (e: IOException) {
- Log.e(TAG, "init media player failed $e")
- }
- }
-
- private fun setProgress(seconds: Int) {
- mMediaPlayer!!.seekTo(seconds * 1000)
- mSeekBar!!.progress = seconds
- mCurrTimeView!!.text = seconds.getFormattedDuration()
- }
-
- private fun addPreviewImage() {
- mMediaPlayer!!.start()
- mMediaPlayer!!.pause()
- }
-
- override fun onPause() {
- super.onPause()
- pauseVideo()
- mIsFragmentVisible = false
- }
-
- override fun onDestroy() {
- super.onDestroy()
- if (activity?.isChangingConfigurations == false) {
- cleanup()
- }
- }
-
- private fun cleanup() {
- pauseVideo()
- mCurrTimeView?.text = 0.getFormattedDuration()
- mMediaPlayer?.release()
- mMediaPlayer = null
- mSeekBar?.progress = 0
- mTimerHandler?.removeCallbacksAndMessages(null)
- }
-
- private fun videoPrepared(mediaPlayer: MediaPlayer) {
- mDuration = mediaPlayer.duration / 1000
- addPreviewImage()
- setupTimeHolder()
- setProgress(mCurrTime)
-
- if (mIsFragmentVisible && context.config.autoplayVideos)
- playVideo()
- }
-
- private fun videoCompleted() {
- if (context.config.loopVideos) {
- playVideo()
- } else {
- mSeekBar!!.progress = mSeekBar!!.max
- mCurrTimeView!!.text = mDuration.getFormattedDuration()
- pauseVideo()
- }
- }
-
- override fun surfaceCreated(holder: SurfaceHolder) {
-
- }
-
- override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
- if (width != 0 && height != 0 && mSurfaceView != null)
- setVideoSize()
- }
-
- override fun surfaceDestroyed(holder: SurfaceHolder) {
- mMediaPlayer?.release()
- mMediaPlayer = null
- }
-
- private fun setVideoSize() {
- if (mSurfaceHolder == null)
- mSurfaceHolder = mSurfaceView!!.holder
-
- if (activity == null || mSurfaceHolder == null || !mSurfaceHolder!!.surface.isValid)
- return
-
- initMediaPlayer()
- if (mMediaPlayer == null) {
- activity.toast(R.string.unknown_error_occurred)
- return
- }
-
- val videoProportion = mMediaPlayer!!.videoWidth.toFloat() / mMediaPlayer!!.videoHeight.toFloat()
- val display = activity.windowManager.defaultDisplay
- val screenWidth: Int
- val screenHeight: Int
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
- val realMetrics = DisplayMetrics()
- display.getRealMetrics(realMetrics)
- screenWidth = realMetrics.widthPixels
- screenHeight = realMetrics.heightPixels
- } else {
- screenWidth = display.width
- screenHeight = display.height
- }
-
- val screenProportion = screenWidth.toFloat() / screenHeight.toFloat()
-
- mSurfaceView!!.layoutParams.apply {
- if (videoProportion > screenProportion) {
- width = screenWidth
- height = (screenWidth.toFloat() / videoProportion).toInt()
- } else {
- width = (videoProportion * screenHeight.toFloat()).toInt()
- height = screenHeight
- }
- mSurfaceView!!.layoutParams = this
- }
- }
-
- override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
- if (mMediaPlayer != null && fromUser) {
- setProgress(progress)
- }
- }
-
- override fun onStartTrackingTouch(seekBar: SeekBar) {
- initMediaPlayer()
- mMediaPlayer!!.pause()
- mIsDragged = true
- }
-
- override fun onStopTrackingTouch(seekBar: SeekBar) {
- if (!mIsPlaying) {
- togglePlayPause()
- } else {
- mMediaPlayer!!.start()
- }
-
- mIsDragged = false
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/ViewPagerFragment.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/ViewPagerFragment.kt
deleted file mode 100644
index bd6bc4a50..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/fragments/ViewPagerFragment.kt
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.simplemobiletools.gallery.fragments
-
-import android.support.v4.app.Fragment
-
-abstract class ViewPagerFragment : Fragment() {
- var listener: FragmentListener? = null
-
- interface FragmentListener {
- fun fragmentClicked()
-
- fun systemUiVisibilityChanged(visibility: Int)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/Config.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/Config.kt
deleted file mode 100644
index 424721c88..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/Config.kt
+++ /dev/null
@@ -1,182 +0,0 @@
-package com.simplemobiletools.gallery.helpers
-
-import android.content.Context
-import com.google.gson.Gson
-import com.google.gson.reflect.TypeToken
-import com.simplemobiletools.commons.helpers.BaseConfig
-import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
-import com.simplemobiletools.commons.helpers.SORT_DESCENDING
-import com.simplemobiletools.gallery.R
-import com.simplemobiletools.gallery.models.AlbumCover
-import java.util.*
-
-class Config(context: Context) : BaseConfig(context) {
- companion object {
- fun newInstance(context: Context) = Config(context)
- }
-
- var fileSorting: Int
- get() = prefs.getInt(SORT_ORDER, SORT_BY_DATE_MODIFIED or SORT_DESCENDING)
- set(order) = prefs.edit().putInt(SORT_ORDER, order).apply()
-
- var directorySorting: Int
- get() = prefs.getInt(DIRECTORY_SORT_ORDER, SORT_BY_DATE_MODIFIED or SORT_DESCENDING)
- set(order) = prefs.edit().putInt(DIRECTORY_SORT_ORDER, order).apply()
-
- fun saveFileSorting(path: String, value: Int) {
- if (path.isEmpty()) {
- fileSorting = value
- } else {
- prefs.edit().putInt(SORT_FOLDER_PREFIX + path, value).apply()
- }
- }
-
- fun getFileSorting(path: String) = prefs.getInt(SORT_FOLDER_PREFIX + path, fileSorting)
-
- fun removeFileSorting(path: String) {
- prefs.edit().remove(SORT_FOLDER_PREFIX + path).apply()
- }
-
- fun hasCustomSorting(path: String) = prefs.contains(SORT_FOLDER_PREFIX + path)
-
- var wasHideFolderTooltipShown: Boolean
- get() = prefs.getBoolean(HIDE_FOLDER_TOOLTIP_SHOWN, false)
- set(wasShown) = prefs.edit().putBoolean(HIDE_FOLDER_TOOLTIP_SHOWN, wasShown).apply()
-
- var shouldShowHidden = showHiddenMedia || temporarilyShowHidden
-
- var showHiddenMedia: Boolean
- get() = prefs.getBoolean(SHOW_HIDDEN_MEDIA, false)
- set(showHiddenFolders) = prefs.edit().putBoolean(SHOW_HIDDEN_MEDIA, showHiddenFolders).apply()
-
- var temporarilyShowHidden: Boolean
- get() = prefs.getBoolean(TEMPORARILY_SHOW_HIDDEN, false)
- set(temporarilyShowHidden) = prefs.edit().putBoolean(TEMPORARILY_SHOW_HIDDEN, temporarilyShowHidden).apply()
-
- var pinnedFolders: Set
- get() = prefs.getStringSet(PINNED_FOLDERS, HashSet())
- set(pinnedFolders) = prefs.edit().putStringSet(PINNED_FOLDERS, pinnedFolders).apply()
-
- var showAll: Boolean
- get() = prefs.getBoolean(SHOW_ALL, false)
- set(showAll) = prefs.edit().putBoolean(SHOW_ALL, showAll).apply()
-
- fun addPinnedFolders(paths: Set) {
- val currPinnedFolders = HashSet(pinnedFolders)
- currPinnedFolders.addAll(paths)
- pinnedFolders = currPinnedFolders
- }
-
- fun removePinnedFolders(paths: Set) {
- val currPinnedFolders = HashSet(pinnedFolders)
- currPinnedFolders.removeAll(paths)
- pinnedFolders = currPinnedFolders
- }
-
- fun addExcludedFolder(path: String) {
- addExcludedFolders(HashSet(Arrays.asList(path)))
- }
-
- fun addExcludedFolders(paths: Set) {
- val currExcludedFolders = HashSet(excludedFolders)
- currExcludedFolders.addAll(paths)
- excludedFolders = currExcludedFolders
- }
-
- fun removeExcludedFolder(path: String) {
- val currExcludedFolders = HashSet(excludedFolders)
- currExcludedFolders.remove(path)
- excludedFolders = currExcludedFolders
- }
-
- var excludedFolders: MutableSet
- get() = prefs.getStringSet(EXCLUDED_FOLDERS, getDataFolder())
- set(excludedFolders) = prefs.edit().remove(EXCLUDED_FOLDERS).putStringSet(EXCLUDED_FOLDERS, excludedFolders).apply()
-
- private fun getDataFolder(): Set {
- val folders = HashSet()
- val dataFolder = context.externalCacheDir?.parentFile?.parent?.trimEnd('/') ?: ""
- if (dataFolder.endsWith("data"))
- folders.add(dataFolder)
- return folders
- }
-
- fun addIncludedFolder(path: String) {
- val currIncludedFolders = HashSet(includedFolders)
- currIncludedFolders.add(path)
- includedFolders = currIncludedFolders
- }
-
- fun removeIncludedFolder(path: String) {
- val currIncludedFolders = HashSet(includedFolders)
- currIncludedFolders.remove(path)
- includedFolders = currIncludedFolders
- }
-
- var includedFolders: MutableSet
- get() = prefs.getStringSet(INCLUDED_FOLDERS, HashSet())
- set(includedFolders) = prefs.edit().remove(INCLUDED_FOLDERS).putStringSet(INCLUDED_FOLDERS, includedFolders).apply()
-
- fun saveFolderMedia(path: String, json: String) {
- prefs.edit().putString(SAVE_FOLDER_PREFIX + path, json).apply()
- }
-
- fun loadFolderMedia(path: String) = prefs.getString(SAVE_FOLDER_PREFIX + path, "")
-
- var autoplayVideos: Boolean
- get() = prefs.getBoolean(AUTOPLAY_VIDEOS, false)
- set(autoplay) = prefs.edit().putBoolean(AUTOPLAY_VIDEOS, autoplay).apply()
-
- var animateGifs: Boolean
- get() = prefs.getBoolean(ANIMATE_GIFS, false)
- set(animateGifs) = prefs.edit().putBoolean(ANIMATE_GIFS, animateGifs).apply()
-
- var maxBrightness: Boolean
- get() = prefs.getBoolean(MAX_BRIGHTNESS, false)
- set(maxBrightness) = prefs.edit().putBoolean(MAX_BRIGHTNESS, maxBrightness).apply()
-
- var cropThumbnails: Boolean
- get() = prefs.getBoolean(CROP_THUMBNAILS, true)
- set(cropThumbnails) = prefs.edit().putBoolean(CROP_THUMBNAILS, cropThumbnails).apply()
-
- var screenRotation: Int
- get() = prefs.getInt(SCREEN_ROTATION, ROTATE_BY_SYSTEM_SETTING)
- set(screenRotation) = prefs.edit().putInt(SCREEN_ROTATION, screenRotation).apply()
-
- var loopVideos: Boolean
- get() = prefs.getBoolean(LOOP_VIDEOS, false)
- set(loop) = prefs.edit().putBoolean(LOOP_VIDEOS, loop).apply()
-
- var displayFileNames: Boolean
- get() = prefs.getBoolean(DISPLAY_FILE_NAMES, false)
- set(display) = prefs.edit().putBoolean(DISPLAY_FILE_NAMES, display).apply()
-
- var darkBackground: Boolean
- get() = prefs.getBoolean(DARK_BACKGROUND, false)
- set(darkBackground) = prefs.edit().putBoolean(DARK_BACKGROUND, darkBackground).apply()
-
- var showMedia: Int
- get() = prefs.getInt(SHOW_MEDIA, IMAGES_AND_VIDEOS)
- set(showMedia) = prefs.edit().putInt(SHOW_MEDIA, showMedia).apply()
-
- var dirColumnCnt: Int
- get() = prefs.getInt(DIR_COLUMN_CNT, context.resources.getInteger(R.integer.directory_columns))
- set(dirColumnCnt) = prefs.edit().putInt(DIR_COLUMN_CNT, dirColumnCnt).apply()
-
- var mediaColumnCnt: Int
- get() = prefs.getInt(MEDIA_COLUMN_CNT, context.resources.getInteger(R.integer.media_columns))
- set(mediaColumnCnt) = prefs.edit().putInt(MEDIA_COLUMN_CNT, mediaColumnCnt).apply()
-
- var directories: String
- get() = prefs.getString(DIRECTORIES, "")
- set(directories) = prefs.edit().putString(DIRECTORIES, directories).apply()
-
- var albumCovers: String
- get() = prefs.getString(ALBUM_COVERS, "")
- set(albumCovers) = prefs.edit().putString(ALBUM_COVERS, albumCovers).apply()
-
- fun parseAlbumCovers(): ArrayList {
- val listType = object : TypeToken>() {}.type
- return Gson().fromJson>(albumCovers, listType) ?: ArrayList(1)
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/Constants.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/Constants.kt
deleted file mode 100644
index 21dc7c6de..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/Constants.kt
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.simplemobiletools.gallery.helpers
-
-// shared preferences
-val SORT_ORDER = "sort_order"
-val DIRECTORY_SORT_ORDER = "directory_sort_order"
-val SORT_FOLDER_PREFIX = "sort_folder_"
-val SHOW_HIDDEN_MEDIA = "show_hidden_media"
-val TEMPORARILY_SHOW_HIDDEN = "temporarily_show_hidden"
-val AUTOPLAY_VIDEOS = "autoplay_videos"
-val LOOP_VIDEOS = "loop_videos"
-val ANIMATE_GIFS = "animate_gifs"
-val MAX_BRIGHTNESS = "max_brightness"
-val CROP_THUMBNAILS = "crop_thumbnails"
-val SCREEN_ROTATION = "screen_rotation"
-val DISPLAY_FILE_NAMES = "display_file_names"
-val DARK_BACKGROUND = "dark_background"
-val PINNED_FOLDERS = "pinned_folders"
-val DIR_COLUMN_CNT = "dir_column_cnt"
-val MEDIA_COLUMN_CNT = "media_column_cnt"
-val SHOW_ALL = "show_all" // display images and videos from all folders together
-val SHOW_MEDIA = "show_media"
-val SAVE_FOLDER_PREFIX = "folder2_"
-val HIDE_FOLDER_TOOLTIP_SHOWN = "hide_folder_tooltip_shown"
-val EXCLUDED_FOLDERS = "excluded_folders"
-val INCLUDED_FOLDERS = "included_folders"
-val ALBUM_COVERS = "album_covers"
-
-val NOMEDIA = ".nomedia"
-
-val DIRECTORY = "directory"
-val MEDIUM = "medium"
-val GET_IMAGE_INTENT = "get_image_intent"
-val GET_VIDEO_INTENT = "get_video_intent"
-val GET_ANY_INTENT = "get_any_intent"
-val SET_WALLPAPER_INTENT = "set_wallpaper_intent"
-val DIRECTORIES = "directories2"
-val IS_VIEW_INTENT = "is_view_intent"
-
-val REQUEST_EDIT_IMAGE = 1
-val REQUEST_SET_WALLPAPER = 2
-
-// show media
-val IMAGES_AND_VIDEOS = 0
-val IMAGES = 1
-val VIDEOS = 2
-
-// rotations
-val ROTATE_BY_SYSTEM_SETTING = 0
-val ROTATE_BY_DEVICE_ROTATION = 1
-val ROTATE_BY_ASPECT_RATIO = 2
-
-val ORIENT_PORTRAIT = 0
-val ORIENT_LANDSCAPE_LEFT = 1
-val ORIENT_LANDSCAPE_RIGHT = 2
-val ORIENT_UPSIDE_DOWN = 3
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/GlideRotateTransformation.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/GlideRotateTransformation.kt
deleted file mode 100644
index 4e347dd9e..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/helpers/GlideRotateTransformation.kt
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.simplemobiletools.gallery.helpers
-
-import android.content.Context
-import android.graphics.Bitmap
-import android.graphics.Matrix
-import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
-import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
-
-class GlideRotateTransformation(context: Context, val rotateRotationAngle: Float) : BitmapTransformation(context) {
-
- override fun transform(pool: BitmapPool, bitmap: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
- if (rotateRotationAngle % 360 == 0f)
- return bitmap
-
- val matrix = Matrix()
- matrix.postRotate(rotateRotationAngle)
- return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
- }
-
- override fun getId() = "GlideRotateTransformation $rotateRotationAngle"
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/models/Directory.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/models/Directory.kt
deleted file mode 100644
index 77cd94602..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/models/Directory.kt
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.simplemobiletools.gallery.models
-
-import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
-import com.simplemobiletools.commons.helpers.SORT_BY_NAME
-import com.simplemobiletools.commons.helpers.SORT_BY_SIZE
-import com.simplemobiletools.commons.helpers.SORT_DESCENDING
-import java.io.Serializable
-
-data class Directory(val path: String, val tmb: String, val name: String, var mediaCnt: Int, val modified: Long, val taken: Long,
- var size: Long) : Serializable, Comparable {
- companion object {
- private val serialVersionUID = -6553345863555455L
- var sorting: Int = 0
- }
-
- fun addSize(bytes: Long) {
- size += bytes
- }
-
- override fun compareTo(other: Directory): Int {
- var result: Int
- if (sorting and SORT_BY_NAME != 0) {
- result = name.toLowerCase().compareTo(other.name.toLowerCase())
- } else if (sorting and SORT_BY_SIZE != 0) {
- result = if (size == other.size)
- 0
- else if (size > other.size)
- 1
- else
- -1
- } else if (sorting and SORT_BY_DATE_MODIFIED != 0) {
- result = if (modified == other.modified)
- 0
- else if (modified > other.modified)
- 1
- else
- -1
- } else {
- result = if (taken == other.taken)
- 0
- else if (taken > other.taken)
- 1
- else
- -1
- }
-
- if (sorting and SORT_DESCENDING != 0) {
- result *= -1
- }
- return result
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/models/Medium.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/models/Medium.kt
deleted file mode 100644
index c9afe29f0..000000000
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/models/Medium.kt
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.simplemobiletools.gallery.models
-
-import com.simplemobiletools.commons.extensions.getMimeType
-import com.simplemobiletools.commons.extensions.isGif
-import com.simplemobiletools.commons.extensions.isPng
-import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
-import com.simplemobiletools.commons.helpers.SORT_BY_NAME
-import com.simplemobiletools.commons.helpers.SORT_BY_SIZE
-import com.simplemobiletools.commons.helpers.SORT_DESCENDING
-import java.io.File
-import java.io.Serializable
-
-data class Medium(var name: String, var path: String, val video: Boolean, val modified: Long, val taken: Long, val size: Long) : Serializable, Comparable {
- companion object {
- private val serialVersionUID = -6553149366975455L
- var sorting: Int = 0
- }
-
- fun isPng() = path.isPng()
-
- fun isGif() = path.isGif()
-
- fun isImage() = !isGif() && !video
-
- fun getMimeType() = File(path).getMimeType()
-
- override fun compareTo(other: Medium): Int {
- var res: Int
- if (sorting and SORT_BY_NAME != 0) {
- res = name.toLowerCase().compareTo(other.name.toLowerCase())
- } else if (sorting and SORT_BY_SIZE != 0) {
- res = if (size == other.size)
- 0
- else if (size > other.size)
- 1
- else
- -1
- } else if (sorting and SORT_BY_DATE_MODIFIED != 0) {
- res = if (modified == other.modified)
- 0
- else if (modified > other.modified)
- 1
- else
- -1
- } else {
- res = if (taken == other.taken)
- 0
- else if (taken > other.taken)
- 1
- else
- -1
- }
-
- if (sorting and SORT_DESCENDING != 0) {
- res *= -1
- }
- return res
- }
-}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/App.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/App.kt
new file mode 100644
index 000000000..07e9a4097
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/App.kt
@@ -0,0 +1,13 @@
+package com.simplemobiletools.gallery.pro
+
+import android.app.Application
+import com.github.ajalt.reprint.core.Reprint
+import com.simplemobiletools.commons.extensions.checkUseEnglish
+
+class App : Application() {
+ override fun onCreate() {
+ super.onCreate()
+ checkUseEnglish()
+ Reprint.initialize(this)
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/EditActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/EditActivity.kt
new file mode 100644
index 000000000..26cea909e
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/EditActivity.kt
@@ -0,0 +1,897 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.annotation.TargetApi
+import android.app.Activity
+import android.content.Intent
+import android.graphics.Bitmap
+import android.graphics.Bitmap.CompressFormat
+import android.graphics.Color
+import android.graphics.Point
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.provider.MediaStore
+import android.view.Menu
+import android.view.MenuItem
+import android.widget.RelativeLayout
+import androidx.exifinterface.media.ExifInterface
+import androidx.recyclerview.widget.LinearLayoutManager
+import com.bumptech.glide.Glide
+import com.bumptech.glide.load.DataSource
+import com.bumptech.glide.load.DecodeFormat
+import com.bumptech.glide.load.engine.DiskCacheStrategy
+import com.bumptech.glide.load.engine.GlideException
+import com.bumptech.glide.request.RequestListener
+import com.bumptech.glide.request.RequestOptions
+import com.bumptech.glide.request.target.Target
+import com.simplemobiletools.commons.dialogs.ColorPickerDialog
+import com.simplemobiletools.commons.dialogs.ConfirmationDialog
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.REAL_FILE_PATH
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.commons.helpers.isNougatPlus
+import com.simplemobiletools.commons.models.FileDirItem
+import com.simplemobiletools.gallery.pro.BuildConfig
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.FiltersAdapter
+import com.simplemobiletools.gallery.pro.dialogs.OtherAspectRatioDialog
+import com.simplemobiletools.gallery.pro.dialogs.ResizeDialog
+import com.simplemobiletools.gallery.pro.dialogs.SaveAsDialog
+import com.simplemobiletools.gallery.pro.extensions.config
+import com.simplemobiletools.gallery.pro.extensions.copyNonDimensionAttributesTo
+import com.simplemobiletools.gallery.pro.extensions.fixDateTaken
+import com.simplemobiletools.gallery.pro.extensions.openEditor
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.models.FilterItem
+import com.theartofdev.edmodo.cropper.CropImageView
+import com.zomato.photofilters.FilterPack
+import com.zomato.photofilters.imageprocessors.Filter
+import kotlinx.android.synthetic.main.activity_edit.*
+import kotlinx.android.synthetic.main.bottom_actions_aspect_ratio.*
+import kotlinx.android.synthetic.main.bottom_editor_actions_filter.*
+import kotlinx.android.synthetic.main.bottom_editor_crop_rotate_actions.*
+import kotlinx.android.synthetic.main.bottom_editor_draw_actions.*
+import kotlinx.android.synthetic.main.bottom_editor_primary_actions.*
+import java.io.*
+
+class EditActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener {
+ companion object {
+ init {
+ System.loadLibrary("NativeImageProcessor")
+ }
+ }
+
+ private val TEMP_FOLDER_NAME = "images"
+ private val ASPECT_X = "aspectX"
+ private val ASPECT_Y = "aspectY"
+ private val CROP = "crop"
+
+ // constants for bottom primary action groups
+ private val PRIMARY_ACTION_NONE = 0
+ private val PRIMARY_ACTION_FILTER = 1
+ private val PRIMARY_ACTION_CROP_ROTATE = 2
+ private val PRIMARY_ACTION_DRAW = 3
+
+ private val CROP_ROTATE_NONE = 0
+ private val CROP_ROTATE_ASPECT_RATIO = 1
+
+ private lateinit var saveUri: Uri
+ private var uri: Uri? = null
+ private var resizeWidth = 0
+ private var resizeHeight = 0
+ private var drawColor = 0
+ private var lastOtherAspectRatio: Pair? = null
+ private var currPrimaryAction = PRIMARY_ACTION_NONE
+ private var currCropRotateAction = CROP_ROTATE_ASPECT_RATIO
+ private var currAspectRatio = ASPECT_RATIO_FREE
+ private var isCropIntent = false
+ private var isEditingWithThirdParty = false
+ private var isSharingBitmap = false
+ private var wasDrawCanvasPositioned = false
+ private var oldExif: ExifInterface? = null
+ private var filterInitialBitmap: Bitmap? = null
+ private var originalUri: Uri? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_edit)
+
+ if (checkAppSideloading()) {
+ return
+ }
+
+ initEditActivity()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ isEditingWithThirdParty = false
+ bottom_draw_width.setColors(config.textColor, getAdjustedPrimaryColor(), config.backgroundColor)
+ }
+
+ override fun onStop() {
+ super.onStop()
+ if (isEditingWithThirdParty) {
+ finish()
+ }
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_editor, menu)
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.save_as -> saveImage()
+ R.id.edit -> editWith()
+ R.id.share -> shareImage()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ private fun initEditActivity() {
+ if (intent.data == null) {
+ toast(R.string.invalid_image_path)
+ finish()
+ return
+ }
+
+ uri = intent.data!!
+ originalUri = uri
+ if (uri!!.scheme != "file" && uri!!.scheme != "content") {
+ toast(R.string.unknown_file_location)
+ finish()
+ return
+ }
+
+ if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
+ val realPath = intent.extras!!.getString(REAL_FILE_PATH)
+ uri = when {
+ isPathOnOTG(realPath!!) -> uri
+ realPath.startsWith("file:/") -> Uri.parse(realPath)
+ else -> Uri.fromFile(File(realPath))
+ }
+ } else {
+ (getRealPathFromURI(uri!!))?.apply {
+ uri = Uri.fromFile(File(this))
+ }
+ }
+
+ saveUri = when {
+ intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true -> intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri
+ else -> uri!!
+ }
+
+ isCropIntent = intent.extras?.get(CROP) == "true"
+ if (isCropIntent) {
+ bottom_editor_primary_actions.beGone()
+ (bottom_editor_crop_rotate_actions.layoutParams as RelativeLayout.LayoutParams).addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1)
+ }
+
+ loadDefaultImageView()
+ setupBottomActions()
+
+ if (config.lastEditorCropAspectRatio == ASPECT_RATIO_OTHER) {
+ if (config.lastEditorCropOtherAspectRatioX == 0f) {
+ config.lastEditorCropOtherAspectRatioX = 1f
+ }
+
+ if (config.lastEditorCropOtherAspectRatioY == 0f) {
+ config.lastEditorCropOtherAspectRatioY = 1f
+ }
+
+ lastOtherAspectRatio = Pair(config.lastEditorCropOtherAspectRatioX, config.lastEditorCropOtherAspectRatioY)
+ }
+ updateAspectRatio(config.lastEditorCropAspectRatio)
+ crop_image_view.guidelines = CropImageView.Guidelines.ON
+ bottom_aspect_ratios.beVisible()
+ }
+
+ private fun loadDefaultImageView() {
+ default_image_view.beVisible()
+ crop_image_view.beGone()
+ editor_draw_canvas.beGone()
+
+ val options = RequestOptions()
+ .skipMemoryCache(true)
+ .diskCacheStrategy(DiskCacheStrategy.NONE)
+
+ Glide.with(this)
+ .asBitmap()
+ .load(uri)
+ .apply(options)
+ .listener(object : RequestListener {
+ override fun onLoadFailed(e: GlideException?, model: Any?, target: Target?, isFirstResource: Boolean): Boolean {
+ if (uri != originalUri) {
+ uri = originalUri
+ Handler().post {
+ loadDefaultImageView()
+ }
+ }
+ return false
+ }
+
+ override fun onResourceReady(bitmap: Bitmap?, model: Any?, target: Target?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
+ val currentFilter = getFiltersAdapter()?.getCurrentFilter()
+ if (filterInitialBitmap == null) {
+ loadCropImageView()
+ bottomCropRotateClicked()
+ }
+
+ if (filterInitialBitmap != null && currentFilter != null && currentFilter.filter.name != getString(R.string.none)) {
+ default_image_view.onGlobalLayout {
+ applyFilter(currentFilter)
+ }
+ } else {
+ filterInitialBitmap = bitmap
+ }
+
+ if (isCropIntent) {
+ bottom_primary_filter.beGone()
+ bottom_primary_draw.beGone()
+ }
+
+ return false
+ }
+ }).into(default_image_view)
+ }
+
+ private fun loadCropImageView() {
+ default_image_view.beGone()
+ editor_draw_canvas.beGone()
+ crop_image_view.apply {
+ beVisible()
+ setOnCropImageCompleteListener(this@EditActivity)
+ setImageUriAsync(uri)
+ guidelines = CropImageView.Guidelines.ON
+
+ if (isCropIntent && shouldCropSquare()) {
+ currAspectRatio = ASPECT_RATIO_ONE_ONE
+ setFixedAspectRatio(true)
+ bottom_aspect_ratio.beGone()
+ }
+ }
+ }
+
+ private fun loadDrawCanvas() {
+ default_image_view.beGone()
+ crop_image_view.beGone()
+ editor_draw_canvas.beVisible()
+
+ if (!wasDrawCanvasPositioned) {
+ wasDrawCanvasPositioned = true
+ editor_draw_canvas.onGlobalLayout {
+ ensureBackgroundThread {
+ fillCanvasBackground()
+ }
+ }
+ }
+ }
+
+ private fun fillCanvasBackground() {
+ val size = Point()
+ windowManager.defaultDisplay.getSize(size)
+ val options = RequestOptions()
+ .format(DecodeFormat.PREFER_ARGB_8888)
+ .skipMemoryCache(true)
+ .diskCacheStrategy(DiskCacheStrategy.NONE)
+ .fitCenter()
+
+ try {
+ val builder = Glide.with(applicationContext)
+ .asBitmap()
+ .load(uri)
+ .apply(options)
+ .into(editor_draw_canvas.width, editor_draw_canvas.height)
+
+ val bitmap = builder.get()
+ runOnUiThread {
+ editor_draw_canvas.apply {
+ updateBackgroundBitmap(bitmap)
+ layoutParams.width = bitmap.width
+ layoutParams.height = bitmap.height
+ y = (height - bitmap.height) / 2f
+ requestLayout()
+ }
+ }
+ } catch (e: Exception) {
+ showErrorToast(e)
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.N)
+ private fun saveImage() {
+ setOldExif()
+
+ if (crop_image_view.isVisible()) {
+ crop_image_view.getCroppedImageAsync()
+ } else if (editor_draw_canvas.isVisible()) {
+ val bitmap = editor_draw_canvas.getBitmap()
+ if (saveUri.scheme == "file") {
+ SaveAsDialog(this, saveUri.path!!, true) {
+ saveBitmapToFile(bitmap, it, true)
+ }
+ } else if (saveUri.scheme == "content") {
+ val filePathGetter = getNewFilePath()
+ SaveAsDialog(this, filePathGetter.first, filePathGetter.second) {
+ saveBitmapToFile(bitmap, it, true)
+ }
+ }
+ } else {
+ val currentFilter = getFiltersAdapter()?.getCurrentFilter() ?: return
+ val filePathGetter = getNewFilePath()
+ SaveAsDialog(this, filePathGetter.first, filePathGetter.second) {
+ toast(R.string.saving)
+
+ // clean up everything to free as much memory as possible
+ default_image_view.setImageResource(0)
+ crop_image_view.setImageBitmap(null)
+ bottom_actions_filter_list.adapter = null
+ bottom_actions_filter_list.beGone()
+
+ ensureBackgroundThread {
+ try {
+ val originalBitmap = Glide.with(applicationContext).asBitmap().load(uri).submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get()
+ currentFilter.filter.processFilter(originalBitmap)
+ saveBitmapToFile(originalBitmap, it, false)
+ } catch (e: OutOfMemoryError) {
+ toast(R.string.out_of_memory_error)
+ }
+ }
+ }
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.N)
+ private fun setOldExif() {
+ var inputStream: InputStream? = null
+ try {
+ if (isNougatPlus()) {
+ inputStream = contentResolver.openInputStream(uri!!)
+ oldExif = ExifInterface(inputStream!!)
+ }
+ } catch (e: Exception) {
+ } finally {
+ inputStream?.close()
+ }
+ }
+
+ private fun shareImage() {
+ ensureBackgroundThread {
+ when {
+ default_image_view.isVisible() -> {
+ val currentFilter = getFiltersAdapter()?.getCurrentFilter()
+ if (currentFilter == null) {
+ toast(R.string.unknown_error_occurred)
+ return@ensureBackgroundThread
+ }
+
+ val originalBitmap = Glide.with(applicationContext).asBitmap().load(uri).submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get()
+ currentFilter.filter.processFilter(originalBitmap)
+ shareBitmap(originalBitmap)
+ }
+ crop_image_view.isVisible() -> {
+ isSharingBitmap = true
+ runOnUiThread {
+ crop_image_view.getCroppedImageAsync()
+ }
+ }
+ editor_draw_canvas.isVisible() -> shareBitmap(editor_draw_canvas.getBitmap())
+ }
+ }
+ }
+
+ private fun getTempImagePath(bitmap: Bitmap, callback: (path: String?) -> Unit) {
+ val bytes = ByteArrayOutputStream()
+ bitmap.compress(CompressFormat.PNG, 0, bytes)
+
+ val folder = File(cacheDir, TEMP_FOLDER_NAME)
+ if (!folder.exists()) {
+ if (!folder.mkdir()) {
+ callback(null)
+ return
+ }
+ }
+
+ val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: "tmp.jpg"
+ val newPath = "$folder/$filename"
+ val fileDirItem = FileDirItem(newPath, filename)
+ getFileOutputStream(fileDirItem, true) {
+ if (it != null) {
+ try {
+ it.write(bytes.toByteArray())
+ callback(newPath)
+ } catch (e: Exception) {
+ } finally {
+ it.close()
+ }
+ } else {
+ callback("")
+ }
+ }
+ }
+
+ private fun shareBitmap(bitmap: Bitmap) {
+ getTempImagePath(bitmap) {
+ if (it != null) {
+ sharePathIntent(it, BuildConfig.APPLICATION_ID)
+ } else {
+ toast(R.string.unknown_error_occurred)
+ }
+ }
+ }
+
+ private fun getFiltersAdapter() = bottom_actions_filter_list.adapter as? FiltersAdapter
+
+ private fun setupBottomActions() {
+ setupPrimaryActionButtons()
+ setupCropRotateActionButtons()
+ setupAspectRatioButtons()
+ setupDrawButtons()
+ }
+
+ private fun setupPrimaryActionButtons() {
+ bottom_primary_filter.setOnClickListener {
+ bottomFilterClicked()
+ }
+
+ bottom_primary_crop_rotate.setOnClickListener {
+ bottomCropRotateClicked()
+ }
+
+ bottom_primary_draw.setOnClickListener {
+ bottomDrawClicked()
+ }
+ }
+
+ private fun bottomFilterClicked() {
+ currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_FILTER) {
+ PRIMARY_ACTION_NONE
+ } else {
+ PRIMARY_ACTION_FILTER
+ }
+ updatePrimaryActionButtons()
+ }
+
+ private fun bottomCropRotateClicked() {
+ currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE) {
+ PRIMARY_ACTION_NONE
+ } else {
+ PRIMARY_ACTION_CROP_ROTATE
+ }
+ updatePrimaryActionButtons()
+ }
+
+ private fun bottomDrawClicked() {
+ currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_DRAW) {
+ PRIMARY_ACTION_NONE
+ } else {
+ PRIMARY_ACTION_DRAW
+ }
+ updatePrimaryActionButtons()
+ }
+
+ private fun setupCropRotateActionButtons() {
+ bottom_rotate.setOnClickListener {
+ crop_image_view.rotateImage(90)
+ }
+
+ bottom_resize.beGoneIf(isCropIntent)
+ bottom_resize.setOnClickListener {
+ resizeImage()
+ }
+
+ bottom_flip_horizontally.setOnClickListener {
+ crop_image_view.flipImageHorizontally()
+ }
+
+ bottom_flip_vertically.setOnClickListener {
+ crop_image_view.flipImageVertically()
+ }
+
+ bottom_aspect_ratio.setOnClickListener {
+ currCropRotateAction = if (currCropRotateAction == CROP_ROTATE_ASPECT_RATIO) {
+ crop_image_view.guidelines = CropImageView.Guidelines.OFF
+ bottom_aspect_ratios.beGone()
+ CROP_ROTATE_NONE
+ } else {
+ crop_image_view.guidelines = CropImageView.Guidelines.ON
+ bottom_aspect_ratios.beVisible()
+ CROP_ROTATE_ASPECT_RATIO
+ }
+ updateCropRotateActionButtons()
+ }
+ }
+
+ private fun setupAspectRatioButtons() {
+ bottom_aspect_ratio_free.setOnClickListener {
+ updateAspectRatio(ASPECT_RATIO_FREE)
+ }
+
+ bottom_aspect_ratio_one_one.setOnClickListener {
+ updateAspectRatio(ASPECT_RATIO_ONE_ONE)
+ }
+
+ bottom_aspect_ratio_four_three.setOnClickListener {
+ updateAspectRatio(ASPECT_RATIO_FOUR_THREE)
+ }
+
+ bottom_aspect_ratio_sixteen_nine.setOnClickListener {
+ updateAspectRatio(ASPECT_RATIO_SIXTEEN_NINE)
+ }
+
+ bottom_aspect_ratio_other.setOnClickListener {
+ OtherAspectRatioDialog(this, lastOtherAspectRatio) {
+ lastOtherAspectRatio = it
+ config.lastEditorCropOtherAspectRatioX = it.first
+ config.lastEditorCropOtherAspectRatioY = it.second
+ updateAspectRatio(ASPECT_RATIO_OTHER)
+ }
+ }
+
+ updateAspectRatioButtons()
+ }
+
+ private fun setupDrawButtons() {
+ updateDrawColor(config.lastEditorDrawColor)
+ bottom_draw_width.progress = config.lastEditorBrushSize
+ updateBrushSize(config.lastEditorBrushSize)
+
+ bottom_draw_color_clickable.setOnClickListener {
+ ColorPickerDialog(this, drawColor) { wasPositivePressed, color ->
+ if (wasPositivePressed) {
+ updateDrawColor(color)
+ }
+ }
+ }
+
+ bottom_draw_width.onSeekBarChangeListener {
+ config.lastEditorBrushSize = it
+ updateBrushSize(it)
+ }
+
+ bottom_draw_undo.setOnClickListener {
+ editor_draw_canvas.undo()
+ }
+ }
+
+ private fun updateBrushSize(percent: Int) {
+ editor_draw_canvas.updateBrushSize(percent)
+ val scale = Math.max(0.03f, percent / 100f)
+ bottom_draw_color.scaleX = scale
+ bottom_draw_color.scaleY = scale
+ }
+
+ private fun updatePrimaryActionButtons() {
+ if (crop_image_view.isGone() && currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE) {
+ loadCropImageView()
+ } else if (default_image_view.isGone() && currPrimaryAction == PRIMARY_ACTION_FILTER) {
+ loadDefaultImageView()
+ } else if (editor_draw_canvas.isGone() && currPrimaryAction == PRIMARY_ACTION_DRAW) {
+ loadDrawCanvas()
+ }
+
+ arrayOf(bottom_primary_filter, bottom_primary_crop_rotate, bottom_primary_draw).forEach {
+ it.applyColorFilter(Color.WHITE)
+ }
+
+ val currentPrimaryActionButton = when (currPrimaryAction) {
+ PRIMARY_ACTION_FILTER -> bottom_primary_filter
+ PRIMARY_ACTION_CROP_ROTATE -> bottom_primary_crop_rotate
+ PRIMARY_ACTION_DRAW -> bottom_primary_draw
+ else -> null
+ }
+
+ currentPrimaryActionButton?.applyColorFilter(getAdjustedPrimaryColor())
+ bottom_editor_filter_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_FILTER)
+ bottom_editor_crop_rotate_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE)
+ bottom_editor_draw_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_DRAW)
+
+ if (currPrimaryAction == PRIMARY_ACTION_FILTER && bottom_actions_filter_list.adapter == null) {
+ ensureBackgroundThread {
+ val thumbnailSize = resources.getDimension(R.dimen.bottom_filters_thumbnail_size).toInt()
+
+ val bitmap = try {
+ Glide.with(this)
+ .asBitmap()
+ .load(uri).listener(object : RequestListener {
+ override fun onLoadFailed(e: GlideException?, model: Any?, target: Target?, isFirstResource: Boolean): Boolean {
+ showErrorToast(e.toString())
+ return false
+ }
+
+ override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target?, dataSource: DataSource?, isFirstResource: Boolean) = false
+ })
+ .submit(thumbnailSize, thumbnailSize)
+ .get()
+ } catch (e: GlideException) {
+ showErrorToast(e)
+ finish()
+ return@ensureBackgroundThread
+ }
+
+ runOnUiThread {
+ val filterThumbnailsManager = FilterThumbnailsManager()
+ filterThumbnailsManager.clearThumbs()
+
+ val noFilter = Filter(getString(R.string.none))
+ filterThumbnailsManager.addThumb(FilterItem(bitmap, noFilter))
+
+ FilterPack.getFilterPack(this).forEach {
+ val filterItem = FilterItem(bitmap, it)
+ filterThumbnailsManager.addThumb(filterItem)
+ }
+
+ val filterItems = filterThumbnailsManager.processThumbs()
+ val adapter = FiltersAdapter(applicationContext, filterItems) {
+ val layoutManager = bottom_actions_filter_list.layoutManager as LinearLayoutManager
+ applyFilter(filterItems[it])
+
+ if (it == layoutManager.findLastCompletelyVisibleItemPosition() || it == layoutManager.findLastVisibleItemPosition()) {
+ bottom_actions_filter_list.smoothScrollBy(thumbnailSize, 0)
+ } else if (it == layoutManager.findFirstCompletelyVisibleItemPosition() || it == layoutManager.findFirstVisibleItemPosition()) {
+ bottom_actions_filter_list.smoothScrollBy(-thumbnailSize, 0)
+ }
+ }
+
+ bottom_actions_filter_list.adapter = adapter
+ adapter.notifyDataSetChanged()
+ }
+ }
+ }
+
+ if (currPrimaryAction != PRIMARY_ACTION_CROP_ROTATE) {
+ bottom_aspect_ratios.beGone()
+ currCropRotateAction = CROP_ROTATE_NONE
+ }
+ updateCropRotateActionButtons()
+ }
+
+ private fun applyFilter(filterItem: FilterItem) {
+ val newBitmap = Bitmap.createBitmap(filterInitialBitmap!!)
+ default_image_view.setImageBitmap(filterItem.filter.processFilter(newBitmap))
+ }
+
+ private fun updateAspectRatio(aspectRatio: Int) {
+ currAspectRatio = aspectRatio
+ config.lastEditorCropAspectRatio = aspectRatio
+ updateAspectRatioButtons()
+
+ crop_image_view.apply {
+ if (aspectRatio == ASPECT_RATIO_FREE) {
+ setFixedAspectRatio(false)
+ } else {
+ val newAspectRatio = when (aspectRatio) {
+ ASPECT_RATIO_ONE_ONE -> Pair(1f, 1f)
+ ASPECT_RATIO_FOUR_THREE -> Pair(4f, 3f)
+ ASPECT_RATIO_SIXTEEN_NINE -> Pair(16f, 9f)
+ else -> Pair(lastOtherAspectRatio!!.first, lastOtherAspectRatio!!.second)
+ }
+
+ setAspectRatio(newAspectRatio.first.toInt(), newAspectRatio.second.toInt())
+ }
+ }
+ }
+
+ private fun updateAspectRatioButtons() {
+ arrayOf(bottom_aspect_ratio_free, bottom_aspect_ratio_one_one, bottom_aspect_ratio_four_three, bottom_aspect_ratio_sixteen_nine, bottom_aspect_ratio_other).forEach {
+ it.setTextColor(Color.WHITE)
+ }
+
+ val currentAspectRatioButton = when (currAspectRatio) {
+ ASPECT_RATIO_FREE -> bottom_aspect_ratio_free
+ ASPECT_RATIO_ONE_ONE -> bottom_aspect_ratio_one_one
+ ASPECT_RATIO_FOUR_THREE -> bottom_aspect_ratio_four_three
+ ASPECT_RATIO_SIXTEEN_NINE -> bottom_aspect_ratio_sixteen_nine
+ else -> bottom_aspect_ratio_other
+ }
+
+ currentAspectRatioButton.setTextColor(getAdjustedPrimaryColor())
+ }
+
+ private fun updateCropRotateActionButtons() {
+ arrayOf(bottom_aspect_ratio).forEach {
+ it.applyColorFilter(Color.WHITE)
+ }
+
+ val primaryActionView = when (currCropRotateAction) {
+ CROP_ROTATE_ASPECT_RATIO -> bottom_aspect_ratio
+ else -> null
+ }
+
+ primaryActionView?.applyColorFilter(getAdjustedPrimaryColor())
+ }
+
+ private fun updateDrawColor(color: Int) {
+ drawColor = color
+ bottom_draw_color.applyColorFilter(color)
+ config.lastEditorDrawColor = color
+ editor_draw_canvas.updateColor(color)
+ }
+
+ private fun resizeImage() {
+ val point = getAreaSize()
+ if (point == null) {
+ toast(R.string.unknown_error_occurred)
+ return
+ }
+
+ ResizeDialog(this, point) {
+ resizeWidth = it.x
+ resizeHeight = it.y
+ crop_image_view.getCroppedImageAsync()
+ }
+ }
+
+ private fun shouldCropSquare(): Boolean {
+ val extras = intent.extras
+ return if (extras != null && extras.containsKey(ASPECT_X) && extras.containsKey(ASPECT_Y)) {
+ extras.getInt(ASPECT_X) == extras.getInt(ASPECT_Y)
+ } else {
+ false
+ }
+ }
+
+ private fun getAreaSize(): Point? {
+ val rect = crop_image_view.cropRect ?: return null
+ val rotation = crop_image_view.rotatedDegrees
+ return if (rotation == 0 || rotation == 180) {
+ Point(rect.width(), rect.height())
+ } else {
+ Point(rect.height(), rect.width())
+ }
+ }
+
+ override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) {
+ if (result.error == null) {
+ setOldExif()
+
+ val bitmap = result.bitmap
+ if (isSharingBitmap) {
+ isSharingBitmap = false
+ shareBitmap(bitmap)
+ return
+ }
+
+ if (isCropIntent) {
+ if (saveUri.scheme == "file") {
+ saveBitmapToFile(bitmap, saveUri.path!!, true)
+ } else {
+ var inputStream: InputStream? = null
+ var outputStream: OutputStream? = null
+ try {
+ val stream = ByteArrayOutputStream()
+ bitmap.compress(CompressFormat.JPEG, 100, stream)
+ inputStream = ByteArrayInputStream(stream.toByteArray())
+ outputStream = contentResolver.openOutputStream(saveUri)
+ inputStream.copyTo(outputStream!!)
+ } finally {
+ inputStream?.close()
+ outputStream?.close()
+ }
+
+ Intent().apply {
+ data = saveUri
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ setResult(RESULT_OK, this)
+ }
+ finish()
+ }
+ } else if (saveUri.scheme == "file") {
+ SaveAsDialog(this, saveUri.path!!, true) {
+ saveBitmapToFile(bitmap, it, true)
+ }
+ } else if (saveUri.scheme == "content") {
+ val filePathGetter = getNewFilePath()
+ SaveAsDialog(this, filePathGetter.first, filePathGetter.second) {
+ saveBitmapToFile(bitmap, it, true)
+ }
+ } else {
+ toast(R.string.unknown_file_location)
+ }
+ } else {
+ toast("${getString(R.string.image_editing_failed)}: ${result.error.message}")
+ }
+ }
+
+ private fun getNewFilePath(): Pair {
+ var newPath = applicationContext.getRealPathFromURI(saveUri) ?: ""
+ if (newPath.startsWith("/mnt/")) {
+ newPath = ""
+ }
+
+ var shouldAppendFilename = true
+ if (newPath.isEmpty()) {
+ val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: ""
+ if (filename.isNotEmpty()) {
+ val path = if (intent.extras?.containsKey(REAL_FILE_PATH) == true) intent.getStringExtra(REAL_FILE_PATH).getParentPath() else internalStoragePath
+ newPath = "$path/$filename"
+ shouldAppendFilename = false
+ }
+ }
+
+ if (newPath.isEmpty()) {
+ newPath = "$internalStoragePath/${getCurrentFormattedDateTime()}.${saveUri.toString().getFilenameExtension()}"
+ shouldAppendFilename = false
+ }
+
+ return Pair(newPath, shouldAppendFilename)
+ }
+
+ private fun saveBitmapToFile(bitmap: Bitmap, path: String, showSavingToast: Boolean) {
+ if (!packageName.contains("slootelibomelpmis".reversed(), true)) {
+ if (baseConfig.appRunCount > 100) {
+ val label = "sknahT .moc.slootelibomelpmis.www morf eno lanigiro eht daolnwod ytefas nwo ruoy roF .ppa eht fo noisrev ekaf a gnisu era uoY".reversed()
+ runOnUiThread {
+ ConfirmationDialog(this, label, positive = com.simplemobiletools.commons.R.string.ok, negative = 0) {
+ launchViewIntent("6629852208836920709=di?ved/sppa/erots/moc.elgoog.yalp//:sptth".reversed())
+ }
+ }
+ return
+ }
+ }
+
+ try {
+ ensureBackgroundThread {
+ val file = File(path)
+ val fileDirItem = FileDirItem(path, path.getFilenameFromPath())
+ getFileOutputStream(fileDirItem, true) {
+ if (it != null) {
+ saveBitmap(file, bitmap, it, showSavingToast)
+ } else {
+ toast(R.string.image_editing_failed)
+ }
+ }
+ }
+ } catch (e: Exception) {
+ showErrorToast(e)
+ } catch (e: OutOfMemoryError) {
+ toast(R.string.out_of_memory_error)
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.N)
+ private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream, showSavingToast: Boolean) {
+ if (showSavingToast) {
+ toast(R.string.saving)
+ }
+
+ if (resizeWidth > 0 && resizeHeight > 0) {
+ val resized = Bitmap.createScaledBitmap(bitmap, resizeWidth, resizeHeight, false)
+ resized.compress(file.absolutePath.getCompressionFormat(), 90, out)
+ } else {
+ bitmap.compress(file.absolutePath.getCompressionFormat(), 90, out)
+ }
+
+ try {
+ if (isNougatPlus()) {
+ val newExif = ExifInterface(file.absolutePath)
+ oldExif?.copyNonDimensionAttributesTo(newExif)
+ }
+ } catch (e: Exception) {
+ }
+
+ setResult(Activity.RESULT_OK, intent)
+ scanFinalPath(file.absolutePath)
+ out.close()
+ }
+
+ private fun editWith() {
+ openEditor(uri.toString(), true)
+ isEditingWithThirdParty = true
+ }
+
+ private fun scanFinalPath(path: String) {
+ val paths = arrayListOf(path)
+ rescanPaths(paths) {
+ fixDateTaken(paths, false)
+ setResult(Activity.RESULT_OK, intent)
+ toast(R.string.file_saved)
+ finish()
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/ExcludedFoldersActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/ExcludedFoldersActivity.kt
new file mode 100644
index 000000000..2d584ab73
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/ExcludedFoldersActivity.kt
@@ -0,0 +1,59 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.os.Bundle
+import android.view.Menu
+import android.view.MenuItem
+import com.simplemobiletools.commons.dialogs.FilePickerDialog
+import com.simplemobiletools.commons.extensions.beVisibleIf
+import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.ManageFoldersAdapter
+import com.simplemobiletools.gallery.pro.extensions.config
+import kotlinx.android.synthetic.main.activity_manage_folders.*
+
+class ExcludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_manage_folders)
+ updateFolders()
+ }
+
+ private fun updateFolders() {
+ val folders = ArrayList()
+ config.excludedFolders.mapTo(folders) { it }
+ manage_folders_placeholder.apply {
+ text = getString(R.string.excluded_activity_placeholder)
+ beVisibleIf(folders.isEmpty())
+ setTextColor(config.textColor)
+ }
+
+ val adapter = ManageFoldersAdapter(this, folders, true, this, manage_folders_list) {}
+ manage_folders_list.adapter = adapter
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_add_folder, menu)
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.add_folder -> addFolder()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ override fun refreshItems() {
+ updateFolders()
+ }
+
+ private fun addFolder() {
+ FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden, false, true, true) {
+ config.lastFilepickerPath = it
+ config.addExcludedFolder(it)
+ updateFolders()
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/HiddenFoldersActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/HiddenFoldersActivity.kt
new file mode 100644
index 000000000..4a5aaac85
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/HiddenFoldersActivity.kt
@@ -0,0 +1,67 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.os.Bundle
+import android.view.Menu
+import android.view.MenuItem
+import com.simplemobiletools.commons.dialogs.FilePickerDialog
+import com.simplemobiletools.commons.extensions.beVisibleIf
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.ManageHiddenFoldersAdapter
+import com.simplemobiletools.gallery.pro.extensions.addNoMedia
+import com.simplemobiletools.gallery.pro.extensions.config
+import com.simplemobiletools.gallery.pro.extensions.getNoMediaFolders
+import kotlinx.android.synthetic.main.activity_manage_folders.*
+
+class HiddenFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_manage_folders)
+ updateFolders()
+ }
+
+ private fun updateFolders() {
+ getNoMediaFolders {
+ runOnUiThread {
+ manage_folders_placeholder.apply {
+ text = getString(R.string.hidden_folders_placeholder)
+ beVisibleIf(it.isEmpty())
+ setTextColor(config.textColor)
+ }
+
+ val adapter = ManageHiddenFoldersAdapter(this, it, this, manage_folders_list) {}
+ manage_folders_list.adapter = adapter
+ }
+ }
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_add_folder, menu)
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.add_folder -> addFolder()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ override fun refreshItems() {
+ updateFolders()
+ }
+
+ private fun addFolder() {
+ FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden, false, true) {
+ config.lastFilepickerPath = it
+ ensureBackgroundThread {
+ addNoMedia(it) {
+ updateFolders()
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/IncludedFoldersActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/IncludedFoldersActivity.kt
new file mode 100644
index 000000000..e1f0d9a06
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/IncludedFoldersActivity.kt
@@ -0,0 +1,56 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.os.Bundle
+import android.view.Menu
+import android.view.MenuItem
+import com.simplemobiletools.commons.extensions.beVisibleIf
+import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.ManageFoldersAdapter
+import com.simplemobiletools.gallery.pro.extensions.config
+import kotlinx.android.synthetic.main.activity_manage_folders.*
+
+class IncludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_manage_folders)
+ updateFolders()
+ }
+
+ private fun updateFolders() {
+ val folders = ArrayList()
+ config.includedFolders.mapTo(folders) { it }
+ manage_folders_placeholder.apply {
+ text = getString(R.string.included_activity_placeholder)
+ beVisibleIf(folders.isEmpty())
+ setTextColor(config.textColor)
+ }
+
+ val adapter = ManageFoldersAdapter(this, folders, false, this, manage_folders_list) {}
+ manage_folders_list.adapter = adapter
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_add_folder, menu)
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.add_folder -> addFolder()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ override fun refreshItems() {
+ updateFolders()
+ }
+
+ private fun addFolder() {
+ showAddIncludedFolderDialog {
+ updateFolders()
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/MainActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/MainActivity.kt
new file mode 100644
index 000000000..496f0968d
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/MainActivity.kt
@@ -0,0 +1,1443 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.app.Activity
+import android.app.SearchManager
+import android.content.ClipData
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Bundle
+import android.os.Handler
+import android.provider.MediaStore
+import android.provider.MediaStore.Images
+import android.provider.MediaStore.Video
+import android.view.Menu
+import android.view.MenuItem
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import android.widget.RelativeLayout
+import android.widget.Toast
+import androidx.appcompat.widget.SearchView
+import androidx.core.view.MenuItemCompat
+import androidx.recyclerview.widget.RecyclerView
+import com.simplemobiletools.commons.dialogs.ConfirmationDialog
+import com.simplemobiletools.commons.dialogs.CreateNewFolderDialog
+import com.simplemobiletools.commons.dialogs.FilePickerDialog
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.*
+import com.simplemobiletools.commons.models.FileDirItem
+import com.simplemobiletools.commons.models.Release
+import com.simplemobiletools.commons.views.MyGridLayoutManager
+import com.simplemobiletools.commons.views.MyRecyclerView
+import com.simplemobiletools.gallery.pro.BuildConfig
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.DirectoryAdapter
+import com.simplemobiletools.gallery.pro.databases.GalleryDatabase
+import com.simplemobiletools.gallery.pro.dialogs.ChangeSortingDialog
+import com.simplemobiletools.gallery.pro.dialogs.ChangeViewTypeDialog
+import com.simplemobiletools.gallery.pro.dialogs.FilterMediaDialog
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.interfaces.DirectoryOperationsListener
+import com.simplemobiletools.gallery.pro.jobs.NewPhotoFetcher
+import com.simplemobiletools.gallery.pro.models.Directory
+import com.simplemobiletools.gallery.pro.models.Medium
+import kotlinx.android.synthetic.main.activity_main.*
+import java.io.*
+import java.util.*
+import kotlin.collections.ArrayList
+
+class MainActivity : SimpleActivity(), DirectoryOperationsListener {
+ private val PICK_MEDIA = 2
+ private val PICK_WALLPAPER = 3
+ private val LAST_MEDIA_CHECK_PERIOD = 3000L
+
+ private var mIsPickImageIntent = false
+ private var mIsPickVideoIntent = false
+ private var mIsGetImageContentIntent = false
+ private var mIsGetVideoContentIntent = false
+ private var mIsGetAnyContentIntent = false
+ private var mIsSetWallpaperIntent = false
+ private var mAllowPickingMultiple = false
+ private var mIsThirdPartyIntent = false
+ private var mIsGettingDirs = false
+ private var mLoadedInitialPhotos = false
+ private var mIsPasswordProtectionPending = false
+ private var mWasProtectionHandled = false
+ private var mShouldStopFetching = false
+ private var mIsSearchOpen = false
+ private var mWasDefaultFolderChecked = false
+ private var mLatestMediaId = 0L
+ private var mLatestMediaDateId = 0L
+ private var mCurrentPathPrefix = "" // used at "Group direct subfolders" for navigation
+ private var mOpenedSubfolders = arrayListOf("") // used at "Group direct subfolders" for navigating Up with the back button
+ private var mDateFormat = ""
+ private var mTimeFormat = ""
+ private var mLastMediaHandler = Handler()
+ private var mTempShowHiddenHandler = Handler()
+ private var mZoomListener: MyRecyclerView.MyZoomListener? = null
+ private var mSearchMenuItem: MenuItem? = null
+ private var mLastMediaFetcher: MediaFetcher? = null
+ private var mDirs = ArrayList()
+
+ private var mStoredAnimateGifs = true
+ private var mStoredCropThumbnails = true
+ private var mStoredScrollHorizontally = true
+ private var mStoredTextColor = 0
+ private var mStoredPrimaryColor = 0
+ private var mStoredStyleString = ""
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_main)
+ appLaunched(BuildConfig.APPLICATION_ID)
+
+ if (savedInstanceState == null) {
+ config.temporarilyShowHidden = false
+ config.tempSkipDeleteConfirmation = false
+ removeTempFolder()
+ checkRecycleBinItems()
+ startNewPhotoFetcher()
+ }
+
+ mIsPickImageIntent = isPickImageIntent(intent)
+ mIsPickVideoIntent = isPickVideoIntent(intent)
+ mIsGetImageContentIntent = isGetImageContentIntent(intent)
+ mIsGetVideoContentIntent = isGetVideoContentIntent(intent)
+ mIsGetAnyContentIntent = isGetAnyContentIntent(intent)
+ mIsSetWallpaperIntent = isSetWallpaperIntent(intent)
+ mAllowPickingMultiple = intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
+ mIsThirdPartyIntent = mIsPickImageIntent || mIsPickVideoIntent || mIsGetImageContentIntent || mIsGetVideoContentIntent ||
+ mIsGetAnyContentIntent || mIsSetWallpaperIntent
+
+ directories_refresh_layout.setOnRefreshListener { getDirectories() }
+ storeStateVariables()
+ checkWhatsNewDialog()
+
+ mIsPasswordProtectionPending = config.isAppPasswordProtectionOn
+ setupLatestMediaId()
+
+ if (!config.wereFavoritesPinned) {
+ config.addPinnedFolders(hashSetOf(FAVORITES))
+ config.wereFavoritesPinned = true
+ }
+
+ if (!config.wasRecycleBinPinned) {
+ config.addPinnedFolders(hashSetOf(RECYCLE_BIN))
+ config.wasRecycleBinPinned = true
+ config.saveFolderGrouping(SHOW_ALL, GROUP_BY_DATE_TAKEN_DAILY or GROUP_DESCENDING)
+ }
+
+ if (!config.wasSVGShowingHandled) {
+ config.wasSVGShowingHandled = true
+ if (config.filterMedia and TYPE_SVGS == 0) {
+ config.filterMedia += TYPE_SVGS
+ }
+ }
+
+ if (!config.wasSortingByNumericValueAdded) {
+ config.wasSortingByNumericValueAdded = true
+ config.sorting = config.sorting or SORT_USE_NUMERIC_VALUE
+ }
+
+ updateWidgets()
+ registerFileUpdateListener()
+
+ directories_switch_searching.setOnClickListener {
+ launchSearchActivity()
+ }
+
+ // just request the permission, tryLoadGallery will then trigger in onResume
+ handlePermission(PERMISSION_WRITE_STORAGE) {
+ if (!it) {
+ toast(R.string.no_storage_permissions)
+ finish()
+ }
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ mTempShowHiddenHandler.removeCallbacksAndMessages(null)
+ }
+
+ override fun onResume() {
+ super.onResume()
+ config.isThirdPartyIntent = false
+ mDateFormat = config.dateFormat
+ mTimeFormat = getTimeFormat()
+
+ if (mStoredAnimateGifs != config.animateGifs) {
+ getRecyclerAdapter()?.updateAnimateGifs(config.animateGifs)
+ }
+
+ if (mStoredCropThumbnails != config.cropThumbnails) {
+ getRecyclerAdapter()?.updateCropThumbnails(config.cropThumbnails)
+ }
+
+ if (mStoredScrollHorizontally != config.scrollHorizontally) {
+ mLoadedInitialPhotos = false
+ directories_grid.adapter = null
+ getDirectories()
+ }
+
+ if (mStoredTextColor != config.textColor) {
+ getRecyclerAdapter()?.updateTextColor(config.textColor)
+ }
+
+ if (mStoredPrimaryColor != config.primaryColor) {
+ getRecyclerAdapter()?.updatePrimaryColor(config.primaryColor)
+ directories_vertical_fastscroller.updatePrimaryColor()
+ directories_horizontal_fastscroller.updatePrimaryColor()
+ }
+
+ val styleString = "${config.folderStyle}${config.showFolderMediaCount}${config.limitFolderTitle}"
+ if (mStoredStyleString != styleString) {
+ setupAdapter(mDirs, forceRecreate = true)
+ }
+
+ directories_horizontal_fastscroller.updateBubbleColors()
+ directories_vertical_fastscroller.updateBubbleColors()
+ directories_refresh_layout.isEnabled = config.enablePullToRefresh
+
+ directories_empty_placeholder.setTextColor(config.textColor)
+ directories_empty_placeholder_2.setTextColor(getAdjustedPrimaryColor())
+ directories_switch_searching.setTextColor(getAdjustedPrimaryColor())
+ directories_switch_searching.underlineText()
+
+ if (!mIsSearchOpen) {
+ invalidateOptionsMenu()
+ if (mIsPasswordProtectionPending && !mWasProtectionHandled) {
+ handleAppPasswordProtection {
+ mWasProtectionHandled = it
+ if (it) {
+ mIsPasswordProtectionPending = false
+ tryLoadGallery()
+ } else {
+ finish()
+ }
+ }
+ } else {
+ tryLoadGallery()
+ }
+ }
+ }
+
+ override fun onPause() {
+ super.onPause()
+ directories_refresh_layout.isRefreshing = false
+ mIsGettingDirs = false
+ storeStateVariables()
+ mLastMediaHandler.removeCallbacksAndMessages(null)
+ }
+
+ override fun onStop() {
+ super.onStop()
+
+ if (config.temporarilyShowHidden || config.tempSkipDeleteConfirmation) {
+ mTempShowHiddenHandler.postDelayed({
+ config.temporarilyShowHidden = false
+ config.tempSkipDeleteConfirmation = false
+ }, SHOW_TEMP_HIDDEN_DURATION)
+ } else {
+ mTempShowHiddenHandler.removeCallbacksAndMessages(null)
+ }
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ if (!isChangingConfigurations) {
+ config.temporarilyShowHidden = false
+ config.tempSkipDeleteConfirmation = false
+ mTempShowHiddenHandler.removeCallbacksAndMessages(null)
+ removeTempFolder()
+ unregisterFileUpdateListener()
+
+ if (!config.showAll) {
+ mLastMediaFetcher?.shouldStop = true
+ GalleryDatabase.destroyInstance()
+ }
+ }
+ }
+
+ override fun onBackPressed() {
+ if (config.groupDirectSubfolders) {
+ if (mCurrentPathPrefix.isEmpty()) {
+ super.onBackPressed()
+ } else {
+ mOpenedSubfolders.removeAt(mOpenedSubfolders.size - 1)
+ mCurrentPathPrefix = mOpenedSubfolders.last()
+ setupAdapter(mDirs)
+ }
+ } else {
+ super.onBackPressed()
+ }
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ if (mIsThirdPartyIntent) {
+ menuInflater.inflate(R.menu.menu_main_intent, menu)
+ } else {
+ menuInflater.inflate(R.menu.menu_main, menu)
+ val useBin = config.useRecycleBin
+ menu.apply {
+ findItem(R.id.increase_column_count).isVisible = config.viewTypeFolders == VIEW_TYPE_GRID && config.dirColumnCnt < MAX_COLUMN_COUNT
+ findItem(R.id.reduce_column_count).isVisible = config.viewTypeFolders == VIEW_TYPE_GRID && config.dirColumnCnt > 1
+ findItem(R.id.hide_the_recycle_bin).isVisible = useBin && config.showRecycleBinAtFolders
+ findItem(R.id.show_the_recycle_bin).isVisible = useBin && !config.showRecycleBinAtFolders
+ findItem(R.id.set_as_default_folder).isVisible = !config.defaultFolder.isEmpty()
+ setupSearch(this)
+ }
+ }
+
+ menu.findItem(R.id.temporarily_show_hidden).isVisible = !config.shouldShowHidden
+ menu.findItem(R.id.stop_showing_hidden).isVisible = config.temporarilyShowHidden
+
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.sort -> showSortingDialog()
+ R.id.filter -> showFilterMediaDialog()
+ R.id.open_camera -> launchCamera()
+ R.id.show_all -> showAllMedia()
+ R.id.change_view_type -> changeViewType()
+ R.id.temporarily_show_hidden -> tryToggleTemporarilyShowHidden()
+ R.id.stop_showing_hidden -> tryToggleTemporarilyShowHidden()
+ R.id.create_new_folder -> createNewFolder()
+ R.id.show_the_recycle_bin -> toggleRecycleBin(true)
+ R.id.hide_the_recycle_bin -> toggleRecycleBin(false)
+ R.id.increase_column_count -> increaseColumnCount()
+ R.id.reduce_column_count -> reduceColumnCount()
+ R.id.set_as_default_folder -> setAsDefaultFolder()
+ R.id.settings -> launchSettings()
+ R.id.about -> launchAbout()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ super.onSaveInstanceState(outState)
+ outState.putBoolean(WAS_PROTECTION_HANDLED, mWasProtectionHandled)
+ }
+
+ override fun onRestoreInstanceState(savedInstanceState: Bundle) {
+ super.onRestoreInstanceState(savedInstanceState)
+ mWasProtectionHandled = savedInstanceState.getBoolean(WAS_PROTECTION_HANDLED, false)
+ }
+
+ private fun getRecyclerAdapter() = directories_grid.adapter as? DirectoryAdapter
+
+ private fun storeStateVariables() {
+ config.apply {
+ mStoredAnimateGifs = animateGifs
+ mStoredCropThumbnails = cropThumbnails
+ mStoredScrollHorizontally = scrollHorizontally
+ mStoredTextColor = textColor
+ mStoredPrimaryColor = primaryColor
+ mStoredStyleString = "$folderStyle$showFolderMediaCount$limitFolderTitle"
+ }
+ }
+
+ private fun setupSearch(menu: Menu) {
+ val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
+ mSearchMenuItem = menu.findItem(R.id.search)
+ (mSearchMenuItem?.actionView as? SearchView)?.apply {
+ setSearchableInfo(searchManager.getSearchableInfo(componentName))
+ isSubmitButtonEnabled = false
+ setOnQueryTextListener(object : SearchView.OnQueryTextListener {
+ override fun onQueryTextSubmit(query: String) = false
+
+ override fun onQueryTextChange(newText: String): Boolean {
+ if (mIsSearchOpen) {
+ setupAdapter(mDirs, newText)
+ }
+ return true
+ }
+ })
+ }
+
+ MenuItemCompat.setOnActionExpandListener(mSearchMenuItem, object : MenuItemCompat.OnActionExpandListener {
+ override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
+ directories_switch_searching.beVisible()
+ mIsSearchOpen = true
+ directories_refresh_layout.isEnabled = false
+ return true
+ }
+
+ // this triggers on device rotation too, avoid doing anything
+ override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
+ if (mIsSearchOpen) {
+ directories_switch_searching.beGone()
+ mIsSearchOpen = false
+ directories_refresh_layout.isEnabled = config.enablePullToRefresh
+ setupAdapter(mDirs, "")
+ }
+ return true
+ }
+ })
+ }
+
+ private fun startNewPhotoFetcher() {
+ if (isNougatPlus()) {
+ val photoFetcher = NewPhotoFetcher()
+ if (!photoFetcher.isScheduled(applicationContext)) {
+ photoFetcher.scheduleJob(applicationContext)
+ }
+ }
+ }
+
+ private fun removeTempFolder() {
+ if (config.tempFolderPath.isNotEmpty()) {
+ val newFolder = File(config.tempFolderPath)
+ if (getDoesFilePathExist(newFolder.absolutePath) && newFolder.isDirectory) {
+ if (newFolder.list()?.isEmpty() == true && newFolder.getProperSize(true) == 0L && newFolder.getFileCount(true) == 0) {
+ toast(String.format(getString(R.string.deleting_folder), config.tempFolderPath), Toast.LENGTH_LONG)
+ tryDeleteFileDirItem(newFolder.toFileDirItem(applicationContext), true, true)
+ }
+ }
+ config.tempFolderPath = ""
+ }
+ }
+
+ private fun checkOTGPath() {
+ ensureBackgroundThread {
+ if (!config.wasOTGHandled && hasPermission(PERMISSION_WRITE_STORAGE) && hasOTGConnected() && config.OTGPath.isEmpty()) {
+ getStorageDirectories().firstOrNull { it.trimEnd('/') != internalStoragePath && it.trimEnd('/') != sdCardPath }?.apply {
+ config.wasOTGHandled = true
+ val otgPath = trimEnd('/')
+ config.OTGPath = otgPath
+ config.addIncludedFolder(otgPath)
+ }
+ }
+ }
+ }
+
+ private fun checkDefaultSpamFolders() {
+ if (!config.spamFoldersChecked) {
+ val spamFolders = arrayListOf(
+ "/storage/emulated/0/Android/data/com.facebook.orca/files/stickers"
+ )
+
+ val OTGPath = config.OTGPath
+ spamFolders.forEach {
+ if (getDoesFilePathExist(it, OTGPath)) {
+ config.addExcludedFolder(it)
+ }
+ }
+ config.spamFoldersChecked = true
+ }
+ }
+
+ private fun tryLoadGallery() {
+ handlePermission(PERMISSION_WRITE_STORAGE) {
+ if (it) {
+ if (!mWasDefaultFolderChecked) {
+ openDefaultFolder()
+ mWasDefaultFolderChecked = true
+ }
+
+ if (!config.wasUpgradedFromFreeShown && isPackageInstalled("com.simplemobiletools.gallery")) {
+ ConfirmationDialog(this, "", R.string.upgraded_from_free, R.string.ok, 0) {}
+ config.wasUpgradedFromFreeShown = true
+ }
+
+ checkOTGPath()
+ checkDefaultSpamFolders()
+
+ if (config.showAll) {
+ showAllMedia()
+ } else {
+ getDirectories()
+ }
+
+ setupLayoutManager()
+ } else {
+ toast(R.string.no_storage_permissions)
+ finish()
+ }
+ }
+ }
+
+ private fun getDirectories() {
+ if (mIsGettingDirs) {
+ return
+ }
+
+ mShouldStopFetching = true
+ mIsGettingDirs = true
+ val getImagesOnly = mIsPickImageIntent || mIsGetImageContentIntent
+ val getVideosOnly = mIsPickVideoIntent || mIsGetVideoContentIntent
+
+ getCachedDirectories(getVideosOnly, getImagesOnly) {
+ gotDirectories(addTempFolderIfNeeded(it))
+ }
+ }
+
+ private fun launchSearchActivity() {
+ Intent(this, SearchActivity::class.java).apply {
+ startActivity(this)
+ }
+ }
+
+ private fun showSortingDialog() {
+ ChangeSortingDialog(this, true, false) {
+ directories_grid.adapter = null
+ if (config.directorySorting and SORT_BY_DATE_MODIFIED != 0 || config.directorySorting and SORT_BY_DATE_TAKEN != 0) {
+ getDirectories()
+ } else {
+ ensureBackgroundThread {
+ gotDirectories(getCurrentlyDisplayedDirs())
+ }
+ }
+ }
+ }
+
+ private fun showFilterMediaDialog() {
+ FilterMediaDialog(this) {
+ mShouldStopFetching = true
+ directories_refresh_layout.isRefreshing = true
+ directories_grid.adapter = null
+ getDirectories()
+ }
+ }
+
+ private fun showAllMedia() {
+ config.showAll = true
+ Intent(this, MediaActivity::class.java).apply {
+ putExtra(DIRECTORY, "")
+
+ if (mIsThirdPartyIntent) {
+ handleMediaIntent(this)
+ } else {
+ startActivity(this)
+ finish()
+ }
+ }
+ }
+
+ private fun changeViewType() {
+ ChangeViewTypeDialog(this, true) {
+ invalidateOptionsMenu()
+ setupLayoutManager()
+ directories_grid.adapter = null
+ setupAdapter(getRecyclerAdapter()?.dirs ?: mDirs)
+ }
+ }
+
+ private fun tryToggleTemporarilyShowHidden() {
+ if (config.temporarilyShowHidden) {
+ toggleTemporarilyShowHidden(false)
+ } else {
+ handleHiddenFolderPasswordProtection {
+ toggleTemporarilyShowHidden(true)
+ }
+ }
+ }
+
+ private fun toggleTemporarilyShowHidden(show: Boolean) {
+ mLoadedInitialPhotos = false
+ config.temporarilyShowHidden = show
+ directories_grid.adapter = null
+ getDirectories()
+ invalidateOptionsMenu()
+ }
+
+ override fun deleteFolders(folders: ArrayList) {
+ val fileDirItems = folders.asSequence().filter { it.isDirectory }.map { FileDirItem(it.absolutePath, it.name, true) }.toMutableList() as ArrayList
+ when {
+ fileDirItems.isEmpty() -> return
+ fileDirItems.size == 1 -> {
+ try {
+ toast(String.format(getString(R.string.deleting_folder), fileDirItems.first().name))
+ } catch (e: Exception) {
+ showErrorToast(e)
+ }
+ }
+ else -> {
+ val baseString = if (config.useRecycleBin) R.plurals.moving_items_into_bin else R.plurals.delete_items
+ val deletingItems = resources.getQuantityString(baseString, fileDirItems.size, fileDirItems.size)
+ toast(deletingItems)
+ }
+ }
+
+ val itemsToDelete = ArrayList()
+ val filter = config.filterMedia
+ val showHidden = config.shouldShowHidden
+ fileDirItems.filter { it.isDirectory }.forEach {
+ val files = File(it.path).listFiles()
+ files?.filter {
+ it.absolutePath.isMediaFile() && (showHidden || !it.name.startsWith('.')) &&
+ ((it.isImageFast() && filter and TYPE_IMAGES != 0) ||
+ (it.isVideoFast() && filter and TYPE_VIDEOS != 0) ||
+ (it.isGif() && filter and TYPE_GIFS != 0) ||
+ (it.isRawFast() && filter and TYPE_RAWS != 0) ||
+ (it.isSvg() && filter and TYPE_SVGS != 0))
+ }?.mapTo(itemsToDelete) { it.toFileDirItem(applicationContext) }
+ }
+
+ if (config.useRecycleBin) {
+ val pathsToDelete = ArrayList()
+ itemsToDelete.mapTo(pathsToDelete) { it.path }
+
+ movePathsInRecycleBin(pathsToDelete) {
+ if (it) {
+ deleteFilteredFileDirItems(itemsToDelete, folders)
+ } else {
+ toast(R.string.unknown_error_occurred)
+ }
+ }
+ } else {
+ deleteFilteredFileDirItems(itemsToDelete, folders)
+ }
+ }
+
+ private fun deleteFilteredFileDirItems(fileDirItems: ArrayList, folders: ArrayList) {
+ val OTGPath = config.OTGPath
+ deleteFiles(fileDirItems) {
+ runOnUiThread {
+ refreshItems()
+ }
+
+ ensureBackgroundThread {
+ folders.filter { !getDoesFilePathExist(it.absolutePath, OTGPath) }.forEach {
+ directoryDao.deleteDirPath(it.absolutePath)
+ }
+
+ if (config.deleteEmptyFolders) {
+ folders.filter { !it.absolutePath.isDownloadsFolder() && it.isDirectory && it.toFileDirItem(this).getProperFileCount(this, true) == 0 }.forEach {
+ tryDeleteFileDirItem(it.toFileDirItem(this), true, true)
+ }
+ }
+ }
+ }
+ }
+
+ private fun setupLayoutManager() {
+ if (config.viewTypeFolders == VIEW_TYPE_GRID) {
+ setupGridLayoutManager()
+ } else {
+ setupListLayoutManager()
+ }
+ }
+
+ private fun setupGridLayoutManager() {
+ val layoutManager = directories_grid.layoutManager as MyGridLayoutManager
+ (directories_grid.layoutParams as RelativeLayout.LayoutParams).apply {
+ topMargin = 0
+ bottomMargin = 0
+ }
+
+ if (config.scrollHorizontally) {
+ layoutManager.orientation = RecyclerView.HORIZONTAL
+ directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
+ } else {
+ layoutManager.orientation = RecyclerView.VERTICAL
+ directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+ }
+
+ layoutManager.spanCount = config.dirColumnCnt
+ }
+
+ private fun setupListLayoutManager() {
+ val layoutManager = directories_grid.layoutManager as MyGridLayoutManager
+ layoutManager.spanCount = 1
+ layoutManager.orientation = RecyclerView.VERTICAL
+ directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+
+ val smallMargin = resources.getDimension(R.dimen.small_margin).toInt()
+ (directories_grid.layoutParams as RelativeLayout.LayoutParams).apply {
+ topMargin = smallMargin
+ bottomMargin = smallMargin
+ }
+
+ mZoomListener = null
+ }
+
+ private fun measureRecyclerViewContent(directories: ArrayList) {
+ directories_grid.onGlobalLayout {
+ if (config.scrollHorizontally) {
+ calculateContentWidth(directories)
+ } else {
+ calculateContentHeight(directories)
+ }
+ }
+ }
+
+ private fun calculateContentWidth(directories: ArrayList) {
+ val layoutManager = directories_grid.layoutManager as MyGridLayoutManager
+
+ val fullWidth = if (config.folderStyle == FOLDER_STYLE_SQUARE) {
+ val thumbnailWidth = layoutManager.getChildAt(0)?.width ?: 0
+ ((directories.size - 1) / layoutManager.spanCount + 1) * thumbnailWidth
+ } else {
+ val thumbnailWidth = (layoutManager.getChildAt(0)?.width ?: 0) + resources.getDimension(R.dimen.medium_margin).toInt() * 2
+ val columnCount = (directories.size - 1) / layoutManager.spanCount + 1
+ columnCount * thumbnailWidth
+ }
+
+ directories_horizontal_fastscroller.setContentWidth(fullWidth)
+ directories_horizontal_fastscroller.setScrollToX(directories_grid.computeHorizontalScrollOffset())
+ }
+
+ private fun calculateContentHeight(directories: ArrayList) {
+ val layoutManager = directories_grid.layoutManager as MyGridLayoutManager
+
+ val fullHeight = if (config.folderStyle == FOLDER_STYLE_SQUARE) {
+ val thumbnailHeight = layoutManager.getChildAt(0)?.height ?: 0
+ ((directories.size - 1) / layoutManager.spanCount + 1) * thumbnailHeight
+ } else {
+ var thumbnailHeight = (layoutManager.getChildAt(0)?.height ?: 0)
+ if (config.viewTypeFolders == VIEW_TYPE_GRID) {
+ thumbnailHeight += resources.getDimension(R.dimen.medium_margin).toInt() * 2
+ }
+
+ val rowCount = (directories.size - 1) / layoutManager.spanCount + 1
+ rowCount * thumbnailHeight
+ }
+
+ directories_vertical_fastscroller.setContentHeight(fullHeight)
+ directories_vertical_fastscroller.setScrollToY(directories_grid.computeVerticalScrollOffset())
+ }
+
+ private fun initZoomListener() {
+ if (config.viewTypeFolders == VIEW_TYPE_GRID) {
+ val layoutManager = directories_grid.layoutManager as MyGridLayoutManager
+ mZoomListener = object : MyRecyclerView.MyZoomListener {
+ override fun zoomIn() {
+ if (layoutManager.spanCount > 1) {
+ reduceColumnCount()
+ getRecyclerAdapter()?.finishActMode()
+ }
+ }
+
+ override fun zoomOut() {
+ if (layoutManager.spanCount < MAX_COLUMN_COUNT) {
+ increaseColumnCount()
+ getRecyclerAdapter()?.finishActMode()
+ }
+ }
+ }
+ } else {
+ mZoomListener = null
+ }
+ }
+
+ private fun toggleRecycleBin(show: Boolean) {
+ config.showRecycleBinAtFolders = show
+ invalidateOptionsMenu()
+ ensureBackgroundThread {
+ var dirs = getCurrentlyDisplayedDirs()
+ if (!show) {
+ dirs = dirs.filter { it.path != RECYCLE_BIN } as ArrayList
+ }
+ gotDirectories(dirs)
+ }
+ }
+
+ private fun createNewFolder() {
+ FilePickerDialog(this, internalStoragePath, false, config.shouldShowHidden, false, true) {
+ CreateNewFolderDialog(this, it) {
+ config.tempFolderPath = it
+ ensureBackgroundThread {
+ gotDirectories(addTempFolderIfNeeded(getCurrentlyDisplayedDirs()))
+ }
+ }
+ }
+ }
+
+ private fun increaseColumnCount() {
+ config.dirColumnCnt = ++(directories_grid.layoutManager as MyGridLayoutManager).spanCount
+ columnCountChanged()
+ }
+
+ private fun reduceColumnCount() {
+ config.dirColumnCnt = --(directories_grid.layoutManager as MyGridLayoutManager).spanCount
+ columnCountChanged()
+ }
+
+ private fun columnCountChanged() {
+ invalidateOptionsMenu()
+ getRecyclerAdapter()?.apply {
+ notifyItemRangeChanged(0, dirs.size)
+ measureRecyclerViewContent(dirs)
+ }
+ }
+
+ private fun isPickImageIntent(intent: Intent) = isPickIntent(intent) && (hasImageContentData(intent) || isImageType(intent))
+
+ private fun isPickVideoIntent(intent: Intent) = isPickIntent(intent) && (hasVideoContentData(intent) || isVideoType(intent))
+
+ private fun isPickIntent(intent: Intent) = intent.action == Intent.ACTION_PICK
+
+ private fun isGetContentIntent(intent: Intent) = intent.action == Intent.ACTION_GET_CONTENT && intent.type != null
+
+ private fun isGetImageContentIntent(intent: Intent) = isGetContentIntent(intent) &&
+ (intent.type!!.startsWith("image/") || intent.type == Images.Media.CONTENT_TYPE)
+
+ private fun isGetVideoContentIntent(intent: Intent) = isGetContentIntent(intent) &&
+ (intent.type!!.startsWith("video/") || intent.type == Video.Media.CONTENT_TYPE)
+
+ private fun isGetAnyContentIntent(intent: Intent) = isGetContentIntent(intent) && intent.type == "*/*"
+
+ private fun isSetWallpaperIntent(intent: Intent?) = intent?.action == Intent.ACTION_SET_WALLPAPER
+
+ private fun hasImageContentData(intent: Intent) = (intent.data == Images.Media.EXTERNAL_CONTENT_URI ||
+ intent.data == Images.Media.INTERNAL_CONTENT_URI)
+
+ private fun hasVideoContentData(intent: Intent) = (intent.data == Video.Media.EXTERNAL_CONTENT_URI ||
+ intent.data == Video.Media.INTERNAL_CONTENT_URI)
+
+ private fun isImageType(intent: Intent) = (intent.type?.startsWith("image/") == true || intent.type == Images.Media.CONTENT_TYPE)
+
+ private fun isVideoType(intent: Intent) = (intent.type?.startsWith("video/") == true || intent.type == Video.Media.CONTENT_TYPE)
+
+ override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
+ if (resultCode == Activity.RESULT_OK) {
+ if (requestCode == PICK_MEDIA && resultData != null) {
+ val resultIntent = Intent()
+ var resultUri: Uri? = null
+ if (mIsThirdPartyIntent) {
+ when {
+ intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true && intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0 -> {
+ resultUri = fillExtraOutput(resultData)
+ }
+ resultData.extras?.containsKey(PICKED_PATHS) == true -> fillPickedPaths(resultData, resultIntent)
+ else -> fillIntentPath(resultData, resultIntent)
+ }
+ }
+
+ if (resultUri != null) {
+ resultIntent.data = resultUri
+ resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+
+ setResult(Activity.RESULT_OK, resultIntent)
+ finish()
+ } else if (requestCode == PICK_WALLPAPER) {
+ setResult(Activity.RESULT_OK)
+ finish()
+ }
+ }
+ super.onActivityResult(requestCode, resultCode, resultData)
+ }
+
+ private fun fillExtraOutput(resultData: Intent): Uri? {
+ val file = File(resultData.data!!.path!!)
+ var inputStream: InputStream? = null
+ var outputStream: OutputStream? = null
+ try {
+ val output = intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri
+ inputStream = FileInputStream(file)
+ outputStream = contentResolver.openOutputStream(output)
+ inputStream.copyTo(outputStream!!)
+ } catch (e: SecurityException) {
+ showErrorToast(e)
+ } catch (ignored: FileNotFoundException) {
+ return getFilePublicUri(file, BuildConfig.APPLICATION_ID)
+ } finally {
+ inputStream?.close()
+ outputStream?.close()
+ }
+
+ return null
+ }
+
+ private fun fillPickedPaths(resultData: Intent, resultIntent: Intent) {
+ val paths = resultData.extras!!.getStringArrayList(PICKED_PATHS)
+ val uris = paths!!.map { getFilePublicUri(File(it), BuildConfig.APPLICATION_ID) } as ArrayList
+ val clipData = ClipData("Attachment", arrayOf("image/*", "video/*"), ClipData.Item(uris.removeAt(0)))
+
+ uris.forEach {
+ clipData.addItem(ClipData.Item(it))
+ }
+
+ resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ resultIntent.clipData = clipData
+ }
+
+ private fun fillIntentPath(resultData: Intent, resultIntent: Intent) {
+ val data = resultData.data
+ val path = if (data.toString().startsWith("/")) data.toString() else data!!.path
+ val uri = getFilePublicUri(File(path!!), BuildConfig.APPLICATION_ID)
+ val type = path.getMimeType()
+ resultIntent.setDataAndTypeAndNormalize(uri, type)
+ resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+
+ private fun itemClicked(path: String) {
+ handleLockedFolderOpening(path) { success ->
+ if (success) {
+ Intent(this, MediaActivity::class.java).apply {
+ putExtra(SKIP_AUTHENTICATION, true)
+ putExtra(DIRECTORY, path)
+ handleMediaIntent(this)
+ }
+ }
+ }
+ }
+
+ private fun handleMediaIntent(intent: Intent) {
+ intent.apply {
+ if (mIsSetWallpaperIntent) {
+ putExtra(SET_WALLPAPER_INTENT, true)
+ startActivityForResult(this, PICK_WALLPAPER)
+ } else {
+ putExtra(GET_IMAGE_INTENT, mIsPickImageIntent || mIsGetImageContentIntent)
+ putExtra(GET_VIDEO_INTENT, mIsPickVideoIntent || mIsGetVideoContentIntent)
+ putExtra(GET_ANY_INTENT, mIsGetAnyContentIntent)
+ putExtra(Intent.EXTRA_ALLOW_MULTIPLE, mAllowPickingMultiple)
+ startActivityForResult(this, PICK_MEDIA)
+ }
+ }
+ }
+
+ private fun gotDirectories(newDirs: ArrayList) {
+ mIsGettingDirs = false
+ mShouldStopFetching = false
+
+ // if hidden item showing is disabled but all Favorite items are hidden, hide the Favorites folder
+ if (!config.shouldShowHidden) {
+ val favoritesFolder = newDirs.firstOrNull { it.areFavorites() }
+ if (favoritesFolder != null && favoritesFolder.tmb.getFilenameFromPath().startsWith('.')) {
+ newDirs.remove(favoritesFolder)
+ }
+ }
+
+ val dirs = getSortedDirectories(newDirs)
+ if (config.groupDirectSubfolders) {
+ mDirs = dirs.clone() as ArrayList
+ }
+
+ var isPlaceholderVisible = dirs.isEmpty()
+
+ runOnUiThread {
+ checkPlaceholderVisibility(dirs)
+
+ val allowHorizontalScroll = config.scrollHorizontally && config.viewTypeFolders == VIEW_TYPE_GRID
+ directories_vertical_fastscroller.beVisibleIf(directories_grid.isVisible() && !allowHorizontalScroll)
+ directories_horizontal_fastscroller.beVisibleIf(directories_grid.isVisible() && allowHorizontalScroll)
+ setupAdapter(dirs.clone() as ArrayList)
+ }
+
+ // cached folders have been loaded, recheck folders one by one starting with the first displayed
+ mLastMediaFetcher?.shouldStop = true
+ mLastMediaFetcher = MediaFetcher(applicationContext)
+ val getImagesOnly = mIsPickImageIntent || mIsGetImageContentIntent
+ val getVideosOnly = mIsPickVideoIntent || mIsGetVideoContentIntent
+ val hiddenString = getString(R.string.hidden)
+ val albumCovers = config.parseAlbumCovers()
+ val includedFolders = config.includedFolders
+ val noMediaFolders = getNoMediaFoldersSync()
+ val tempFolderPath = config.tempFolderPath
+ val getProperFileSize = config.directorySorting and SORT_BY_SIZE != 0
+ val favoritePaths = getFavoritePaths()
+ val dirPathsToRemove = ArrayList()
+ val lastModifieds = mLastMediaFetcher!!.getLastModifieds()
+ val dateTakens = mLastMediaFetcher!!.getDateTakens()
+
+ try {
+ for (directory in dirs) {
+ if (mShouldStopFetching || isDestroyed || isFinishing) {
+ return
+ }
+
+ val sorting = config.getFolderSorting(directory.path)
+ val grouping = config.getFolderGrouping(directory.path)
+ val getProperDateTaken = config.directorySorting and SORT_BY_DATE_TAKEN != 0 ||
+ sorting and SORT_BY_DATE_TAKEN != 0 ||
+ grouping and GROUP_BY_DATE_TAKEN_DAILY != 0 ||
+ grouping and GROUP_BY_DATE_TAKEN_MONTHLY != 0
+
+ val getProperLastModified = config.directorySorting and SORT_BY_DATE_MODIFIED != 0 ||
+ sorting and SORT_BY_DATE_MODIFIED != 0 ||
+ grouping and GROUP_BY_LAST_MODIFIED_DAILY != 0 ||
+ grouping and GROUP_BY_LAST_MODIFIED_MONTHLY != 0
+
+ val curMedia = mLastMediaFetcher!!.getFilesFrom(directory.path, getImagesOnly, getVideosOnly, getProperDateTaken, getProperLastModified,
+ getProperFileSize, favoritePaths, false, lastModifieds, dateTakens)
+
+ val newDir = if (curMedia.isEmpty()) {
+ if (directory.path != tempFolderPath) {
+ dirPathsToRemove.add(directory.path)
+ }
+ directory
+ } else {
+ createDirectoryFromMedia(directory.path, curMedia, albumCovers, hiddenString, includedFolders, getProperFileSize, noMediaFolders)
+ }
+
+ // we are looping through the already displayed folders looking for changes, do not do anything if nothing changed
+ if (directory.copy(subfoldersCount = 0, subfoldersMediaCount = 0) == newDir) {
+ continue
+ }
+
+ directory.apply {
+ tmb = newDir.tmb
+ name = newDir.name
+ mediaCnt = newDir.mediaCnt
+ modified = newDir.modified
+ taken = newDir.taken
+ this@apply.size = newDir.size
+ types = newDir.types
+ sortValue = getDirectorySortingValue(curMedia, path, name, size)
+ }
+
+ setupAdapter(dirs)
+
+ // update directories and media files in the local db, delete invalid items. Intentionally creating a new thread
+ updateDBDirectory(directory)
+ if (!directory.isRecycleBin()) {
+ Thread {
+ try {
+ mediaDB.insertAll(curMedia)
+ } catch (ignored: Exception) {
+ }
+ }.start()
+ }
+
+ if (!directory.isRecycleBin()) {
+ getCachedMedia(directory.path, getVideosOnly, getImagesOnly) {
+ val mediaToDelete = ArrayList()
+ it.forEach {
+ if (!curMedia.contains(it)) {
+ val medium = it as? Medium
+ val path = medium?.path
+ if (path != null) {
+ mediaToDelete.add(medium)
+ }
+ }
+ }
+ mediaDB.deleteMedia(*mediaToDelete.toTypedArray())
+ }
+ }
+ }
+
+ if (dirPathsToRemove.isNotEmpty()) {
+ val dirsToRemove = dirs.filter { dirPathsToRemove.contains(it.path) }
+ dirsToRemove.forEach {
+ directoryDao.deleteDirPath(it.path)
+ }
+ dirs.removeAll(dirsToRemove)
+ setupAdapter(dirs)
+ }
+ } catch (ignored: Exception) {
+ }
+
+ val foldersToScan = mLastMediaFetcher!!.getFoldersToScan()
+ foldersToScan.add(FAVORITES)
+ if (config.showRecycleBinAtFolders) {
+ foldersToScan.add(RECYCLE_BIN)
+ } else {
+ foldersToScan.remove(RECYCLE_BIN)
+ }
+
+ dirs.forEach {
+ foldersToScan.remove(it.path)
+ }
+
+ // check the remaining folders which were not cached at all yet
+ for (folder in foldersToScan) {
+ if (mShouldStopFetching || isDestroyed || isFinishing) {
+ return
+ }
+
+ val sorting = config.getFolderSorting(folder)
+ val grouping = config.getFolderGrouping(folder)
+ val getProperDateTaken = config.directorySorting and SORT_BY_DATE_TAKEN != 0 ||
+ sorting and SORT_BY_DATE_TAKEN != 0 ||
+ grouping and GROUP_BY_DATE_TAKEN_DAILY != 0 ||
+ grouping and GROUP_BY_DATE_TAKEN_MONTHLY != 0
+
+ val getProperLastModified = config.directorySorting and SORT_BY_DATE_MODIFIED != 0 ||
+ sorting and SORT_BY_DATE_MODIFIED != 0 ||
+ grouping and GROUP_BY_LAST_MODIFIED_DAILY != 0 ||
+ grouping and GROUP_BY_LAST_MODIFIED_MONTHLY != 0
+
+ val newMedia = mLastMediaFetcher!!.getFilesFrom(folder, getImagesOnly, getVideosOnly, getProperDateTaken, getProperLastModified,
+ getProperFileSize, favoritePaths, false, lastModifieds, dateTakens)
+
+ if (newMedia.isEmpty()) {
+ continue
+ }
+
+ if (isPlaceholderVisible) {
+ isPlaceholderVisible = false
+ runOnUiThread {
+ directories_empty_placeholder.beGone()
+ directories_empty_placeholder_2.beGone()
+ directories_grid.beVisible()
+ }
+ }
+
+ val newDir = createDirectoryFromMedia(folder, newMedia, albumCovers, hiddenString, includedFolders, getProperFileSize, noMediaFolders)
+ dirs.add(newDir)
+ setupAdapter(dirs)
+
+ // make sure to create a new thread for these operations, dont just use the common bg thread
+ Thread {
+ try {
+ directoryDao.insert(newDir)
+ if (folder != RECYCLE_BIN) {
+ mediaDB.insertAll(newMedia)
+ }
+ } catch (ignored: Exception) {
+ }
+ }.start()
+ }
+
+ mLoadedInitialPhotos = true
+ checkLastMediaChanged()
+
+ runOnUiThread {
+ directories_refresh_layout.isRefreshing = false
+ checkPlaceholderVisibility(dirs)
+ }
+
+ checkInvalidDirectories(dirs)
+ if (mDirs.size > 50) {
+ excludeSpamFolders()
+ }
+
+ val excludedFolders = config.excludedFolders
+ val everShownFolders = config.everShownFolders.toMutableSet() as HashSet
+
+ // do not add excluded folders and their subfolders at everShownFolders
+ dirs.filter { dir ->
+ if (excludedFolders.any { dir.path.startsWith(it) }) {
+ return@filter false
+ }
+ return@filter true
+ }.mapTo(everShownFolders) { it.path }
+
+ try {
+ // scan the internal storage from time to time for new folders
+ if (config.appRunCount == 1 || config.appRunCount % 30 == 0) {
+ everShownFolders.addAll(getFoldersWithMedia(config.internalStoragePath))
+ }
+
+ // catch some extreme exceptions like too many everShownFolders for storing, shouldnt really happen
+ config.everShownFolders = everShownFolders
+ } catch (e: Exception) {
+ config.everShownFolders = HashSet()
+ }
+
+ mDirs = dirs.clone() as ArrayList
+ }
+
+ private fun setAsDefaultFolder() {
+ config.defaultFolder = ""
+ invalidateOptionsMenu()
+ }
+
+ private fun openDefaultFolder() {
+ if (config.defaultFolder.isEmpty()) {
+ return
+ }
+
+ val defaultDir = File(config.defaultFolder)
+
+ if ((!defaultDir.exists() || !defaultDir.isDirectory) && (config.defaultFolder != RECYCLE_BIN && config.defaultFolder != FAVORITES)) {
+ config.defaultFolder = ""
+ return
+ }
+
+ Intent(this, MediaActivity::class.java).apply {
+ putExtra(DIRECTORY, config.defaultFolder)
+ handleMediaIntent(this)
+ }
+ }
+
+ private fun checkPlaceholderVisibility(dirs: ArrayList) {
+ directories_empty_placeholder.beVisibleIf(dirs.isEmpty() && mLoadedInitialPhotos)
+ directories_empty_placeholder_2.beVisibleIf(dirs.isEmpty() && mLoadedInitialPhotos)
+
+ if (mIsSearchOpen) {
+ directories_empty_placeholder.text = getString(R.string.no_items_found)
+ directories_empty_placeholder_2.beGone()
+ } else if (dirs.isEmpty() && config.filterMedia == getDefaultFileFilter()) {
+ directories_empty_placeholder.text = getString(R.string.no_media_add_included)
+ directories_empty_placeholder_2.text = getString(R.string.add_folder)
+
+ directories_empty_placeholder_2.setOnClickListener {
+ showAddIncludedFolderDialog {
+ refreshItems()
+ }
+ }
+ } else {
+ directories_empty_placeholder.text = getString(R.string.no_media_with_filters)
+ directories_empty_placeholder_2.text = getString(R.string.change_filters_underlined)
+
+ directories_empty_placeholder_2.setOnClickListener {
+ showFilterMediaDialog()
+ }
+ }
+
+ directories_empty_placeholder_2.underlineText()
+ directories_grid.beVisibleIf(directories_empty_placeholder.isGone())
+ }
+
+ private fun setupAdapter(dirs: ArrayList, textToSearch: String = "", forceRecreate: Boolean = false) {
+ val currAdapter = directories_grid.adapter
+ val distinctDirs = dirs.distinctBy { it.path.getDistinctPath() }.toMutableList() as ArrayList
+ val sortedDirs = getSortedDirectories(distinctDirs)
+ var dirsToShow = getDirsToShow(sortedDirs, mDirs, mCurrentPathPrefix).clone() as ArrayList
+
+ if (currAdapter == null || forceRecreate) {
+ initZoomListener()
+ val fastscroller = if (config.scrollHorizontally) directories_horizontal_fastscroller else directories_vertical_fastscroller
+ DirectoryAdapter(this, dirsToShow, this, directories_grid, isPickIntent(intent) || isGetAnyContentIntent(intent), fastscroller) {
+ val clickedDir = it as Directory
+ val path = clickedDir.path
+ if (clickedDir.subfoldersCount == 1 || !config.groupDirectSubfolders) {
+ if (path != config.tempFolderPath) {
+ itemClicked(path)
+ }
+ } else {
+ mCurrentPathPrefix = path
+ mOpenedSubfolders.add(path)
+ setupAdapter(mDirs, "")
+ }
+ }.apply {
+ setupZoomListener(mZoomListener)
+ runOnUiThread {
+ directories_grid.adapter = this
+ setupScrollDirection()
+ }
+ }
+ measureRecyclerViewContent(dirsToShow)
+ } else {
+ runOnUiThread {
+ if (textToSearch.isNotEmpty()) {
+ dirsToShow = dirsToShow.filter { it.name.contains(textToSearch, true) }.sortedBy { !it.name.startsWith(textToSearch, true) }.toMutableList() as ArrayList
+ }
+ checkPlaceholderVisibility(dirsToShow)
+
+ (directories_grid.adapter as? DirectoryAdapter)?.updateDirs(dirsToShow)
+ measureRecyclerViewContent(dirsToShow)
+ }
+ }
+
+ // recyclerview sometimes becomes empty at init/update, triggering an invisible refresh like this seems to work fine
+ directories_grid.postDelayed({
+ directories_grid.scrollBy(0, 0)
+ }, 500)
+ }
+
+ private fun setupScrollDirection() {
+ val allowHorizontalScroll = config.scrollHorizontally && config.viewTypeFolders == VIEW_TYPE_GRID
+ directories_vertical_fastscroller.isHorizontal = false
+ directories_vertical_fastscroller.beGoneIf(allowHorizontalScroll)
+
+ directories_horizontal_fastscroller.isHorizontal = true
+ directories_horizontal_fastscroller.beVisibleIf(allowHorizontalScroll)
+
+ if (allowHorizontalScroll) {
+ directories_horizontal_fastscroller.setViews(directories_grid, directories_refresh_layout) {
+ directories_horizontal_fastscroller.updateBubbleText(getBubbleTextItem(it))
+ }
+ } else {
+ directories_vertical_fastscroller.setViews(directories_grid, directories_refresh_layout) {
+ directories_vertical_fastscroller.updateBubbleText(getBubbleTextItem(it))
+ }
+ }
+ }
+
+ private fun checkInvalidDirectories(dirs: ArrayList) {
+ val invalidDirs = ArrayList()
+ val OTGPath = config.OTGPath
+ dirs.filter { !it.areFavorites() && !it.isRecycleBin() }.forEach {
+ if (!getDoesFilePathExist(it.path, OTGPath)) {
+ invalidDirs.add(it)
+ } else if (it.path != config.tempFolderPath) {
+ val children = if (isPathOnOTG(it.path)) getOTGFolderChildrenNames(it.path) else File(it.path).list()?.asList()
+ val hasMediaFile = children?.any {
+ it != null && (it.isMediaFile() || (it.startsWith("img_", true) && File(it).isDirectory))
+ } ?: false
+
+ if (!hasMediaFile) {
+ invalidDirs.add(it)
+ }
+ }
+ }
+
+ if (getFavoritePaths().isEmpty()) {
+ val favoritesFolder = dirs.firstOrNull { it.areFavorites() }
+ if (favoritesFolder != null) {
+ invalidDirs.add(favoritesFolder)
+ }
+ }
+
+ if (config.useRecycleBin) {
+ try {
+ val binFolder = dirs.firstOrNull { it.path == RECYCLE_BIN }
+ if (binFolder != null && mediaDB.getDeletedMedia().isEmpty()) {
+ invalidDirs.add(binFolder)
+ }
+ } catch (ignored: Exception) {
+ }
+ }
+
+ if (invalidDirs.isNotEmpty()) {
+ dirs.removeAll(invalidDirs)
+ setupAdapter(dirs)
+ invalidDirs.forEach {
+ try {
+ directoryDao.deleteDirPath(it.path)
+ } catch (ignored: Exception) {
+ }
+ }
+ }
+ }
+
+ private fun getCurrentlyDisplayedDirs() = getRecyclerAdapter()?.dirs ?: ArrayList()
+
+ private fun getBubbleTextItem(index: Int) = getRecyclerAdapter()?.dirs?.getOrNull(index)?.getBubbleText(config.directorySorting, this, mDateFormat, mTimeFormat)
+ ?: ""
+
+ private fun setupLatestMediaId() {
+ ensureBackgroundThread {
+ if (hasPermission(PERMISSION_READ_STORAGE)) {
+ mLatestMediaId = getLatestMediaId()
+ mLatestMediaDateId = getLatestMediaByDateId()
+ }
+ }
+ }
+
+ private fun checkLastMediaChanged() {
+ if (isDestroyed) {
+ return
+ }
+
+ mLastMediaHandler.postDelayed({
+ ensureBackgroundThread {
+ val mediaId = getLatestMediaId()
+ val mediaDateId = getLatestMediaByDateId()
+ if (mLatestMediaId != mediaId || mLatestMediaDateId != mediaDateId) {
+ mLatestMediaId = mediaId
+ mLatestMediaDateId = mediaDateId
+ runOnUiThread {
+ getDirectories()
+ }
+ } else {
+ mLastMediaHandler.removeCallbacksAndMessages(null)
+ checkLastMediaChanged()
+ }
+ }
+ }, LAST_MEDIA_CHECK_PERIOD)
+ }
+
+ private fun checkRecycleBinItems() {
+ if (config.useRecycleBin && config.lastBinCheck < System.currentTimeMillis() - DAY_SECONDS * 1000) {
+ config.lastBinCheck = System.currentTimeMillis()
+ Handler().postDelayed({
+ ensureBackgroundThread {
+ try {
+ mediaDB.deleteOldRecycleBinItems(System.currentTimeMillis() - MONTH_MILLISECONDS)
+ } catch (e: Exception) {
+ }
+ }
+ }, 3000L)
+ }
+ }
+
+ // exclude probably unwanted folders, for example facebook stickers are split between hundreds of separate folders like
+ // /storage/emulated/0/Android/data/com.facebook.orca/files/stickers/175139712676531/209575122566323
+ // /storage/emulated/0/Android/data/com.facebook.orca/files/stickers/497837993632037/499671223448714
+ private fun excludeSpamFolders() {
+ ensureBackgroundThread {
+ try {
+ val internalPath = internalStoragePath
+ val checkedPaths = ArrayList()
+ val oftenRepeatedPaths = ArrayList()
+ val paths = mDirs.map { it.path.removePrefix(internalPath) }.toMutableList() as ArrayList
+ paths.forEach {
+ val parts = it.split("/")
+ var currentString = ""
+ for (i in 0 until parts.size) {
+ currentString += "${parts[i]}/"
+
+ if (!checkedPaths.contains(currentString)) {
+ val cnt = paths.count { it.startsWith(currentString) }
+ if (cnt > 50 && currentString.startsWith("/Android/data", true)) {
+ oftenRepeatedPaths.add(currentString)
+ }
+ }
+
+ checkedPaths.add(currentString)
+ }
+ }
+
+ val substringToRemove = oftenRepeatedPaths.filter {
+ val path = it
+ it == "/" || oftenRepeatedPaths.any { it != path && it.startsWith(path) }
+ }
+
+ oftenRepeatedPaths.removeAll(substringToRemove)
+ val OTGPath = config.OTGPath
+ oftenRepeatedPaths.forEach {
+ val file = File("$internalPath/$it")
+ if (getDoesFilePathExist(file.absolutePath, OTGPath)) {
+ config.addExcludedFolder(file.absolutePath)
+ }
+ }
+ } catch (e: Exception) {
+ }
+ }
+ }
+
+ private fun getFoldersWithMedia(path: String): HashSet {
+ val folders = HashSet()
+ try {
+ val files = File(path).listFiles()
+ if (files != null) {
+ files.sortBy { !it.isDirectory }
+ for (file in files) {
+ if (file.isDirectory && !file.startsWith("${config.internalStoragePath}/Android")) {
+ folders.addAll(getFoldersWithMedia(file.absolutePath))
+ } else if (file.isFile && file.isMediaFile()) {
+ folders.add(file.parent ?: "")
+ break
+ }
+ }
+ }
+ } catch (ignored: Exception) {
+ }
+
+ return folders
+ }
+
+ override fun refreshItems() {
+ getDirectories()
+ }
+
+ override fun recheckPinnedFolders() {
+ ensureBackgroundThread {
+ gotDirectories(movePinnedDirectoriesToFront(getCurrentlyDisplayedDirs()))
+ }
+ }
+
+ override fun updateDirectories(directories: ArrayList) {
+ ensureBackgroundThread {
+ storeDirectoryItems(directories)
+ removeInvalidDBDirectories()
+ }
+ }
+
+ private fun checkWhatsNewDialog() {
+ arrayListOf().apply {
+ add(Release(213, R.string.release_213))
+ add(Release(217, R.string.release_217))
+ add(Release(220, R.string.release_220))
+ add(Release(221, R.string.release_221))
+ add(Release(225, R.string.release_225))
+ add(Release(258, R.string.release_258))
+ add(Release(277, R.string.release_277))
+ add(Release(295, R.string.release_295))
+ add(Release(327, R.string.release_327))
+ checkWhatsNew(this, BuildConfig.VERSION_CODE)
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/MediaActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/MediaActivity.kt
new file mode 100644
index 000000000..731ac3e6d
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/MediaActivity.kt
@@ -0,0 +1,1019 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.app.Activity
+import android.app.SearchManager
+import android.app.WallpaperManager
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.net.Uri
+import android.os.Bundle
+import android.os.Handler
+import android.view.Menu
+import android.view.MenuItem
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import android.widget.RelativeLayout
+import androidx.appcompat.widget.SearchView
+import androidx.core.view.MenuItemCompat
+import androidx.recyclerview.widget.GridLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.bumptech.glide.Glide
+import com.bumptech.glide.request.RequestOptions
+import com.bumptech.glide.request.target.SimpleTarget
+import com.bumptech.glide.request.transition.Transition
+import com.simplemobiletools.commons.dialogs.CreateNewFolderDialog
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.*
+import com.simplemobiletools.commons.models.FileDirItem
+import com.simplemobiletools.commons.views.MyGridLayoutManager
+import com.simplemobiletools.commons.views.MyRecyclerView
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.MediaAdapter
+import com.simplemobiletools.gallery.pro.asynctasks.GetMediaAsynctask
+import com.simplemobiletools.gallery.pro.databases.GalleryDatabase
+import com.simplemobiletools.gallery.pro.dialogs.ChangeGroupingDialog
+import com.simplemobiletools.gallery.pro.dialogs.ChangeSortingDialog
+import com.simplemobiletools.gallery.pro.dialogs.ChangeViewTypeDialog
+import com.simplemobiletools.gallery.pro.dialogs.FilterMediaDialog
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.interfaces.MediaOperationsListener
+import com.simplemobiletools.gallery.pro.models.Medium
+import com.simplemobiletools.gallery.pro.models.ThumbnailItem
+import com.simplemobiletools.gallery.pro.models.ThumbnailSection
+import kotlinx.android.synthetic.main.activity_media.*
+import java.io.File
+import java.io.IOException
+import java.util.*
+import kotlin.collections.ArrayList
+
+class MediaActivity : SimpleActivity(), MediaOperationsListener {
+ private val LAST_MEDIA_CHECK_PERIOD = 3000L
+
+ private var mPath = ""
+ private var mIsGetImageIntent = false
+ private var mIsGetVideoIntent = false
+ private var mIsGetAnyIntent = false
+ private var mIsGettingMedia = false
+ private var mAllowPickingMultiple = false
+ private var mShowAll = false
+ private var mLoadedInitialPhotos = false
+ private var mIsSearchOpen = false
+ private var mLastSearchedText = ""
+ private var mDateFormat = ""
+ private var mTimeFormat = ""
+ private var mLatestMediaId = 0L
+ private var mLatestMediaDateId = 0L
+ private var mLastMediaHandler = Handler()
+ private var mTempShowHiddenHandler = Handler()
+ private var mCurrAsyncTask: GetMediaAsynctask? = null
+ private var mZoomListener: MyRecyclerView.MyZoomListener? = null
+ private var mSearchMenuItem: MenuItem? = null
+
+ private var mStoredAnimateGifs = true
+ private var mStoredCropThumbnails = true
+ private var mStoredScrollHorizontally = true
+ private var mStoredShowFileTypes = true
+ private var mStoredRoundedCorners = false
+ private var mStoredTextColor = 0
+ private var mStoredPrimaryColor = 0
+ private var mStoredThumbnailSpacing = 0
+
+ companion object {
+ var mMedia = ArrayList()
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_media)
+
+ intent.apply {
+ mIsGetImageIntent = getBooleanExtra(GET_IMAGE_INTENT, false)
+ mIsGetVideoIntent = getBooleanExtra(GET_VIDEO_INTENT, false)
+ mIsGetAnyIntent = getBooleanExtra(GET_ANY_INTENT, false)
+ mAllowPickingMultiple = getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
+ }
+
+ media_refresh_layout.setOnRefreshListener { getMedia() }
+ try {
+ mPath = intent.getStringExtra(DIRECTORY)
+ } catch (e: Exception) {
+ showErrorToast(e)
+ finish()
+ return
+ }
+
+ storeStateVariables()
+
+ if (mShowAll) {
+ supportActionBar?.setDisplayHomeAsUpEnabled(false)
+ registerFileUpdateListener()
+ }
+
+ media_empty_text_placeholder_2.setOnClickListener {
+ showFilterMediaDialog()
+ }
+
+ updateWidgets()
+ }
+
+ override fun onStart() {
+ super.onStart()
+ mTempShowHiddenHandler.removeCallbacksAndMessages(null)
+ }
+
+ override fun onResume() {
+ super.onResume()
+ mDateFormat = config.dateFormat
+ mTimeFormat = getTimeFormat()
+
+ if (mStoredAnimateGifs != config.animateGifs) {
+ getMediaAdapter()?.updateAnimateGifs(config.animateGifs)
+ }
+
+ if (mStoredCropThumbnails != config.cropThumbnails) {
+ getMediaAdapter()?.updateCropThumbnails(config.cropThumbnails)
+ }
+
+ if (mStoredScrollHorizontally != config.scrollHorizontally) {
+ mLoadedInitialPhotos = false
+ media_grid.adapter = null
+ getMedia()
+ }
+
+ if (mStoredShowFileTypes != config.showThumbnailFileTypes) {
+ getMediaAdapter()?.updateShowFileTypes(config.showThumbnailFileTypes)
+ }
+
+ if (mStoredTextColor != config.textColor) {
+ getMediaAdapter()?.updateTextColor(config.textColor)
+ }
+
+ if (mStoredPrimaryColor != config.primaryColor) {
+ getMediaAdapter()?.updatePrimaryColor(config.primaryColor)
+ media_horizontal_fastscroller.updatePrimaryColor()
+ media_vertical_fastscroller.updatePrimaryColor()
+ }
+
+ if (mStoredThumbnailSpacing != config.thumbnailSpacing) {
+ media_grid.adapter = null
+ setupAdapter()
+ }
+
+ if (mStoredRoundedCorners != config.fileRoundedCorners) {
+ media_grid.adapter = null
+ setupAdapter()
+ }
+
+ media_horizontal_fastscroller.updateBubbleColors()
+ media_vertical_fastscroller.updateBubbleColors()
+ media_refresh_layout.isEnabled = config.enablePullToRefresh
+ media_empty_text_placeholder.setTextColor(config.textColor)
+ media_empty_text_placeholder_2.setTextColor(getAdjustedPrimaryColor())
+
+ if (!mIsSearchOpen) {
+ invalidateOptionsMenu()
+ }
+
+ if (mMedia.isEmpty() || config.getFolderSorting(mPath) and SORT_BY_RANDOM == 0) {
+ if (shouldSkipAuthentication()) {
+ tryLoadGallery()
+ } else {
+ handleLockedFolderOpening(mPath) { success ->
+ if (success) {
+ tryLoadGallery()
+ } else {
+ finish()
+ }
+ }
+ }
+ }
+ }
+
+ override fun onPause() {
+ super.onPause()
+ mIsGettingMedia = false
+ media_refresh_layout.isRefreshing = false
+ storeStateVariables()
+ mLastMediaHandler.removeCallbacksAndMessages(null)
+
+ if (!mMedia.isEmpty()) {
+ mCurrAsyncTask?.stopFetching()
+ }
+ }
+
+ override fun onStop() {
+ super.onStop()
+
+ if (config.temporarilyShowHidden || config.tempSkipDeleteConfirmation) {
+ mTempShowHiddenHandler.postDelayed({
+ config.temporarilyShowHidden = false
+ config.tempSkipDeleteConfirmation = false
+ }, SHOW_TEMP_HIDDEN_DURATION)
+ } else {
+ mTempShowHiddenHandler.removeCallbacksAndMessages(null)
+ }
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ if (config.showAll && !isChangingConfigurations) {
+ config.temporarilyShowHidden = false
+ config.tempSkipDeleteConfirmation = false
+ unregisterFileUpdateListener()
+ GalleryDatabase.destroyInstance()
+ }
+
+ mTempShowHiddenHandler.removeCallbacksAndMessages(null)
+ mMedia.clear()
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_media, menu)
+
+ val isDefaultFolder = !config.defaultFolder.isEmpty() && File(config.defaultFolder).compareTo(File(mPath)) == 0
+
+ menu.apply {
+ findItem(R.id.group).isVisible = !config.scrollHorizontally
+
+ findItem(R.id.empty_recycle_bin).isVisible = mPath == RECYCLE_BIN
+ findItem(R.id.empty_disable_recycle_bin).isVisible = mPath == RECYCLE_BIN
+ findItem(R.id.restore_all_files).isVisible = mPath == RECYCLE_BIN
+
+ findItem(R.id.folder_view).isVisible = mShowAll
+ findItem(R.id.open_camera).isVisible = mShowAll
+ findItem(R.id.about).isVisible = mShowAll
+ findItem(R.id.create_new_folder).isVisible = !mShowAll && mPath != RECYCLE_BIN && mPath != FAVORITES
+
+ findItem(R.id.temporarily_show_hidden).isVisible = !config.shouldShowHidden
+ findItem(R.id.stop_showing_hidden).isVisible = config.temporarilyShowHidden
+
+ findItem(R.id.set_as_default_folder).isVisible = !isDefaultFolder
+ findItem(R.id.unset_as_default_folder).isVisible = isDefaultFolder
+
+ val viewType = config.getFolderViewType(if (mShowAll) SHOW_ALL else mPath)
+ findItem(R.id.increase_column_count).isVisible = viewType == VIEW_TYPE_GRID && config.mediaColumnCnt < MAX_COLUMN_COUNT
+ findItem(R.id.reduce_column_count).isVisible = viewType == VIEW_TYPE_GRID && config.mediaColumnCnt > 1
+ findItem(R.id.toggle_filename).isVisible = viewType == VIEW_TYPE_GRID
+ }
+
+ setupSearch(menu)
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.sort -> showSortingDialog()
+ R.id.filter -> showFilterMediaDialog()
+ R.id.empty_recycle_bin -> emptyRecycleBin()
+ R.id.empty_disable_recycle_bin -> emptyAndDisableRecycleBin()
+ R.id.restore_all_files -> restoreAllFiles()
+ R.id.toggle_filename -> toggleFilenameVisibility()
+ R.id.open_camera -> launchCamera()
+ R.id.folder_view -> switchToFolderView()
+ R.id.change_view_type -> changeViewType()
+ R.id.group -> showGroupByDialog()
+ R.id.create_new_folder -> createNewFolder()
+ R.id.temporarily_show_hidden -> tryToggleTemporarilyShowHidden()
+ R.id.stop_showing_hidden -> tryToggleTemporarilyShowHidden()
+ R.id.increase_column_count -> increaseColumnCount()
+ R.id.reduce_column_count -> reduceColumnCount()
+ R.id.set_as_default_folder -> setAsDefaultFolder()
+ R.id.unset_as_default_folder -> unsetAsDefaultFolder()
+ R.id.slideshow -> startSlideshow()
+ R.id.settings -> launchSettings()
+ R.id.about -> launchAbout()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ private fun startSlideshow() {
+ if (mMedia.isNotEmpty()) {
+ Intent(this, ViewPagerActivity::class.java).apply {
+ val item = mMedia.firstOrNull { it is Medium } as? Medium ?: return
+ putExtra(SKIP_AUTHENTICATION, shouldSkipAuthentication())
+ putExtra(PATH, item.path)
+ putExtra(SHOW_ALL, mShowAll)
+ putExtra(SLIDESHOW_START_ON_ENTER, true)
+ startActivity(this)
+ }
+ }
+ }
+
+ private fun storeStateVariables() {
+ config.apply {
+ mStoredAnimateGifs = animateGifs
+ mStoredCropThumbnails = cropThumbnails
+ mStoredScrollHorizontally = scrollHorizontally
+ mStoredShowFileTypes = showThumbnailFileTypes
+ mStoredTextColor = textColor
+ mStoredPrimaryColor = primaryColor
+ mStoredThumbnailSpacing = thumbnailSpacing
+ mStoredRoundedCorners = fileRoundedCorners
+ mShowAll = showAll
+ }
+ }
+
+ private fun setupSearch(menu: Menu) {
+ val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
+ mSearchMenuItem = menu.findItem(R.id.search)
+ (mSearchMenuItem?.actionView as? SearchView)?.apply {
+ setSearchableInfo(searchManager.getSearchableInfo(componentName))
+ isSubmitButtonEnabled = false
+ setOnQueryTextListener(object : SearchView.OnQueryTextListener {
+ override fun onQueryTextSubmit(query: String) = false
+
+ override fun onQueryTextChange(newText: String): Boolean {
+ if (mIsSearchOpen) {
+ mLastSearchedText = newText
+ searchQueryChanged(newText)
+ }
+ return true
+ }
+ })
+ }
+
+ MenuItemCompat.setOnActionExpandListener(mSearchMenuItem, object : MenuItemCompat.OnActionExpandListener {
+ override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
+ mIsSearchOpen = true
+ media_refresh_layout.isEnabled = false
+ return true
+ }
+
+ // this triggers on device rotation too, avoid doing anything
+ override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
+ if (mIsSearchOpen) {
+ mIsSearchOpen = false
+ mLastSearchedText = ""
+
+ media_refresh_layout.isEnabled = config.enablePullToRefresh
+ searchQueryChanged("")
+ }
+ return true
+ }
+ })
+ }
+
+ private fun searchQueryChanged(text: String) {
+ ensureBackgroundThread {
+ try {
+ val filtered = mMedia.filter { it is Medium && it.name.contains(text, true) } as ArrayList
+ filtered.sortBy { it is Medium && !it.name.startsWith(text, true) }
+ val grouped = MediaFetcher(applicationContext).groupMedia(filtered as ArrayList, mPath)
+ runOnUiThread {
+ if (grouped.isEmpty()) {
+ media_empty_text_placeholder.text = getString(R.string.no_items_found)
+ media_empty_text_placeholder.beVisible()
+ } else {
+ media_empty_text_placeholder.beGone()
+ }
+
+ handleGridSpacing(grouped)
+ getMediaAdapter()?.updateMedia(grouped)
+ measureRecyclerViewContent(grouped)
+ }
+ } catch (ignored: Exception) {
+ }
+ }
+ }
+
+ private fun tryLoadGallery() {
+ handlePermission(PERMISSION_WRITE_STORAGE) {
+ if (it) {
+ val dirName = when {
+ mPath == FAVORITES -> getString(R.string.favorites)
+ mPath == RECYCLE_BIN -> getString(R.string.recycle_bin)
+ mPath == config.OTGPath -> getString(R.string.usb)
+ else -> getHumanizedFilename(mPath)
+ }
+ updateActionBarTitle(if (mShowAll) resources.getString(R.string.all_folders) else dirName)
+ getMedia()
+ setupLayoutManager()
+ } else {
+ toast(R.string.no_storage_permissions)
+ finish()
+ }
+ }
+ }
+
+ private fun getMediaAdapter() = media_grid.adapter as? MediaAdapter
+
+ private fun setupAdapter() {
+ if (!mShowAll && isDirEmpty()) {
+ return
+ }
+
+ val currAdapter = media_grid.adapter
+ if (currAdapter == null) {
+ initZoomListener()
+ val fastscroller = if (config.scrollHorizontally) media_horizontal_fastscroller else media_vertical_fastscroller
+ MediaAdapter(this, mMedia.clone() as ArrayList, this, mIsGetImageIntent || mIsGetVideoIntent || mIsGetAnyIntent,
+ mAllowPickingMultiple, mPath, media_grid, fastscroller) {
+ if (it is Medium && !isFinishing) {
+ itemClicked(it.path)
+ }
+ }.apply {
+ setupZoomListener(mZoomListener)
+ media_grid.adapter = this
+ }
+ setupLayoutManager()
+ handleGridSpacing()
+ measureRecyclerViewContent(mMedia)
+ } else if (mLastSearchedText.isEmpty()) {
+ (currAdapter as MediaAdapter).updateMedia(mMedia)
+ handleGridSpacing()
+ measureRecyclerViewContent(mMedia)
+ } else {
+ searchQueryChanged(mLastSearchedText)
+ }
+
+ setupScrollDirection()
+ }
+
+ private fun setupScrollDirection() {
+ val viewType = config.getFolderViewType(if (mShowAll) SHOW_ALL else mPath)
+ val allowHorizontalScroll = config.scrollHorizontally && viewType == VIEW_TYPE_GRID
+ media_vertical_fastscroller.isHorizontal = false
+ media_vertical_fastscroller.beGoneIf(allowHorizontalScroll)
+
+ media_horizontal_fastscroller.isHorizontal = true
+ media_horizontal_fastscroller.beVisibleIf(allowHorizontalScroll)
+
+ val sorting = config.getFolderSorting(if (mShowAll) SHOW_ALL else mPath)
+ if (allowHorizontalScroll) {
+ media_horizontal_fastscroller.setViews(media_grid, media_refresh_layout) {
+ media_horizontal_fastscroller.updateBubbleText(getBubbleTextItem(it, sorting))
+ }
+ } else {
+ media_vertical_fastscroller.setViews(media_grid, media_refresh_layout) {
+ media_vertical_fastscroller.updateBubbleText(getBubbleTextItem(it, sorting))
+ }
+ }
+ }
+
+ private fun getBubbleTextItem(index: Int, sorting: Int): String {
+ var realIndex = index
+ val mediaAdapter = getMediaAdapter()
+ if (mediaAdapter?.isASectionTitle(index) == true) {
+ realIndex++
+ }
+ return mediaAdapter?.getItemBubbleText(realIndex, sorting, mDateFormat, mTimeFormat) ?: ""
+ }
+
+ private fun checkLastMediaChanged() {
+ if (isDestroyed || config.getFolderSorting(mPath) and SORT_BY_RANDOM != 0) {
+ return
+ }
+
+ mLastMediaHandler.removeCallbacksAndMessages(null)
+ mLastMediaHandler.postDelayed({
+ ensureBackgroundThread {
+ val mediaId = getLatestMediaId()
+ val mediaDateId = getLatestMediaByDateId()
+ if (mLatestMediaId != mediaId || mLatestMediaDateId != mediaDateId) {
+ mLatestMediaId = mediaId
+ mLatestMediaDateId = mediaDateId
+ runOnUiThread {
+ getMedia()
+ }
+ } else {
+ checkLastMediaChanged()
+ }
+ }
+ }, LAST_MEDIA_CHECK_PERIOD)
+ }
+
+ private fun showSortingDialog() {
+ ChangeSortingDialog(this, false, true, mPath) {
+ mLoadedInitialPhotos = false
+ media_grid.adapter = null
+ getMedia()
+ }
+ }
+
+ private fun showFilterMediaDialog() {
+ FilterMediaDialog(this) {
+ mLoadedInitialPhotos = false
+ media_refresh_layout.isRefreshing = true
+ media_grid.adapter = null
+ getMedia()
+ }
+ }
+
+ private fun emptyRecycleBin() {
+ showRecycleBinEmptyingDialog {
+ emptyTheRecycleBin {
+ finish()
+ }
+ }
+ }
+
+ private fun emptyAndDisableRecycleBin() {
+ showRecycleBinEmptyingDialog {
+ emptyAndDisableTheRecycleBin {
+ finish()
+ }
+ }
+ }
+
+ private fun restoreAllFiles() {
+ val paths = mMedia.filter { it is Medium }.map { (it as Medium).path } as ArrayList
+ restoreRecycleBinPaths(paths) {
+ ensureBackgroundThread {
+ directoryDao.deleteDirPath(RECYCLE_BIN)
+ }
+ finish()
+ }
+ }
+
+ private fun toggleFilenameVisibility() {
+ config.displayFileNames = !config.displayFileNames
+ getMediaAdapter()?.updateDisplayFilenames(config.displayFileNames)
+ }
+
+ private fun switchToFolderView() {
+ config.showAll = false
+ startActivity(Intent(this, MainActivity::class.java))
+ finish()
+ }
+
+ private fun changeViewType() {
+ ChangeViewTypeDialog(this, false, mPath) {
+ invalidateOptionsMenu()
+ setupLayoutManager()
+ media_grid.adapter = null
+ setupAdapter()
+ }
+ }
+
+ private fun showGroupByDialog() {
+ ChangeGroupingDialog(this, mPath) {
+ mLoadedInitialPhotos = false
+ media_grid.adapter = null
+ getMedia()
+ }
+ }
+
+ private fun deleteDirectoryIfEmpty() {
+ val fileDirItem = FileDirItem(mPath, mPath.getFilenameFromPath(), true)
+ if (config.deleteEmptyFolders && !fileDirItem.isDownloadsFolder() && fileDirItem.isDirectory && fileDirItem.getProperFileCount(this, true) == 0) {
+ tryDeleteFileDirItem(fileDirItem, true, true)
+ }
+ }
+
+ private fun getMedia() {
+ if (mIsGettingMedia) {
+ return
+ }
+
+ mIsGettingMedia = true
+ if (mLoadedInitialPhotos) {
+ startAsyncTask()
+ } else {
+ getCachedMedia(mPath, mIsGetVideoIntent, mIsGetImageIntent) {
+ if (it.isEmpty()) {
+ runOnUiThread {
+ media_refresh_layout.isRefreshing = true
+ }
+ } else {
+ gotMedia(it, true)
+ }
+ startAsyncTask()
+ }
+ }
+
+ mLoadedInitialPhotos = true
+ }
+
+ private fun startAsyncTask() {
+ mCurrAsyncTask?.stopFetching()
+ mCurrAsyncTask = GetMediaAsynctask(applicationContext, mPath, mIsGetImageIntent, mIsGetVideoIntent, mShowAll) {
+ ensureBackgroundThread {
+ val oldMedia = mMedia.clone() as ArrayList
+ val newMedia = it
+ try {
+ gotMedia(newMedia, false)
+ oldMedia.filter { !newMedia.contains(it) }.mapNotNull { it as? Medium }.filter { !getDoesFilePathExist(it.path) }.forEach {
+ mediaDB.deleteMediumPath(it.path)
+ }
+ } catch (e: Exception) {
+ }
+ }
+ }
+
+ mCurrAsyncTask!!.execute()
+ }
+
+ private fun isDirEmpty(): Boolean {
+ return if (mMedia.size <= 0 && config.filterMedia > 0) {
+ if (mPath != FAVORITES && mPath != RECYCLE_BIN) {
+ deleteDirectoryIfEmpty()
+ deleteDBDirectory()
+ }
+
+ if (mPath == FAVORITES) {
+ ensureBackgroundThread {
+ directoryDao.deleteDirPath(FAVORITES)
+ }
+ }
+
+ finish()
+ true
+ } else {
+ false
+ }
+ }
+
+ private fun deleteDBDirectory() {
+ ensureBackgroundThread {
+ try {
+ directoryDao.deleteDirPath(mPath)
+ } catch (ignored: Exception) {
+ }
+ }
+ }
+
+ private fun createNewFolder() {
+ CreateNewFolderDialog(this, mPath) {
+ config.tempFolderPath = it
+ }
+ }
+
+ private fun tryToggleTemporarilyShowHidden() {
+ if (config.temporarilyShowHidden) {
+ toggleTemporarilyShowHidden(false)
+ } else {
+ handleHiddenFolderPasswordProtection {
+ toggleTemporarilyShowHidden(true)
+ }
+ }
+ }
+
+ private fun toggleTemporarilyShowHidden(show: Boolean) {
+ mLoadedInitialPhotos = false
+ config.temporarilyShowHidden = show
+ getMedia()
+ invalidateOptionsMenu()
+ }
+
+ private fun setupLayoutManager() {
+ val viewType = config.getFolderViewType(if (mShowAll) SHOW_ALL else mPath)
+ if (viewType == VIEW_TYPE_GRID) {
+ setupGridLayoutManager()
+ } else {
+ setupListLayoutManager()
+ }
+ }
+
+ private fun setupGridLayoutManager() {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ (media_grid.layoutParams as RelativeLayout.LayoutParams).apply {
+ topMargin = 0
+ bottomMargin = 0
+ }
+
+ if (config.scrollHorizontally) {
+ layoutManager.orientation = RecyclerView.HORIZONTAL
+ media_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
+ } else {
+ layoutManager.orientation = RecyclerView.VERTICAL
+ media_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+ }
+
+ layoutManager.spanCount = config.mediaColumnCnt
+ val adapter = getMediaAdapter()
+ layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
+ override fun getSpanSize(position: Int): Int {
+ return if (adapter?.isASectionTitle(position) == true) {
+ layoutManager.spanCount
+ } else {
+ 1
+ }
+ }
+ }
+ }
+
+ private fun measureRecyclerViewContent(media: ArrayList) {
+ media_grid.onGlobalLayout {
+ if (config.scrollHorizontally) {
+ calculateContentWidth(media)
+ } else {
+ calculateContentHeight(media)
+ }
+ }
+ }
+
+ private fun calculateContentWidth(media: ArrayList) {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ val thumbnailWidth = layoutManager.getChildAt(0)?.width ?: 0
+ val spacing = config.thumbnailSpacing
+ val fullWidth = ((media.size - 1) / layoutManager.spanCount + 1) * (thumbnailWidth + spacing) - spacing
+ media_horizontal_fastscroller.setContentWidth(fullWidth)
+ media_horizontal_fastscroller.setScrollToX(media_grid.computeHorizontalScrollOffset())
+ }
+
+ private fun calculateContentHeight(media: ArrayList) {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ val pathToCheck = if (mPath.isEmpty()) SHOW_ALL else mPath
+ val hasSections = config.getFolderGrouping(pathToCheck) and GROUP_BY_NONE == 0 && !config.scrollHorizontally
+ val sectionTitleHeight = if (hasSections) layoutManager.getChildAt(0)?.height ?: 0 else 0
+ val thumbnailHeight = if (hasSections) layoutManager.getChildAt(1)?.height ?: 0 else layoutManager.getChildAt(0)?.height ?: 0
+
+ var fullHeight = 0
+ var curSectionItems = 0
+ media.forEach {
+ if (it is ThumbnailSection) {
+ fullHeight += sectionTitleHeight
+ if (curSectionItems != 0) {
+ val rows = ((curSectionItems - 1) / layoutManager.spanCount + 1)
+ fullHeight += rows * thumbnailHeight
+ }
+ curSectionItems = 0
+ } else {
+ curSectionItems++
+ }
+ }
+
+ val spacing = config.thumbnailSpacing
+ fullHeight += ((curSectionItems - 1) / layoutManager.spanCount + 1) * (thumbnailHeight + spacing) - spacing
+ media_vertical_fastscroller.setContentHeight(fullHeight)
+ media_vertical_fastscroller.setScrollToY(media_grid.computeVerticalScrollOffset())
+ }
+
+ private fun handleGridSpacing(media: ArrayList = mMedia) {
+ val viewType = config.getFolderViewType(if (mShowAll) SHOW_ALL else mPath)
+ if (viewType == VIEW_TYPE_GRID) {
+ val spanCount = config.mediaColumnCnt
+ val spacing = config.thumbnailSpacing
+ val useGridPosition = media.firstOrNull() is ThumbnailSection
+
+ var currentGridDecoration: GridSpacingItemDecoration? = null
+ if (media_grid.itemDecorationCount > 0) {
+ currentGridDecoration = media_grid.getItemDecorationAt(0) as GridSpacingItemDecoration
+ currentGridDecoration.items = media
+ }
+
+ val newGridDecoration = GridSpacingItemDecoration(spanCount, spacing, config.scrollHorizontally, config.fileRoundedCorners, media, useGridPosition)
+ if (currentGridDecoration.toString() != newGridDecoration.toString()) {
+ if (currentGridDecoration != null) {
+ media_grid.removeItemDecoration(currentGridDecoration)
+ }
+ media_grid.addItemDecoration(newGridDecoration)
+ }
+ }
+ }
+
+ private fun initZoomListener() {
+ val viewType = config.getFolderViewType(if (mShowAll) SHOW_ALL else mPath)
+ if (viewType == VIEW_TYPE_GRID) {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ mZoomListener = object : MyRecyclerView.MyZoomListener {
+ override fun zoomIn() {
+ if (layoutManager.spanCount > 1) {
+ reduceColumnCount()
+ getMediaAdapter()?.finishActMode()
+ }
+ }
+
+ override fun zoomOut() {
+ if (layoutManager.spanCount < MAX_COLUMN_COUNT) {
+ increaseColumnCount()
+ getMediaAdapter()?.finishActMode()
+ }
+ }
+ }
+ } else {
+ mZoomListener = null
+ }
+ }
+
+ private fun setupListLayoutManager() {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ layoutManager.spanCount = 1
+ layoutManager.orientation = RecyclerView.VERTICAL
+ media_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+
+ val smallMargin = resources.getDimension(R.dimen.small_margin).toInt()
+ (media_grid.layoutParams as RelativeLayout.LayoutParams).apply {
+ topMargin = smallMargin
+ bottomMargin = smallMargin
+ }
+
+ mZoomListener = null
+ }
+
+ private fun increaseColumnCount() {
+ config.mediaColumnCnt = ++(media_grid.layoutManager as MyGridLayoutManager).spanCount
+ columnCountChanged()
+ }
+
+ private fun reduceColumnCount() {
+ config.mediaColumnCnt = --(media_grid.layoutManager as MyGridLayoutManager).spanCount
+ columnCountChanged()
+ }
+
+ private fun columnCountChanged() {
+ handleGridSpacing()
+ invalidateOptionsMenu()
+ getMediaAdapter()?.apply {
+ notifyItemRangeChanged(0, media.size)
+ measureRecyclerViewContent(media)
+ }
+ }
+
+ private fun isSetWallpaperIntent() = intent.getBooleanExtra(SET_WALLPAPER_INTENT, false)
+
+ override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
+ if (requestCode == REQUEST_EDIT_IMAGE) {
+ if (resultCode == Activity.RESULT_OK && resultData != null) {
+ mMedia.clear()
+ refreshItems()
+ }
+ }
+ super.onActivityResult(requestCode, resultCode, resultData)
+ }
+
+ private fun itemClicked(path: String) {
+ if (isSetWallpaperIntent()) {
+ toast(R.string.setting_wallpaper)
+
+ val wantedWidth = wallpaperDesiredMinimumWidth
+ val wantedHeight = wallpaperDesiredMinimumHeight
+ val ratio = wantedWidth.toFloat() / wantedHeight
+
+ val options = RequestOptions()
+ .override((wantedWidth * ratio).toInt(), wantedHeight)
+ .fitCenter()
+
+ Glide.with(this)
+ .asBitmap()
+ .load(File(path))
+ .apply(options)
+ .into(object : SimpleTarget() {
+ override fun onResourceReady(resource: Bitmap, transition: Transition?) {
+ try {
+ WallpaperManager.getInstance(applicationContext).setBitmap(resource)
+ setResult(Activity.RESULT_OK)
+ } catch (ignored: IOException) {
+ }
+
+ finish()
+ }
+ })
+ } else if (mIsGetImageIntent || mIsGetVideoIntent || mIsGetAnyIntent) {
+ Intent().apply {
+ data = Uri.parse(path)
+ setResult(Activity.RESULT_OK, this)
+ }
+ finish()
+ } else {
+ val isVideo = path.isVideoFast()
+ if (isVideo) {
+ val extras = HashMap()
+ extras[SHOW_FAVORITES] = mPath == FAVORITES
+
+ if (shouldSkipAuthentication()) {
+ extras[SKIP_AUTHENTICATION] = true
+ }
+ openPath(path, false, extras)
+ } else {
+ Intent(this, ViewPagerActivity::class.java).apply {
+ putExtra(SKIP_AUTHENTICATION, shouldSkipAuthentication())
+ putExtra(PATH, path)
+ putExtra(SHOW_ALL, mShowAll)
+ putExtra(SHOW_FAVORITES, mPath == FAVORITES)
+ putExtra(SHOW_RECYCLE_BIN, mPath == RECYCLE_BIN)
+ startActivity(this)
+ }
+ }
+ }
+ }
+
+ private fun gotMedia(media: ArrayList, isFromCache: Boolean) {
+ mIsGettingMedia = false
+ checkLastMediaChanged()
+ mMedia = media
+
+ runOnUiThread {
+ media_refresh_layout.isRefreshing = false
+ media_empty_text_placeholder.beVisibleIf(media.isEmpty() && !isFromCache)
+ media_empty_text_placeholder_2.beVisibleIf(media.isEmpty() && !isFromCache)
+
+ if (media_empty_text_placeholder.isVisible()) {
+ media_empty_text_placeholder.text = getString(R.string.no_media_with_filters)
+ }
+ media_grid.beVisibleIf(media_empty_text_placeholder.isGone())
+
+ val viewType = config.getFolderViewType(if (mShowAll) SHOW_ALL else mPath)
+ val allowHorizontalScroll = config.scrollHorizontally && viewType == VIEW_TYPE_GRID
+ media_vertical_fastscroller.beVisibleIf(media_grid.isVisible() && !allowHorizontalScroll)
+ media_horizontal_fastscroller.beVisibleIf(media_grid.isVisible() && allowHorizontalScroll)
+ setupAdapter()
+ }
+
+ mLatestMediaId = getLatestMediaId()
+ mLatestMediaDateId = getLatestMediaByDateId()
+ if (!isFromCache) {
+ val mediaToInsert = (mMedia).filter { it is Medium && it.deletedTS == 0L }.map { it as Medium }
+ Thread {
+ try {
+ mediaDB.insertAll(mediaToInsert)
+ } catch (e: Exception) {
+ }
+ }.start()
+ }
+ }
+
+ override fun tryDeleteFiles(fileDirItems: ArrayList) {
+ val filtered = fileDirItems.filter { !getIsPathDirectory(it.path) && it.path.isMediaFile() } as ArrayList
+ if (filtered.isEmpty()) {
+ return
+ }
+
+ if (config.useRecycleBin && !filtered.first().path.startsWith(recycleBinPath)) {
+ val movingItems = resources.getQuantityString(R.plurals.moving_items_into_bin, filtered.size, filtered.size)
+ toast(movingItems)
+
+ movePathsInRecycleBin(filtered.map { it.path } as ArrayList) {
+ if (it) {
+ deleteFilteredFiles(filtered)
+ } else {
+ toast(R.string.unknown_error_occurred)
+ }
+ }
+ } else {
+ val deletingItems = resources.getQuantityString(R.plurals.deleting_items, filtered.size, filtered.size)
+ toast(deletingItems)
+ deleteFilteredFiles(filtered)
+ }
+ }
+
+ private fun shouldSkipAuthentication() = intent.getBooleanExtra(SKIP_AUTHENTICATION, false)
+
+ private fun deleteFilteredFiles(filtered: ArrayList) {
+ deleteFiles(filtered) {
+ if (!it) {
+ toast(R.string.unknown_error_occurred)
+ return@deleteFiles
+ }
+
+ mMedia.removeAll { filtered.map { it.path }.contains((it as? Medium)?.path) }
+
+ ensureBackgroundThread {
+ val useRecycleBin = config.useRecycleBin
+ filtered.forEach {
+ if (it.path.startsWith(recycleBinPath) || !useRecycleBin) {
+ deleteDBPath(it.path)
+ }
+ }
+ }
+
+ if (mMedia.isEmpty()) {
+ deleteDirectoryIfEmpty()
+ deleteDBDirectory()
+ finish()
+ }
+ }
+ }
+
+ override fun refreshItems() {
+ getMedia()
+ }
+
+ override fun selectedPaths(paths: ArrayList) {
+ Intent().apply {
+ putExtra(PICKED_PATHS, paths)
+ setResult(Activity.RESULT_OK, this)
+ }
+ finish()
+ }
+
+ override fun updateMediaGridDecoration(media: ArrayList) {
+ var currentGridPosition = 0
+ media.forEach {
+ if (it is Medium) {
+ it.gridPosition = currentGridPosition++
+ } else if (it is ThumbnailSection) {
+ currentGridPosition = 0
+ }
+ }
+
+ if (media_grid.itemDecorationCount > 0) {
+ val currentGridDecoration = media_grid.getItemDecorationAt(0) as GridSpacingItemDecoration
+ currentGridDecoration.items = media
+ }
+ }
+
+ private fun setAsDefaultFolder() {
+ config.defaultFolder = mPath
+ invalidateOptionsMenu()
+ }
+
+ private fun unsetAsDefaultFolder() {
+ config.defaultFolder = ""
+ invalidateOptionsMenu()
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaPhotoActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaPhotoActivity.kt
new file mode 100644
index 000000000..362bd6f8b
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaPhotoActivity.kt
@@ -0,0 +1,182 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.content.res.Configuration
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Color
+import android.net.Uri
+import android.os.Bundle
+import android.view.View
+import android.view.Window
+import android.widget.RelativeLayout
+import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener
+import com.google.vr.sdk.widgets.pano.VrPanoramaView
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.PATH
+import kotlinx.android.synthetic.main.activity_panorama_photo.*
+
+open class PanoramaPhotoActivity : SimpleActivity() {
+ private val CARDBOARD_DISPLAY_MODE = 3
+
+ private var isFullscreen = false
+ private var isExploreEnabled = true
+ private var isRendering = false
+
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ useDynamicTheme = false
+ requestWindowFeature(Window.FEATURE_NO_TITLE)
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_panorama_photo)
+ supportActionBar?.hide()
+
+ checkNotchSupport()
+ setupButtonMargins()
+
+ cardboard.setOnClickListener {
+ panorama_view.displayMode = CARDBOARD_DISPLAY_MODE
+ }
+
+ explore.setOnClickListener {
+ isExploreEnabled = !isExploreEnabled
+ panorama_view.setPureTouchTracking(isExploreEnabled)
+ explore.setImageResource(if (isExploreEnabled) R.drawable.ic_explore_vector else R.drawable.ic_explore_off_vector)
+ }
+
+ checkIntent()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ panorama_view.resumeRendering()
+ isRendering = true
+ if (config.blackBackground) {
+ updateStatusbarColor(Color.BLACK)
+ }
+
+ window.statusBarColor = resources.getColor(R.color.circle_black_background)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ panorama_view.pauseRendering()
+ isRendering = false
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ if (isRendering) {
+ panorama_view.shutdown()
+ }
+ }
+
+ private fun checkIntent() {
+ val path = intent.getStringExtra(PATH)
+ if (path == null) {
+ toast(R.string.invalid_image_path)
+ finish()
+ return
+ }
+
+ intent.removeExtra(PATH)
+
+ try {
+ val options = VrPanoramaView.Options()
+ options.inputType = VrPanoramaView.Options.TYPE_MONO
+ ensureBackgroundThread {
+ val bitmap = getBitmapToLoad(path)
+ runOnUiThread {
+ panorama_view.apply {
+ beVisible()
+ loadImageFromBitmap(bitmap, options)
+ setFlingingEnabled(true)
+ setPureTouchTracking(true)
+
+ // add custom buttons so we can position them and toggle visibility as desired
+ setFullscreenButtonEnabled(false)
+ setInfoButtonEnabled(false)
+ setTransitionViewEnabled(false)
+ setStereoModeButtonEnabled(false)
+
+ setOnClickListener {
+ handleClick()
+ }
+
+ setEventListener(object : VrPanoramaEventListener() {
+ override fun onClick() {
+ handleClick()
+ }
+ })
+ }
+ }
+ }
+ } catch (e: Exception) {
+ showErrorToast(e)
+ }
+
+ window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
+ isFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
+ toggleButtonVisibility()
+ }
+ }
+
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ setupButtonMargins()
+ }
+
+ private fun getBitmapToLoad(path: String): Bitmap? {
+ val options = BitmapFactory.Options()
+ options.inSampleSize = 1
+ var bitmap: Bitmap? = null
+
+ for (i in 0..10) {
+ try {
+ bitmap = if (path.startsWith("content://")) {
+ val inputStream = contentResolver.openInputStream(Uri.parse(path))
+ BitmapFactory.decodeStream(inputStream)
+ } else {
+ BitmapFactory.decodeFile(path, options)
+ }
+ break
+ } catch (e: OutOfMemoryError) {
+ options.inSampleSize *= 2
+ }
+ }
+
+ return bitmap
+ }
+
+ private fun setupButtonMargins() {
+ val navBarHeight = navigationBarHeight
+ (cardboard.layoutParams as RelativeLayout.LayoutParams).apply {
+ bottomMargin = navBarHeight
+ rightMargin = navigationBarWidth
+ }
+
+ (explore.layoutParams as RelativeLayout.LayoutParams).bottomMargin = navigationBarHeight
+
+ cardboard.onGlobalLayout {
+ panorama_gradient_background.layoutParams.height = navBarHeight + cardboard.height
+ }
+ }
+
+ private fun toggleButtonVisibility() {
+ arrayOf(cardboard, explore, panorama_gradient_background).forEach {
+ it.animate().alpha(if (isFullscreen) 0f else 1f)
+ it.isClickable = !isFullscreen
+ }
+ }
+
+ private fun handleClick() {
+ isFullscreen = !isFullscreen
+ toggleButtonVisibility()
+ if (isFullscreen) {
+ hideSystemUI(false)
+ } else {
+ showSystemUI(false)
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaVideoActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaVideoActivity.kt
new file mode 100644
index 000000000..7098e3e4a
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaVideoActivity.kt
@@ -0,0 +1,319 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.content.res.Configuration
+import android.graphics.Color
+import android.net.Uri
+import android.os.Bundle
+import android.os.Handler
+import android.view.View
+import android.view.Window
+import android.view.WindowManager
+import android.widget.RelativeLayout
+import android.widget.SeekBar
+import com.google.vr.sdk.widgets.video.VrVideoEventListener
+import com.google.vr.sdk.widgets.video.VrVideoView
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.MIN_SKIP_LENGTH
+import com.simplemobiletools.gallery.pro.helpers.PATH
+import kotlinx.android.synthetic.main.activity_panorama_video.*
+import kotlinx.android.synthetic.main.bottom_video_time_holder.*
+import java.io.File
+
+open class PanoramaVideoActivity : SimpleActivity(), SeekBar.OnSeekBarChangeListener {
+ private val CARDBOARD_DISPLAY_MODE = 3
+
+ private var mIsFullscreen = false
+ private var mIsExploreEnabled = true
+ private var mIsRendering = false
+ private var mIsPlaying = false
+ private var mIsDragged = false
+ private var mPlayOnReady = false
+ private var mDuration = 0
+ private var mCurrTime = 0
+
+ private var mTimerHandler = Handler()
+
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ useDynamicTheme = false
+ requestWindowFeature(Window.FEATURE_NO_TITLE)
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_panorama_video)
+ supportActionBar?.hide()
+
+ checkNotchSupport()
+ checkIntent()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ vr_video_view.resumeRendering()
+ mIsRendering = true
+ if (config.blackBackground) {
+ updateStatusbarColor(Color.BLACK)
+ }
+
+ window.statusBarColor = resources.getColor(R.color.circle_black_background)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ vr_video_view.pauseRendering()
+ mIsRendering = false
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ if (mIsRendering) {
+ vr_video_view.shutdown()
+ }
+
+ if (!isChangingConfigurations) {
+ mTimerHandler.removeCallbacksAndMessages(null)
+ }
+ }
+
+ private fun checkIntent() {
+ val path = intent.getStringExtra(PATH)
+ if (path == null) {
+ toast(R.string.invalid_image_path)
+ finish()
+ return
+ }
+
+ setupButtons()
+ intent.removeExtra(PATH)
+
+ video_curr_time.setOnClickListener { skip(false) }
+ video_duration.setOnClickListener { skip(true) }
+
+ try {
+ val options = VrVideoView.Options()
+ options.inputType = VrVideoView.Options.TYPE_MONO
+ val uri = if (path.startsWith("content://")) {
+ Uri.parse(path)
+ } else {
+ Uri.fromFile(File(path))
+ }
+
+ vr_video_view.apply {
+ loadVideo(uri, options)
+ pauseVideo()
+
+ setFlingingEnabled(true)
+ setPureTouchTracking(true)
+
+ // add custom buttons so we can position them and toggle visibility as desired
+ setFullscreenButtonEnabled(false)
+ setInfoButtonEnabled(false)
+ setTransitionViewEnabled(false)
+ setStereoModeButtonEnabled(false)
+
+ setOnClickListener {
+ handleClick()
+ }
+
+ setEventListener(object : VrVideoEventListener() {
+ override fun onClick() {
+ handleClick()
+ }
+
+ override fun onLoadSuccess() {
+ if (mDuration == 0) {
+ setupDuration(duration)
+ setupTimer()
+ }
+
+ if (mPlayOnReady || config.autoplayVideos) {
+ mPlayOnReady = false
+ mIsPlaying = true
+ resumeVideo()
+ } else {
+ video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
+ }
+ video_toggle_play_pause.beVisible()
+ }
+
+ override fun onCompletion() {
+ videoCompleted()
+ }
+ })
+ }
+
+ video_toggle_play_pause.setOnClickListener {
+ togglePlayPause()
+ }
+ } catch (e: Exception) {
+ showErrorToast(e)
+ }
+
+ window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
+ mIsFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
+ toggleButtonVisibility()
+ }
+ }
+
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ setupButtons()
+ }
+
+ private fun setupDuration(duration: Long) {
+ mDuration = (duration / 1000).toInt()
+ video_seekbar.max = mDuration
+ video_duration.text = mDuration.getFormattedDuration()
+ setVideoProgress(0)
+ }
+
+ private fun setupTimer() {
+ runOnUiThread(object : Runnable {
+ override fun run() {
+ if (mIsPlaying && !mIsDragged) {
+ mCurrTime = (vr_video_view!!.currentPosition / 1000).toInt()
+ video_seekbar.progress = mCurrTime
+ video_curr_time.text = mCurrTime.getFormattedDuration()
+ }
+
+ mTimerHandler.postDelayed(this, 1000)
+ }
+ })
+ }
+
+ private fun togglePlayPause() {
+ mIsPlaying = !mIsPlaying
+ if (mIsPlaying) {
+ resumeVideo()
+ } else {
+ pauseVideo()
+ }
+ }
+
+ private fun resumeVideo() {
+ video_toggle_play_pause.setImageResource(R.drawable.ic_pause_outline_vector)
+ if (mCurrTime == mDuration) {
+ setVideoProgress(0)
+ mPlayOnReady = true
+ return
+ }
+
+ vr_video_view.playVideo()
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+
+ private fun pauseVideo() {
+ vr_video_view.pauseVideo()
+ video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
+ window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+
+ private fun setVideoProgress(seconds: Int) {
+ vr_video_view.seekTo(seconds * 1000L)
+ video_seekbar.progress = seconds
+ mCurrTime = seconds
+ video_curr_time.text = seconds.getFormattedDuration()
+ }
+
+ private fun videoCompleted() {
+ mIsPlaying = false
+ mCurrTime = (vr_video_view.duration / 1000).toInt()
+ video_seekbar.progress = video_seekbar.max
+ video_curr_time.text = mDuration.getFormattedDuration()
+ pauseVideo()
+ }
+
+ private fun setupButtons() {
+ var right = 0
+ var bottom = 0
+
+ if (hasNavBar()) {
+ if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
+ bottom += navigationBarHeight
+ } else {
+ right += navigationBarWidth
+ bottom += navigationBarHeight
+ }
+ }
+
+ video_time_holder.setPadding(0, 0, right, bottom)
+ video_time_holder.background = resources.getDrawable(R.drawable.gradient_background)
+ video_time_holder.onGlobalLayout {
+ val newBottomMargin = video_time_holder.height - resources.getDimension(R.dimen.video_player_play_pause_size).toInt() - resources.getDimension(R.dimen.activity_margin).toInt()
+ (explore.layoutParams as RelativeLayout.LayoutParams).bottomMargin = newBottomMargin
+
+ (cardboard.layoutParams as RelativeLayout.LayoutParams).apply {
+ bottomMargin = newBottomMargin
+ rightMargin = navigationBarWidth
+ }
+ explore.requestLayout()
+ }
+ video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
+
+ cardboard.setOnClickListener {
+ vr_video_view.displayMode = CARDBOARD_DISPLAY_MODE
+ }
+
+ explore.setOnClickListener {
+ mIsExploreEnabled = !mIsExploreEnabled
+ vr_video_view.setPureTouchTracking(mIsExploreEnabled)
+ explore.setImageResource(if (mIsExploreEnabled) R.drawable.ic_explore_vector else R.drawable.ic_explore_off_vector)
+ }
+ }
+
+ private fun toggleButtonVisibility() {
+ val newAlpha = if (mIsFullscreen) 0f else 1f
+ arrayOf(cardboard, explore).forEach {
+ it.animate().alpha(newAlpha)
+ }
+
+ arrayOf(cardboard, explore, video_toggle_play_pause, video_curr_time, video_duration).forEach {
+ it.isClickable = !mIsFullscreen
+ }
+
+ video_seekbar.setOnSeekBarChangeListener(if (mIsFullscreen) null else this)
+ video_time_holder.animate().alpha(newAlpha).start()
+ }
+
+ private fun handleClick() {
+ mIsFullscreen = !mIsFullscreen
+ toggleButtonVisibility()
+ if (mIsFullscreen) {
+ hideSystemUI(false)
+ } else {
+ showSystemUI(false)
+ }
+ }
+
+ private fun skip(forward: Boolean) {
+ if (forward && mCurrTime == mDuration) {
+ return
+ }
+
+ val curr = vr_video_view.currentPosition
+ val twoPercents = Math.max((vr_video_view.duration / 50).toInt(), MIN_SKIP_LENGTH)
+ val newProgress = if (forward) curr + twoPercents else curr - twoPercents
+ val roundProgress = Math.round(newProgress / 1000f)
+ val limitedProgress = Math.max(Math.min(vr_video_view.duration.toInt(), roundProgress), 0)
+ setVideoProgress(limitedProgress)
+ if (!mIsPlaying) {
+ togglePlayPause()
+ }
+ }
+
+ override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
+ if (fromUser) {
+ setVideoProgress(progress)
+ }
+ }
+
+ override fun onStartTrackingTouch(seekBar: SeekBar?) {
+ vr_video_view.pauseVideo()
+ mIsDragged = true
+ }
+
+ override fun onStopTrackingTouch(seekBar: SeekBar?) {
+ mIsPlaying = true
+ resumeVideo()
+ mIsDragged = false
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/PhotoActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PhotoActivity.kt
similarity index 65%
rename from app/src/main/kotlin/com/simplemobiletools/gallery/activities/PhotoActivity.kt
rename to app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PhotoActivity.kt
index ef309a26d..95c439d3a 100644
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/PhotoActivity.kt
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PhotoActivity.kt
@@ -1,10 +1,10 @@
-package com.simplemobiletools.gallery.activities
+package com.simplemobiletools.gallery.pro.activities
import android.os.Bundle
class PhotoActivity : PhotoVideoActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
- PhotoVideoActivity.mIsVideo = false
+ mIsVideo = false
super.onCreate(savedInstanceState)
}
}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PhotoVideoActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PhotoVideoActivity.kt
new file mode 100644
index 000000000..ff328654b
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PhotoVideoActivity.kt
@@ -0,0 +1,354 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.content.Intent
+import android.content.res.Configuration
+import android.graphics.Color
+import android.graphics.drawable.ColorDrawable
+import android.net.Uri
+import android.os.Bundle
+import android.view.Menu
+import android.view.MenuItem
+import android.view.View
+import com.simplemobiletools.commons.dialogs.PropertiesDialog
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.IS_FROM_GALLERY
+import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_STORAGE
+import com.simplemobiletools.commons.helpers.REAL_FILE_PATH
+import com.simplemobiletools.gallery.pro.BuildConfig
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.fragments.PhotoFragment
+import com.simplemobiletools.gallery.pro.fragments.VideoFragment
+import com.simplemobiletools.gallery.pro.fragments.ViewPagerFragment
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.models.Medium
+import kotlinx.android.synthetic.main.bottom_actions.*
+import kotlinx.android.synthetic.main.fragment_holder.*
+import java.io.File
+import java.io.FileInputStream
+
+open class PhotoVideoActivity : SimpleActivity(), ViewPagerFragment.FragmentListener {
+ private var mMedium: Medium? = null
+ private var mIsFullScreen = false
+ private var mIsFromGallery = false
+ private var mFragment: ViewPagerFragment? = null
+ private var mUri: Uri? = null
+
+ var mIsVideo = false
+
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.fragment_holder)
+
+ if (checkAppSideloading()) {
+ return
+ }
+
+ handlePermission(PERMISSION_WRITE_STORAGE) {
+ if (it) {
+ checkIntent(savedInstanceState)
+ } else {
+ toast(R.string.no_storage_permissions)
+ finish()
+ }
+ }
+ }
+
+ override fun onResume() {
+ super.onResume()
+ supportActionBar?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
+ window.statusBarColor = Color.TRANSPARENT
+
+ if (config.bottomActions) {
+ window.navigationBarColor = Color.TRANSPARENT
+ } else {
+ setTranslucentNavigation()
+ }
+
+ if (config.blackBackground) {
+ updateStatusbarColor(Color.BLACK)
+ }
+ }
+
+ private fun checkIntent(savedInstanceState: Bundle? = null) {
+ if (intent.data == null && intent.action == Intent.ACTION_VIEW) {
+ startActivity(Intent(this, MainActivity::class.java))
+ finish()
+ return
+ }
+
+ mUri = intent.data ?: return
+ val uri = mUri.toString()
+ if (uri.startsWith("content:/") && uri.contains("/storage/")) {
+ val guessedPath = uri.substring(uri.indexOf("/storage/"))
+ if (getDoesFilePathExist(guessedPath)) {
+ val extras = intent.extras ?: Bundle()
+ extras.apply {
+ putString(REAL_FILE_PATH, guessedPath)
+ intent.putExtras(this)
+ }
+ }
+ }
+
+ var filename = getFilenameFromUri(mUri!!)
+ mIsFromGallery = intent.getBooleanExtra(IS_FROM_GALLERY, false)
+ if (mIsFromGallery && filename.isVideoFast() && config.openVideosOnSeparateScreen) {
+ launchVideoPlayer()
+ return
+ }
+
+ if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
+ val realPath = intent.extras!!.getString(REAL_FILE_PATH)
+ if (realPath != null && getDoesFilePathExist(realPath)) {
+ if (realPath.getFilenameFromPath().contains('.') || filename.contains('.')) {
+ if (isFileTypeVisible(realPath)) {
+ bottom_actions.beGone()
+ sendViewPagerIntent(realPath)
+ finish()
+ return
+ }
+ } else {
+ filename = realPath.getFilenameFromPath()
+ }
+ }
+ }
+
+ if (mUri!!.scheme == "file") {
+ if (filename.contains('.')) {
+ bottom_actions.beGone()
+ rescanPaths(arrayListOf(mUri!!.path!!))
+ sendViewPagerIntent(mUri!!.path!!)
+ finish()
+ }
+ return
+ } else {
+ val path = applicationContext.getRealPathFromURI(mUri!!) ?: ""
+ if (path != mUri.toString() && path.isNotEmpty() && mUri!!.authority != "mms" && filename.contains('.') && getDoesFilePathExist(path)) {
+ if (isFileTypeVisible(path)) {
+ bottom_actions.beGone()
+ rescanPaths(arrayListOf(mUri!!.path!!))
+ sendViewPagerIntent(path)
+ finish()
+ return
+ }
+ }
+ }
+
+ checkNotchSupport()
+ showSystemUI(true)
+ val bundle = Bundle()
+ val file = File(mUri.toString())
+ val intentType = intent.type ?: ""
+ val type = when {
+ filename.isVideoFast() || intentType.startsWith("video/") -> TYPE_VIDEOS
+ filename.isGif() || intentType.equals("image/gif", true) -> TYPE_GIFS
+ filename.isRawFast() -> TYPE_RAWS
+ filename.isSvg() -> TYPE_SVGS
+ file.isPortrait() -> TYPE_PORTRAITS
+ else -> TYPE_IMAGES
+ }
+
+ mIsVideo = type == TYPE_VIDEOS
+ mMedium = Medium(null, filename, mUri.toString(), mUri!!.path!!.getParentPath(), 0, 0, file.length(), type, 0, false, 0L)
+ supportActionBar?.title = mMedium!!.name
+ bundle.putSerializable(MEDIUM, mMedium)
+
+ if (savedInstanceState == null) {
+ mFragment = if (mIsVideo) VideoFragment() else PhotoFragment()
+ mFragment!!.listener = this
+ mFragment!!.arguments = bundle
+ supportFragmentManager.beginTransaction().replace(R.id.fragment_placeholder, mFragment!!).commit()
+ }
+
+ if (config.blackBackground) {
+ fragment_holder.background = ColorDrawable(Color.BLACK)
+ }
+
+ if (config.maxBrightness) {
+ val attributes = window.attributes
+ attributes.screenBrightness = 1f
+ window.attributes = attributes
+ }
+
+ window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
+ val isFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
+ mFragment?.fullscreenToggled(isFullscreen)
+ }
+
+ initBottomActions()
+ }
+
+ private fun launchVideoPlayer() {
+ val newUri = getFinalUriFromPath(mUri.toString(), BuildConfig.APPLICATION_ID)
+ if (newUri == null) {
+ toast(R.string.unknown_error_occurred)
+ return
+ }
+
+ var isPanorama = false
+ val realPath = intent?.extras?.getString(REAL_FILE_PATH) ?: ""
+ try {
+ if (realPath.isNotEmpty()) {
+ val fis = FileInputStream(File(realPath))
+ parseFileChannel(realPath, fis.channel, 0, 0, 0) {
+ isPanorama = true
+ }
+ }
+ } catch (ignored: Exception) {
+ } catch (ignored: OutOfMemoryError) {
+ }
+
+ if (isPanorama) {
+ Intent(applicationContext, PanoramaVideoActivity::class.java).apply {
+ putExtra(PATH, realPath)
+ startActivity(this)
+ }
+ } else {
+ val mimeType = getUriMimeType(mUri.toString(), newUri)
+ Intent(applicationContext, VideoPlayerActivity::class.java).apply {
+ setDataAndType(newUri, mimeType)
+ addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT)
+ if (intent.extras != null) {
+ putExtras(intent.extras!!)
+ }
+
+ startActivity(this)
+ }
+ }
+ finish()
+ }
+
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ initBottomActionsLayout()
+ }
+
+ private fun sendViewPagerIntent(path: String) {
+ Intent(this, ViewPagerActivity::class.java).apply {
+ putExtra(SKIP_AUTHENTICATION, intent.getBooleanExtra(SKIP_AUTHENTICATION, false))
+ putExtra(SHOW_FAVORITES, intent.getBooleanExtra(SHOW_FAVORITES, false))
+ putExtra(IS_VIEW_INTENT, true)
+ putExtra(IS_FROM_GALLERY, mIsFromGallery)
+ putExtra(PATH, path)
+ startActivity(this)
+ }
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.photo_video_menu, menu)
+ val visibleBottomActions = if (config.bottomActions) config.visibleBottomActions else 0
+
+ menu.apply {
+ findItem(R.id.menu_set_as).isVisible = mMedium?.isImage() == true && visibleBottomActions and BOTTOM_ACTION_SET_AS == 0
+ findItem(R.id.menu_edit).isVisible = mMedium?.isImage() == true && mUri?.scheme == "file" && visibleBottomActions and BOTTOM_ACTION_EDIT == 0
+ findItem(R.id.menu_properties).isVisible = mUri?.scheme == "file" && visibleBottomActions and BOTTOM_ACTION_PROPERTIES == 0
+ findItem(R.id.menu_share).isVisible = visibleBottomActions and BOTTOM_ACTION_SHARE == 0
+ findItem(R.id.menu_show_on_map).isVisible = visibleBottomActions and BOTTOM_ACTION_SHOW_ON_MAP == 0
+ }
+
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ if (mMedium == null || mUri == null) {
+ return true
+ }
+
+ when (item.itemId) {
+ R.id.menu_set_as -> setAs(mUri!!.toString())
+ R.id.menu_open_with -> openPath(mUri!!.toString(), true)
+ R.id.menu_share -> sharePath(mUri!!.toString())
+ R.id.menu_edit -> openEditor(mUri!!.toString())
+ R.id.menu_properties -> showProperties()
+ R.id.menu_show_on_map -> showFileOnMap(mUri!!.toString())
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ private fun showProperties() {
+ PropertiesDialog(this, mUri!!.path!!)
+ }
+
+ private fun isFileTypeVisible(path: String): Boolean {
+ val filter = config.filterMedia
+ return !(path.isImageFast() && filter and TYPE_IMAGES == 0 ||
+ path.isVideoFast() && filter and TYPE_VIDEOS == 0 ||
+ path.isGif() && filter and TYPE_GIFS == 0 ||
+ path.isRawFast() && filter and TYPE_RAWS == 0 ||
+ path.isSvg() && filter and TYPE_SVGS == 0 ||
+ path.isPortrait() && filter and TYPE_PORTRAITS == 0)
+ }
+
+ private fun initBottomActions() {
+ initBottomActionButtons()
+ initBottomActionsLayout()
+ }
+
+ private fun initBottomActionsLayout() {
+ bottom_actions.layoutParams.height = resources.getDimension(R.dimen.bottom_actions_height).toInt() + navigationBarHeight
+ if (config.bottomActions) {
+ bottom_actions.beVisible()
+ } else {
+ bottom_actions.beGone()
+ }
+ }
+
+ private fun initBottomActionButtons() {
+ arrayListOf(bottom_favorite, bottom_delete, bottom_rotate, bottom_properties, bottom_change_orientation, bottom_slideshow, bottom_show_on_map,
+ bottom_toggle_file_visibility, bottom_rename, bottom_copy, bottom_move, bottom_resize).forEach {
+ it.beGone()
+ }
+
+ val visibleBottomActions = if (config.bottomActions) config.visibleBottomActions else 0
+ bottom_edit.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_EDIT != 0 && mMedium?.isImage() == true)
+ bottom_edit.setOnClickListener {
+ if (mUri != null && bottom_actions.alpha == 1f) {
+ openEditor(mUri!!.toString())
+ }
+ }
+
+ bottom_share.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SHARE != 0)
+ bottom_share.setOnClickListener {
+ if (mUri != null && bottom_actions.alpha == 1f) {
+ sharePath(mUri!!.toString())
+ }
+ }
+
+ bottom_set_as.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SET_AS != 0 && mMedium?.isImage() == true)
+ bottom_set_as.setOnClickListener {
+ setAs(mUri!!.toString())
+ }
+
+ bottom_show_on_map.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SHOW_ON_MAP != 0)
+ bottom_show_on_map.setOnClickListener {
+ showFileOnMap(mUri!!.toString())
+ }
+ }
+
+ override fun fragmentClicked() {
+ mIsFullScreen = !mIsFullScreen
+ if (mIsFullScreen) {
+ hideSystemUI(true)
+ } else {
+ showSystemUI(true)
+ }
+
+ val newAlpha = if (mIsFullScreen) 0f else 1f
+ top_shadow.animate().alpha(newAlpha).start()
+ if (!bottom_actions.isGone()) {
+ bottom_actions.animate().alpha(newAlpha).start()
+ }
+ }
+
+ override fun videoEnded() = false
+
+ override fun goToPrevItem() {}
+
+ override fun goToNextItem() {}
+
+ override fun launchViewVideoIntent(path: String) {}
+
+ override fun isSlideShowActive() = false
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SearchActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SearchActivity.kt
new file mode 100644
index 000000000..769d65e90
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SearchActivity.kt
@@ -0,0 +1,385 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.app.SearchManager
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.view.Menu
+import android.view.MenuItem
+import android.view.ViewGroup
+import android.widget.RelativeLayout
+import androidx.appcompat.widget.SearchView
+import androidx.core.view.MenuItemCompat
+import androidx.recyclerview.widget.GridLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.VIEW_TYPE_GRID
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.commons.models.FileDirItem
+import com.simplemobiletools.commons.views.MyGridLayoutManager
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.MediaAdapter
+import com.simplemobiletools.gallery.pro.asynctasks.GetMediaAsynctask
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.interfaces.MediaOperationsListener
+import com.simplemobiletools.gallery.pro.models.Medium
+import com.simplemobiletools.gallery.pro.models.ThumbnailItem
+import com.simplemobiletools.gallery.pro.models.ThumbnailSection
+import kotlinx.android.synthetic.main.activity_media.*
+import kotlinx.android.synthetic.main.activity_search.*
+import kotlinx.android.synthetic.main.activity_search.media_empty_text_placeholder
+import kotlinx.android.synthetic.main.activity_search.media_grid
+import kotlinx.android.synthetic.main.activity_search.media_horizontal_fastscroller
+import kotlinx.android.synthetic.main.activity_search.media_vertical_fastscroller
+import java.io.File
+
+class SearchActivity : SimpleActivity(), MediaOperationsListener {
+ private var mIsSearchOpen = false
+ private var mLastSearchedText = ""
+ private var mDateFormat = ""
+ private var mTimeFormat = ""
+
+ private var mSearchMenuItem: MenuItem? = null
+ private var mCurrAsyncTask: GetMediaAsynctask? = null
+ private var mAllMedia = ArrayList()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_search)
+ media_empty_text_placeholder.setTextColor(config.textColor)
+ mDateFormat = config.dateFormat
+ mTimeFormat = getTimeFormat()
+ getAllMedia()
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ mCurrAsyncTask?.stopFetching()
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_search, menu)
+ setupSearch(menu)
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.toggle_filename -> toggleFilenameVisibility()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ private fun setupSearch(menu: Menu) {
+ val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
+ mSearchMenuItem = menu.findItem(R.id.search)
+ (mSearchMenuItem?.actionView as? SearchView)?.apply {
+ setSearchableInfo(searchManager.getSearchableInfo(componentName))
+ isSubmitButtonEnabled = false
+ setOnQueryTextListener(object : SearchView.OnQueryTextListener {
+ override fun onQueryTextSubmit(query: String) = false
+
+ override fun onQueryTextChange(newText: String): Boolean {
+ if (mIsSearchOpen) {
+ mLastSearchedText = newText
+ textChanged(newText)
+ }
+ return true
+ }
+ })
+ }
+
+ MenuItemCompat.setOnActionExpandListener(mSearchMenuItem, object : MenuItemCompat.OnActionExpandListener {
+ override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
+ mIsSearchOpen = true
+ return true
+ }
+
+ // this triggers on device rotation too, avoid doing anything
+ override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
+ if (mIsSearchOpen) {
+ mIsSearchOpen = false
+ mLastSearchedText = ""
+ }
+ return true
+ }
+ })
+ mSearchMenuItem?.expandActionView()
+ }
+
+ private fun textChanged(text: String) {
+ ensureBackgroundThread {
+ try {
+ val filtered = mAllMedia.filter { it is Medium && it.name.contains(text, true) } as ArrayList
+ filtered.sortBy { it is Medium && !it.name.startsWith(text, true) }
+ val grouped = MediaFetcher(applicationContext).groupMedia(filtered as ArrayList, "")
+ runOnUiThread {
+ if (grouped.isEmpty()) {
+ media_empty_text_placeholder.text = getString(R.string.no_items_found)
+ media_empty_text_placeholder.beVisible()
+ } else {
+ media_empty_text_placeholder.beGone()
+ }
+
+ handleGridSpacing(grouped)
+ getMediaAdapter()?.updateMedia(grouped)
+ measureRecyclerViewContent(grouped)
+ }
+ } catch (ignored: Exception) {
+ }
+ }
+ }
+
+ private fun setupAdapter() {
+ val currAdapter = media_grid.adapter
+ if (currAdapter == null) {
+ val fastscroller = if (config.scrollHorizontally) media_horizontal_fastscroller else media_vertical_fastscroller
+ MediaAdapter(this, ArrayList(), this, false, false, "", media_grid, fastscroller) {
+ if (it is Medium) {
+ itemClicked(it.path)
+ }
+ }.apply {
+ media_grid.adapter = this
+ }
+ setupLayoutManager()
+ handleGridSpacing(mAllMedia)
+ measureRecyclerViewContent(mAllMedia)
+ } else if (mLastSearchedText.isEmpty()) {
+ (currAdapter as MediaAdapter).updateMedia(mAllMedia)
+ handleGridSpacing(mAllMedia)
+ measureRecyclerViewContent(mAllMedia)
+ } else {
+ textChanged(mLastSearchedText)
+ }
+
+ setupScrollDirection()
+ }
+
+ private fun handleGridSpacing(media: ArrayList) {
+ val viewType = config.getFolderViewType(SHOW_ALL)
+ if (viewType == VIEW_TYPE_GRID) {
+ if (media_grid.itemDecorationCount > 0) {
+ media_grid.removeItemDecorationAt(0)
+ }
+
+ val spanCount = config.mediaColumnCnt
+ val spacing = config.thumbnailSpacing
+ val decoration = GridSpacingItemDecoration(spanCount, spacing, config.scrollHorizontally, config.fileRoundedCorners, media, true)
+ media_grid.addItemDecoration(decoration)
+ }
+ }
+
+ private fun getMediaAdapter() = media_grid.adapter as? MediaAdapter
+
+ private fun toggleFilenameVisibility() {
+ config.displayFileNames = !config.displayFileNames
+ getMediaAdapter()?.updateDisplayFilenames(config.displayFileNames)
+ }
+
+ private fun itemClicked(path: String) {
+ val isVideo = path.isVideoFast()
+ if (isVideo) {
+ openPath(path, false)
+ } else {
+ Intent(this, ViewPagerActivity::class.java).apply {
+ putExtra(PATH, path)
+ putExtra(SHOW_ALL, false)
+ startActivity(this)
+ }
+ }
+ }
+
+ private fun setupLayoutManager() {
+ val viewType = config.getFolderViewType(SHOW_ALL)
+ if (viewType == VIEW_TYPE_GRID) {
+ setupGridLayoutManager()
+ } else {
+ setupListLayoutManager()
+ }
+ }
+
+ private fun setupGridLayoutManager() {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ if (config.scrollHorizontally) {
+ layoutManager.orientation = RecyclerView.HORIZONTAL
+ media_grid.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
+ } else {
+ layoutManager.orientation = RecyclerView.VERTICAL
+ media_grid.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+ }
+
+ layoutManager.spanCount = config.mediaColumnCnt
+ val adapter = getMediaAdapter()
+ layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
+ override fun getSpanSize(position: Int): Int {
+ return if (adapter?.isASectionTitle(position) == true) {
+ layoutManager.spanCount
+ } else {
+ 1
+ }
+ }
+ }
+ }
+
+ private fun setupListLayoutManager() {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ layoutManager.spanCount = 1
+ layoutManager.orientation = RecyclerView.VERTICAL
+ }
+
+ private fun setupScrollDirection() {
+ val viewType = config.getFolderViewType(SHOW_ALL)
+ val allowHorizontalScroll = config.scrollHorizontally && viewType == VIEW_TYPE_GRID
+ media_vertical_fastscroller.isHorizontal = false
+ media_vertical_fastscroller.beGoneIf(allowHorizontalScroll)
+
+ media_horizontal_fastscroller.isHorizontal = true
+ media_horizontal_fastscroller.beVisibleIf(allowHorizontalScroll)
+
+ val sorting = config.getFolderSorting(SHOW_ALL)
+ if (allowHorizontalScroll) {
+ media_horizontal_fastscroller.setViews(media_grid) {
+ media_horizontal_fastscroller.updateBubbleText(getBubbleTextItem(it, sorting))
+ }
+ } else {
+ media_vertical_fastscroller.setViews(media_grid) {
+ media_vertical_fastscroller.updateBubbleText(getBubbleTextItem(it, sorting))
+ }
+ }
+ }
+
+ private fun getBubbleTextItem(index: Int, sorting: Int): String {
+ var realIndex = index
+ val mediaAdapter = getMediaAdapter()
+ if (mediaAdapter?.isASectionTitle(index) == true) {
+ realIndex++
+ }
+ return mediaAdapter?.getItemBubbleText(realIndex, sorting, mDateFormat, mTimeFormat) ?: ""
+ }
+
+ private fun measureRecyclerViewContent(media: ArrayList) {
+ media_grid.onGlobalLayout {
+ if (config.scrollHorizontally) {
+ calculateContentWidth(media)
+ } else {
+ calculateContentHeight(media)
+ }
+ }
+ }
+
+ private fun calculateContentWidth(media: ArrayList) {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ val thumbnailWidth = layoutManager.getChildAt(0)?.width ?: 0
+ val fullWidth = ((media.size - 1) / layoutManager.spanCount + 1) * thumbnailWidth
+ media_horizontal_fastscroller.setContentWidth(fullWidth)
+ media_horizontal_fastscroller.setScrollToX(media_grid.computeHorizontalScrollOffset())
+ }
+
+ private fun calculateContentHeight(media: ArrayList) {
+ val layoutManager = media_grid.layoutManager as MyGridLayoutManager
+ val pathToCheck = SHOW_ALL
+ val hasSections = config.getFolderGrouping(pathToCheck) and GROUP_BY_NONE == 0 && !config.scrollHorizontally
+ val sectionTitleHeight = if (hasSections) layoutManager.getChildAt(0)?.height ?: 0 else 0
+ val thumbnailHeight = if (hasSections) layoutManager.getChildAt(1)?.height ?: 0 else layoutManager.getChildAt(0)?.height ?: 0
+
+ var fullHeight = 0
+ var curSectionItems = 0
+ media.forEach {
+ if (it is ThumbnailSection) {
+ fullHeight += sectionTitleHeight
+ if (curSectionItems != 0) {
+ val rows = ((curSectionItems - 1) / layoutManager.spanCount + 1)
+ fullHeight += rows * thumbnailHeight
+ }
+ curSectionItems = 0
+ } else {
+ curSectionItems++
+ }
+ }
+
+ fullHeight += ((curSectionItems - 1) / layoutManager.spanCount + 1) * thumbnailHeight
+ media_vertical_fastscroller.setContentHeight(fullHeight)
+ media_vertical_fastscroller.setScrollToY(media_grid.computeVerticalScrollOffset())
+ }
+
+ private fun getAllMedia() {
+ getCachedMedia("") {
+ if (it.isNotEmpty()) {
+ mAllMedia = it.clone() as ArrayList
+ }
+ runOnUiThread {
+ setupAdapter()
+ }
+ startAsyncTask(false)
+ }
+ }
+
+ private fun startAsyncTask(updateItems: Boolean) {
+ mCurrAsyncTask?.stopFetching()
+ mCurrAsyncTask = GetMediaAsynctask(applicationContext, "", showAll = true) {
+ mAllMedia = it.clone() as ArrayList
+ if (updateItems) {
+ textChanged(mLastSearchedText)
+ }
+ }
+
+ mCurrAsyncTask!!.execute()
+ }
+
+ override fun refreshItems() {
+ startAsyncTask(true)
+ }
+
+ override fun tryDeleteFiles(fileDirItems: ArrayList) {
+ val filtered = fileDirItems.filter { File(it.path).isFile && it.path.isMediaFile() } as ArrayList
+ if (filtered.isEmpty()) {
+ return
+ }
+
+ if (config.useRecycleBin && !filtered.first().path.startsWith(recycleBinPath)) {
+ val movingItems = resources.getQuantityString(R.plurals.moving_items_into_bin, filtered.size, filtered.size)
+ toast(movingItems)
+
+ movePathsInRecycleBin(filtered.map { it.path } as ArrayList) {
+ if (it) {
+ deleteFilteredFiles(filtered)
+ } else {
+ toast(R.string.unknown_error_occurred)
+ }
+ }
+ } else {
+ val deletingItems = resources.getQuantityString(R.plurals.deleting_items, filtered.size, filtered.size)
+ toast(deletingItems)
+ deleteFilteredFiles(filtered)
+ }
+ }
+
+ private fun deleteFilteredFiles(filtered: ArrayList) {
+ deleteFiles(filtered) {
+ if (!it) {
+ toast(R.string.unknown_error_occurred)
+ return@deleteFiles
+ }
+
+ mAllMedia.removeAll { filtered.map { it.path }.contains((it as? Medium)?.path) }
+
+ ensureBackgroundThread {
+ val useRecycleBin = config.useRecycleBin
+ filtered.forEach {
+ if (it.path.startsWith(recycleBinPath) || !useRecycleBin) {
+ deleteDBPath(it.path)
+ }
+ }
+ }
+ }
+ }
+
+ override fun selectedPaths(paths: ArrayList) {
+ }
+
+ override fun updateMediaGridDecoration(media: ArrayList) {
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SetWallpaperActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SetWallpaperActivity.kt
similarity index 58%
rename from app/src/main/kotlin/com/simplemobiletools/gallery/activities/SetWallpaperActivity.kt
rename to app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SetWallpaperActivity.kt
index 9d2fddb3c..a6941c2b4 100644
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/SetWallpaperActivity.kt
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SetWallpaperActivity.kt
@@ -1,29 +1,40 @@
-package com.simplemobiletools.gallery.activities
+package com.simplemobiletools.gallery.pro.activities
+import android.annotation.SuppressLint
import android.app.Activity
import android.app.WallpaperManager
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
-import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
+import com.simplemobiletools.commons.dialogs.RadioGroupDialog
+import com.simplemobiletools.commons.extensions.checkAppSideloading
import com.simplemobiletools.commons.extensions.toast
-import com.simplemobiletools.gallery.R
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.commons.helpers.isNougatPlus
+import com.simplemobiletools.commons.models.RadioItem
+import com.simplemobiletools.gallery.pro.R
import com.theartofdev.edmodo.cropper.CropImageView
-import kotlinx.android.synthetic.main.view_crop_image.*
+import kotlinx.android.synthetic.main.activity_set_wallpaper.*
+import kotlinx.android.synthetic.main.bottom_set_wallpaper_actions.*
class SetWallpaperActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener {
private val PICK_IMAGE = 1
private var isLandscapeRatio = true
+ private var wallpaperFlag = -1
lateinit var uri: Uri
lateinit var wallpaperManager: WallpaperManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- setContentView(R.layout.view_crop_image)
+ setContentView(R.layout.activity_set_wallpaper)
+
+ if (checkAppSideloading()) {
+ return
+ }
if (intent.data == null) {
val pickIntent = Intent(applicationContext, MainActivity::class.java)
@@ -34,10 +45,25 @@ class SetWallpaperActivity : SimpleActivity(), CropImageView.OnCropImageComplete
}
handleImage(intent)
+ setupBottomActions()
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_set_wallpaper, menu)
+ updateMenuItemColors(menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.save -> confirmWallpaper()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
}
private fun handleImage(intent: Intent) {
- uri = intent.data
+ uri = intent.data!!
if (uri.scheme != "file" && uri.scheme != "content") {
toast(R.string.unknown_file_location)
finish()
@@ -53,56 +79,70 @@ class SetWallpaperActivity : SimpleActivity(), CropImageView.OnCropImageComplete
setupAspectRatio()
}
+ private fun setupBottomActions() {
+ bottom_set_wallpaper_aspect_ratio.setOnClickListener {
+ changeAspectRatio(!isLandscapeRatio)
+ }
+
+ bottom_set_wallpaper_rotate.setOnClickListener {
+ crop_image_view.rotateImage(90)
+ }
+ }
+
private fun setupAspectRatio() {
val wallpaperWidth = if (isLandscapeRatio) wallpaperManager.desiredMinimumWidth else wallpaperManager.desiredMinimumWidth / 2
crop_image_view.setAspectRatio(wallpaperWidth, wallpaperManager.desiredMinimumHeight)
- }
-
- override fun onCreateOptionsMenu(menu: Menu): Boolean {
- menuInflater.inflate(R.menu.menu_set_wallpaper, menu)
-
- menu.findItem(R.id.portrait_aspect_ratio).isVisible = isLandscapeRatio
- menu.findItem(R.id.landscape_aspect_ratio).isVisible = !isLandscapeRatio
- return true
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- when (item.itemId) {
- R.id.save -> crop_image_view.getCroppedImageAsync()
- R.id.rotate -> crop_image_view.rotateImage(90)
- R.id.portrait_aspect_ratio -> changeAspectRatio(false)
- R.id.landscape_aspect_ratio -> changeAspectRatio(true)
- else -> return super.onOptionsItemSelected(item)
- }
- return true
+ bottom_set_wallpaper_aspect_ratio.setImageResource(if (isLandscapeRatio) R.drawable.ic_minimize else R.drawable.ic_maximize)
}
private fun changeAspectRatio(isLandscape: Boolean) {
isLandscapeRatio = isLandscape
setupAspectRatio()
- invalidateOptionsMenu()
}
+ @SuppressLint("InlinedApi")
+ private fun confirmWallpaper() {
+ if (isNougatPlus()) {
+ val items = arrayListOf(
+ RadioItem(WallpaperManager.FLAG_SYSTEM, getString(R.string.home_screen)),
+ RadioItem(WallpaperManager.FLAG_LOCK, getString(R.string.lock_screen)),
+ RadioItem(WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK, getString(R.string.home_and_lock_screen)))
+
+ RadioGroupDialog(this, items) {
+ wallpaperFlag = it as Int
+ crop_image_view.getCroppedImageAsync()
+ }
+ } else {
+ crop_image_view.getCroppedImageAsync()
+ }
+ }
+
+ @SuppressLint("NewApi")
override fun onCropImageComplete(view: CropImageView?, result: CropImageView.CropResult) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed)
+ if (isDestroyed)
return
if (result.error == null) {
toast(R.string.setting_wallpaper)
- Thread({
+ ensureBackgroundThread {
val bitmap = result.bitmap
val wantedHeight = wallpaperManager.desiredMinimumHeight
val ratio = wantedHeight / bitmap.height.toFloat()
val wantedWidth = (bitmap.width * ratio).toInt()
try {
- wallpaperManager.setBitmap(Bitmap.createScaledBitmap(bitmap, wantedWidth, wantedHeight, true))
+ val scaledBitmap = Bitmap.createScaledBitmap(bitmap, wantedWidth, wantedHeight, true)
+ if (isNougatPlus()) {
+ wallpaperManager.setBitmap(scaledBitmap, null, true, wallpaperFlag)
+ } else {
+ wallpaperManager.setBitmap(scaledBitmap)
+ }
setResult(Activity.RESULT_OK)
} catch (e: OutOfMemoryError) {
toast(R.string.out_of_memory_error)
setResult(Activity.RESULT_CANCELED)
}
finish()
- }).start()
+ }
} else {
toast("${getString(R.string.image_editing_failed)}: ${result.error.message}")
}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SettingsActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SettingsActivity.kt
new file mode 100644
index 000000000..45279a23d
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SettingsActivity.kt
@@ -0,0 +1,852 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.app.Activity
+import android.content.Intent
+import android.os.Bundle
+import android.text.TextUtils
+import android.view.Menu
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.simplemobiletools.commons.dialogs.*
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.*
+import com.simplemobiletools.commons.models.RadioItem
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.dialogs.ChangeFileThumbnailStyleDialog
+import com.simplemobiletools.gallery.pro.dialogs.ChangeFolderThumbnailStyleDialog
+import com.simplemobiletools.gallery.pro.dialogs.ManageBottomActionsDialog
+import com.simplemobiletools.gallery.pro.dialogs.ManageExtendedDetailsDialog
+import com.simplemobiletools.gallery.pro.extensions.config
+import com.simplemobiletools.gallery.pro.extensions.emptyTheRecycleBin
+import com.simplemobiletools.gallery.pro.extensions.mediaDB
+import com.simplemobiletools.gallery.pro.extensions.showRecycleBinEmptyingDialog
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.models.AlbumCover
+import kotlinx.android.synthetic.main.activity_settings.*
+import java.io.File
+import java.io.InputStream
+import java.util.*
+
+class SettingsActivity : SimpleActivity() {
+ private val PICK_IMPORT_SOURCE_INTENT = 1
+ private var mRecycleBinContentSize = 0L
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_settings)
+ }
+
+ override fun onResume() {
+ super.onResume()
+ setupSettingItems()
+ }
+
+ private fun setupSettingItems() {
+ setupCustomizeColors()
+ setupUseEnglish()
+ setupChangeDateTimeFormat()
+ setupFileLoadingPriority()
+ setupManageIncludedFolders()
+ setupManageExcludedFolders()
+ setupManageHiddenFolders()
+ setupShowHiddenItems()
+ setupAutoplayVideos()
+ setupRememberLastVideo()
+ setupLoopVideos()
+ setupOpenVideosOnSeparateScreen()
+ setupMaxBrightness()
+ setupCropThumbnails()
+ setupDarkBackground()
+ setupScrollHorizontally()
+ setupScreenRotation()
+ setupHideSystemUI()
+ setupHiddenItemPasswordProtection()
+ setupAppPasswordProtection()
+ setupFileDeletionPasswordProtection()
+ setupDeleteEmptyFolders()
+ setupAllowDownGesture()
+ setupAllowRotatingWithGestures()
+ setupShowNotch()
+ setupBottomActions()
+ setupFileThumbnailStyle()
+ setupFolderThumbnailStyle()
+ setupKeepLastModified()
+ setupEnablePullToRefresh()
+ setupAllowZoomingImages()
+ setupShowHighestQuality()
+ setupAllowOneToOneZoom()
+ setupAllowInstantChange()
+ setupShowExtendedDetails()
+ setupHideExtendedDetails()
+ setupManageExtendedDetails()
+ setupSkipDeleteConfirmation()
+ setupManageBottomActions()
+ setupUseRecycleBin()
+ setupShowRecycleBin()
+ setupShowRecycleBinLast()
+ setupEmptyRecycleBin()
+ updateTextColors(settings_holder)
+ setupSectionColors()
+ setupClearCache()
+ setupExportSettings()
+ setupImportSettings()
+ invalidateOptionsMenu()
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ updateMenuItemColors(menu)
+ return super.onCreateOptionsMenu(menu)
+ }
+
+ override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
+ super.onActivityResult(requestCode, resultCode, resultData)
+ if (requestCode == PICK_IMPORT_SOURCE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
+ val inputStream = contentResolver.openInputStream(resultData.data!!)
+ parseFile(inputStream)
+ }
+ }
+
+ private fun setupSectionColors() {
+ val adjustedPrimaryColor = getAdjustedPrimaryColor()
+ arrayListOf(visibility_label, videos_label, thumbnails_label, scrolling_label, fullscreen_media_label, security_label,
+ file_operations_label, deep_zoomable_images_label, extended_details_label, bottom_actions_label, recycle_bin_label,
+ migrating_label).forEach {
+ it.setTextColor(adjustedPrimaryColor)
+ }
+ }
+
+ private fun setupCustomizeColors() {
+ settings_customize_colors_holder.setOnClickListener {
+ startCustomizationActivity()
+ }
+ }
+
+ private fun setupUseEnglish() {
+ settings_use_english_holder.beVisibleIf(config.wasUseEnglishToggled || Locale.getDefault().language != "en")
+ settings_use_english.isChecked = config.useEnglish
+ settings_use_english_holder.setOnClickListener {
+ settings_use_english.toggle()
+ config.useEnglish = settings_use_english.isChecked
+ System.exit(0)
+ }
+ }
+
+ private fun setupChangeDateTimeFormat() {
+ settings_change_date_time_format_holder.setOnClickListener {
+ ChangeDateTimeFormatDialog(this) {}
+ }
+ }
+
+ private fun setupFileLoadingPriority() {
+ settings_file_loading_priority.text = getFileLoadingPriorityText()
+ settings_file_loading_priority_holder.setOnClickListener {
+ val items = arrayListOf(
+ RadioItem(PRIORITY_SPEED, getString(R.string.speed)),
+ RadioItem(PRIORITY_COMPROMISE, getString(R.string.compromise)),
+ RadioItem(PRIORITY_VALIDITY, getString(R.string.avoid_showing_invalid_files)))
+
+ RadioGroupDialog(this@SettingsActivity, items, config.fileLoadingPriority) {
+ config.fileLoadingPriority = it as Int
+ settings_file_loading_priority.text = getFileLoadingPriorityText()
+ }
+ }
+ }
+
+ private fun getFileLoadingPriorityText() = getString(when (config.fileLoadingPriority) {
+ PRIORITY_SPEED -> R.string.speed
+ PRIORITY_COMPROMISE -> R.string.compromise
+ else -> R.string.avoid_showing_invalid_files
+ })
+
+ private fun setupManageIncludedFolders() {
+ settings_manage_included_folders_holder.setOnClickListener {
+ startActivity(Intent(this, IncludedFoldersActivity::class.java))
+ }
+ }
+
+ private fun setupManageExcludedFolders() {
+ settings_manage_excluded_folders_holder.setOnClickListener {
+ startActivity(Intent(this, ExcludedFoldersActivity::class.java))
+ }
+ }
+
+ private fun setupManageHiddenFolders() {
+ settings_manage_hidden_folders_holder.beVisibleIf(!isQPlus())
+ settings_manage_hidden_folders_holder.setOnClickListener {
+ handleHiddenFolderPasswordProtection {
+ startActivity(Intent(this, HiddenFoldersActivity::class.java))
+ }
+ }
+ }
+
+ private fun setupShowHiddenItems() {
+ settings_show_hidden_items.isChecked = config.showHiddenMedia
+ settings_show_hidden_items_holder.setOnClickListener {
+ if (config.showHiddenMedia) {
+ toggleHiddenItems()
+ } else {
+ handleHiddenFolderPasswordProtection {
+ toggleHiddenItems()
+ }
+ }
+ }
+ }
+
+ private fun toggleHiddenItems() {
+ settings_show_hidden_items.toggle()
+ config.showHiddenMedia = settings_show_hidden_items.isChecked
+ }
+
+ private fun setupAutoplayVideos() {
+ settings_autoplay_videos.isChecked = config.autoplayVideos
+ settings_autoplay_videos_holder.setOnClickListener {
+ settings_autoplay_videos.toggle()
+ config.autoplayVideos = settings_autoplay_videos.isChecked
+ }
+ }
+
+ private fun setupRememberLastVideo() {
+ settings_remember_last_video_position.isChecked = config.rememberLastVideoPosition
+ settings_remember_last_video_position_holder.setOnClickListener {
+ settings_remember_last_video_position.toggle()
+ config.rememberLastVideoPosition = settings_remember_last_video_position.isChecked
+ }
+ }
+
+ private fun setupLoopVideos() {
+ settings_loop_videos.isChecked = config.loopVideos
+ settings_loop_videos_holder.setOnClickListener {
+ settings_loop_videos.toggle()
+ config.loopVideos = settings_loop_videos.isChecked
+ }
+ }
+
+ private fun setupOpenVideosOnSeparateScreen() {
+ settings_open_videos_on_separate_screen.isChecked = config.openVideosOnSeparateScreen
+ settings_open_videos_on_separate_screen_holder.setOnClickListener {
+ settings_open_videos_on_separate_screen.toggle()
+ config.openVideosOnSeparateScreen = settings_open_videos_on_separate_screen.isChecked
+ }
+ }
+
+ private fun setupMaxBrightness() {
+ settings_max_brightness.isChecked = config.maxBrightness
+ settings_max_brightness_holder.setOnClickListener {
+ settings_max_brightness.toggle()
+ config.maxBrightness = settings_max_brightness.isChecked
+ }
+ }
+
+ private fun setupCropThumbnails() {
+ settings_crop_thumbnails.isChecked = config.cropThumbnails
+ settings_crop_thumbnails_holder.setOnClickListener {
+ settings_crop_thumbnails.toggle()
+ config.cropThumbnails = settings_crop_thumbnails.isChecked
+ }
+ }
+
+ private fun setupDarkBackground() {
+ settings_black_background.isChecked = config.blackBackground
+ settings_black_background_holder.setOnClickListener {
+ settings_black_background.toggle()
+ config.blackBackground = settings_black_background.isChecked
+ }
+ }
+
+ private fun setupScrollHorizontally() {
+ settings_scroll_horizontally.isChecked = config.scrollHorizontally
+ settings_scroll_horizontally_holder.setOnClickListener {
+ settings_scroll_horizontally.toggle()
+ config.scrollHorizontally = settings_scroll_horizontally.isChecked
+
+ if (config.scrollHorizontally) {
+ config.enablePullToRefresh = false
+ settings_enable_pull_to_refresh.isChecked = false
+ }
+ }
+ }
+
+ private fun setupHideSystemUI() {
+ settings_hide_system_ui.isChecked = config.hideSystemUI
+ settings_hide_system_ui_holder.setOnClickListener {
+ settings_hide_system_ui.toggle()
+ config.hideSystemUI = settings_hide_system_ui.isChecked
+ }
+ }
+
+ private fun setupHiddenItemPasswordProtection() {
+ settings_hidden_item_password_protection.isChecked = config.isHiddenPasswordProtectionOn
+ settings_hidden_item_password_protection_holder.setOnClickListener {
+ val tabToShow = if (config.isHiddenPasswordProtectionOn) config.hiddenProtectionType else SHOW_ALL_TABS
+ SecurityDialog(this, config.hiddenPasswordHash, tabToShow) { hash, type, success ->
+ if (success) {
+ val hasPasswordProtection = config.isHiddenPasswordProtectionOn
+ settings_hidden_item_password_protection.isChecked = !hasPasswordProtection
+ config.isHiddenPasswordProtectionOn = !hasPasswordProtection
+ config.hiddenPasswordHash = if (hasPasswordProtection) "" else hash
+ config.hiddenProtectionType = type
+
+ if (config.isHiddenPasswordProtectionOn) {
+ val confirmationTextId = if (config.hiddenProtectionType == PROTECTION_FINGERPRINT)
+ R.string.fingerprint_setup_successfully else R.string.protection_setup_successfully
+ ConfirmationDialog(this, "", confirmationTextId, R.string.ok, 0) { }
+ }
+ }
+ }
+ }
+ }
+
+ private fun setupAppPasswordProtection() {
+ settings_app_password_protection.isChecked = config.isAppPasswordProtectionOn
+ settings_app_password_protection_holder.setOnClickListener {
+ val tabToShow = if (config.isAppPasswordProtectionOn) config.appProtectionType else SHOW_ALL_TABS
+ SecurityDialog(this, config.appPasswordHash, tabToShow) { hash, type, success ->
+ if (success) {
+ val hasPasswordProtection = config.isAppPasswordProtectionOn
+ settings_app_password_protection.isChecked = !hasPasswordProtection
+ config.isAppPasswordProtectionOn = !hasPasswordProtection
+ config.appPasswordHash = if (hasPasswordProtection) "" else hash
+ config.appProtectionType = type
+
+ if (config.isAppPasswordProtectionOn) {
+ val confirmationTextId = if (config.appProtectionType == PROTECTION_FINGERPRINT)
+ R.string.fingerprint_setup_successfully else R.string.protection_setup_successfully
+ ConfirmationDialog(this, "", confirmationTextId, R.string.ok, 0) { }
+ }
+ }
+ }
+ }
+ }
+
+ private fun setupFileDeletionPasswordProtection() {
+ settings_file_deletion_password_protection.isChecked = config.isDeletePasswordProtectionOn
+ settings_file_deletion_password_protection_holder.setOnClickListener {
+ val tabToShow = if (config.isDeletePasswordProtectionOn) config.deleteProtectionType else SHOW_ALL_TABS
+ SecurityDialog(this, config.deletePasswordHash, tabToShow) { hash, type, success ->
+ if (success) {
+ val hasPasswordProtection = config.isDeletePasswordProtectionOn
+ settings_file_deletion_password_protection.isChecked = !hasPasswordProtection
+ config.isDeletePasswordProtectionOn = !hasPasswordProtection
+ config.deletePasswordHash = if (hasPasswordProtection) "" else hash
+ config.deleteProtectionType = type
+
+ if (config.isDeletePasswordProtectionOn) {
+ val confirmationTextId = if (config.deleteProtectionType == PROTECTION_FINGERPRINT)
+ R.string.fingerprint_setup_successfully else R.string.protection_setup_successfully
+ ConfirmationDialog(this, "", confirmationTextId, R.string.ok, 0) { }
+ }
+ }
+ }
+ }
+ }
+
+ private fun setupDeleteEmptyFolders() {
+ settings_delete_empty_folders.isChecked = config.deleteEmptyFolders
+ settings_delete_empty_folders_holder.setOnClickListener {
+ settings_delete_empty_folders.toggle()
+ config.deleteEmptyFolders = settings_delete_empty_folders.isChecked
+ }
+ }
+
+ private fun setupAllowDownGesture() {
+ settings_allow_down_gesture.isChecked = config.allowDownGesture
+ settings_allow_down_gesture_holder.setOnClickListener {
+ settings_allow_down_gesture.toggle()
+ config.allowDownGesture = settings_allow_down_gesture.isChecked
+ }
+ }
+
+ private fun setupAllowRotatingWithGestures() {
+ settings_allow_rotating_with_gestures.isChecked = config.allowRotatingWithGestures
+ settings_allow_rotating_with_gestures_holder.setOnClickListener {
+ settings_allow_rotating_with_gestures.toggle()
+ config.allowRotatingWithGestures = settings_allow_rotating_with_gestures.isChecked
+ }
+ }
+
+ private fun setupShowNotch() {
+ settings_show_notch_holder.beVisibleIf(isPiePlus())
+ settings_show_notch.isChecked = config.showNotch
+ settings_show_notch_holder.setOnClickListener {
+ settings_show_notch.toggle()
+ config.showNotch = settings_show_notch.isChecked
+ }
+ }
+
+ private fun setupFileThumbnailStyle() {
+ settings_file_thumbnail_style_holder.setOnClickListener {
+ ChangeFileThumbnailStyleDialog(this)
+ }
+ }
+
+ private fun setupFolderThumbnailStyle() {
+ settings_folder_thumbnail_style.text = getFolderStyleText()
+ settings_folder_thumbnail_style_holder.setOnClickListener {
+ ChangeFolderThumbnailStyleDialog(this) {
+ settings_folder_thumbnail_style.text = getFolderStyleText()
+ }
+ }
+ }
+
+ private fun getFolderStyleText() = getString(when (config.folderStyle) {
+ FOLDER_STYLE_SQUARE -> R.string.square
+ else -> R.string.rounded_corners
+ })
+
+ private fun setupKeepLastModified() {
+ settings_keep_last_modified.isChecked = config.keepLastModified
+ settings_keep_last_modified_holder.setOnClickListener {
+ settings_keep_last_modified.toggle()
+ config.keepLastModified = settings_keep_last_modified.isChecked
+ }
+ }
+
+ private fun setupEnablePullToRefresh() {
+ settings_enable_pull_to_refresh.isChecked = config.enablePullToRefresh
+ settings_enable_pull_to_refresh_holder.setOnClickListener {
+ settings_enable_pull_to_refresh.toggle()
+ config.enablePullToRefresh = settings_enable_pull_to_refresh.isChecked
+ }
+ }
+
+ private fun setupAllowZoomingImages() {
+ settings_allow_zooming_images.isChecked = config.allowZoomingImages
+ updateDeepZoomToggleButtons()
+ settings_allow_zooming_images_holder.setOnClickListener {
+ settings_allow_zooming_images.toggle()
+ config.allowZoomingImages = settings_allow_zooming_images.isChecked
+ updateDeepZoomToggleButtons()
+ }
+ }
+
+ private fun updateDeepZoomToggleButtons() {
+ settings_allow_rotating_with_gestures_holder.beVisibleIf(config.allowZoomingImages)
+ settings_show_highest_quality_holder.beVisibleIf(config.allowZoomingImages)
+ settings_allow_one_to_one_zoom_holder.beVisibleIf(config.allowZoomingImages)
+ }
+
+ private fun setupShowHighestQuality() {
+ settings_show_highest_quality.isChecked = config.showHighestQuality
+ settings_show_highest_quality_holder.setOnClickListener {
+ settings_show_highest_quality.toggle()
+ config.showHighestQuality = settings_show_highest_quality.isChecked
+ }
+ }
+
+ private fun setupAllowOneToOneZoom() {
+ settings_allow_one_to_one_zoom.isChecked = config.allowOneToOneZoom
+ settings_allow_one_to_one_zoom_holder.setOnClickListener {
+ settings_allow_one_to_one_zoom.toggle()
+ config.allowOneToOneZoom = settings_allow_one_to_one_zoom.isChecked
+ }
+ }
+
+ private fun setupAllowInstantChange() {
+ settings_allow_instant_change.isChecked = config.allowInstantChange
+ settings_allow_instant_change_holder.setOnClickListener {
+ settings_allow_instant_change.toggle()
+ config.allowInstantChange = settings_allow_instant_change.isChecked
+ }
+ }
+
+ private fun setupShowExtendedDetails() {
+ settings_show_extended_details.isChecked = config.showExtendedDetails
+ settings_show_extended_details_holder.setOnClickListener {
+ settings_show_extended_details.toggle()
+ config.showExtendedDetails = settings_show_extended_details.isChecked
+ settings_manage_extended_details_holder.beVisibleIf(config.showExtendedDetails)
+ settings_hide_extended_details_holder.beVisibleIf(config.showExtendedDetails)
+ }
+ }
+
+ private fun setupHideExtendedDetails() {
+ settings_hide_extended_details_holder.beVisibleIf(config.showExtendedDetails)
+ settings_hide_extended_details.isChecked = config.hideExtendedDetails
+ settings_hide_extended_details_holder.setOnClickListener {
+ settings_hide_extended_details.toggle()
+ config.hideExtendedDetails = settings_hide_extended_details.isChecked
+ }
+ }
+
+ private fun setupManageExtendedDetails() {
+ settings_manage_extended_details_holder.beVisibleIf(config.showExtendedDetails)
+ settings_manage_extended_details_holder.setOnClickListener {
+ ManageExtendedDetailsDialog(this) {
+ if (config.extendedDetails == 0) {
+ settings_show_extended_details_holder.callOnClick()
+ }
+ }
+ }
+ }
+
+ private fun setupSkipDeleteConfirmation() {
+ settings_skip_delete_confirmation.isChecked = config.skipDeleteConfirmation
+ settings_skip_delete_confirmation_holder.setOnClickListener {
+ settings_skip_delete_confirmation.toggle()
+ config.skipDeleteConfirmation = settings_skip_delete_confirmation.isChecked
+ }
+ }
+
+ private fun setupScreenRotation() {
+ settings_screen_rotation.text = getScreenRotationText()
+ settings_screen_rotation_holder.setOnClickListener {
+ val items = arrayListOf(
+ RadioItem(ROTATE_BY_SYSTEM_SETTING, getString(R.string.screen_rotation_system_setting)),
+ RadioItem(ROTATE_BY_DEVICE_ROTATION, getString(R.string.screen_rotation_device_rotation)),
+ RadioItem(ROTATE_BY_ASPECT_RATIO, getString(R.string.screen_rotation_aspect_ratio)))
+
+ RadioGroupDialog(this@SettingsActivity, items, config.screenRotation) {
+ config.screenRotation = it as Int
+ settings_screen_rotation.text = getScreenRotationText()
+ }
+ }
+ }
+
+ private fun getScreenRotationText() = getString(when (config.screenRotation) {
+ ROTATE_BY_SYSTEM_SETTING -> R.string.screen_rotation_system_setting
+ ROTATE_BY_DEVICE_ROTATION -> R.string.screen_rotation_device_rotation
+ else -> R.string.screen_rotation_aspect_ratio
+ })
+
+ private fun setupBottomActions() {
+ settings_bottom_actions.isChecked = config.bottomActions
+ settings_bottom_actions_holder.setOnClickListener {
+ settings_bottom_actions.toggle()
+ config.bottomActions = settings_bottom_actions.isChecked
+ settings_manage_bottom_actions_holder.beVisibleIf(config.bottomActions)
+ }
+ }
+
+ private fun setupManageBottomActions() {
+ settings_manage_bottom_actions_holder.beVisibleIf(config.bottomActions)
+ settings_manage_bottom_actions_holder.setOnClickListener {
+ ManageBottomActionsDialog(this) {
+ if (config.visibleBottomActions == 0) {
+ settings_bottom_actions_holder.callOnClick()
+ config.bottomActions = false
+ config.visibleBottomActions = DEFAULT_BOTTOM_ACTIONS
+ }
+ }
+ }
+ }
+
+ private fun setupUseRecycleBin() {
+ settings_empty_recycle_bin_holder.beVisibleIf(config.useRecycleBin)
+ settings_show_recycle_bin_holder.beVisibleIf(config.useRecycleBin)
+ settings_show_recycle_bin_last_holder.beVisibleIf(config.useRecycleBin && config.showRecycleBinAtFolders)
+ settings_use_recycle_bin.isChecked = config.useRecycleBin
+ settings_use_recycle_bin_holder.setOnClickListener {
+ settings_use_recycle_bin.toggle()
+ config.useRecycleBin = settings_use_recycle_bin.isChecked
+ settings_empty_recycle_bin_holder.beVisibleIf(config.useRecycleBin)
+ settings_show_recycle_bin_holder.beVisibleIf(config.useRecycleBin)
+ settings_show_recycle_bin_last_holder.beVisibleIf(config.useRecycleBin && config.showRecycleBinAtFolders)
+ }
+ }
+
+ private fun setupShowRecycleBin() {
+ settings_show_recycle_bin.isChecked = config.showRecycleBinAtFolders
+ settings_show_recycle_bin_holder.setOnClickListener {
+ settings_show_recycle_bin.toggle()
+ config.showRecycleBinAtFolders = settings_show_recycle_bin.isChecked
+ settings_show_recycle_bin_last_holder.beVisibleIf(config.useRecycleBin && config.showRecycleBinAtFolders)
+ }
+ }
+
+ private fun setupShowRecycleBinLast() {
+ settings_show_recycle_bin_last.isChecked = config.showRecycleBinLast
+ settings_show_recycle_bin_last_holder.setOnClickListener {
+ settings_show_recycle_bin_last.toggle()
+ config.showRecycleBinLast = settings_show_recycle_bin_last.isChecked
+ if (config.showRecycleBinLast) {
+ config.removePinnedFolders(setOf(RECYCLE_BIN))
+ }
+ }
+ }
+
+ private fun setupEmptyRecycleBin() {
+ ensureBackgroundThread {
+ try {
+ mRecycleBinContentSize = mediaDB.getDeletedMedia().sumByLong { it.size }
+ } catch (ignored: Exception) {
+ }
+ runOnUiThread {
+ settings_empty_recycle_bin_size.text = mRecycleBinContentSize.formatSize()
+ }
+ }
+
+ settings_empty_recycle_bin_holder.setOnClickListener {
+ if (mRecycleBinContentSize == 0L) {
+ toast(R.string.recycle_bin_empty)
+ } else {
+ showRecycleBinEmptyingDialog {
+ emptyTheRecycleBin()
+ mRecycleBinContentSize = 0L
+ settings_empty_recycle_bin_size.text = 0L.formatSize()
+ }
+ }
+ }
+ }
+
+ private fun setupClearCache() {
+ ensureBackgroundThread {
+ runOnUiThread {
+ settings_clear_cache_size.text = cacheDir.getProperSize(true).formatSize()
+ }
+ }
+
+ settings_clear_cache_holder.setOnClickListener {
+ ensureBackgroundThread {
+ cacheDir.deleteRecursively()
+ runOnUiThread {
+ settings_clear_cache_size.text = cacheDir.getProperSize(true).formatSize()
+ }
+ }
+ }
+ }
+
+ private fun setupExportSettings() {
+ settings_export_holder.setOnClickListener {
+ val configItems = LinkedHashMap().apply {
+ put(IS_USING_SHARED_THEME, config.isUsingSharedTheme)
+ put(TEXT_COLOR, config.textColor)
+ put(BACKGROUND_COLOR, config.backgroundColor)
+ put(PRIMARY_COLOR, config.primaryColor)
+ put(APP_ICON_COLOR, config.appIconColor)
+ put(USE_ENGLISH, config.useEnglish)
+ put(WAS_USE_ENGLISH_TOGGLED, config.wasUseEnglishToggled)
+ put(WIDGET_BG_COLOR, config.widgetBgColor)
+ put(WIDGET_TEXT_COLOR, config.widgetTextColor)
+ put(DATE_FORMAT, config.dateFormat)
+ put(USE_24_HOUR_FORMAT, config.use24HourFormat)
+ put(INCLUDED_FOLDERS, TextUtils.join(",", config.includedFolders))
+ put(EXCLUDED_FOLDERS, TextUtils.join(",", config.excludedFolders))
+ put(SHOW_HIDDEN_MEDIA, config.showHiddenMedia)
+ put(FILE_LOADING_PRIORITY, config.fileLoadingPriority)
+ put(AUTOPLAY_VIDEOS, config.autoplayVideos)
+ put(REMEMBER_LAST_VIDEO_POSITION, config.rememberLastVideoPosition)
+ put(LOOP_VIDEOS, config.loopVideos)
+ put(OPEN_VIDEOS_ON_SEPARATE_SCREEN, config.openVideosOnSeparateScreen)
+ put(ALLOW_VIDEO_GESTURES, config.allowVideoGestures)
+ put(ANIMATE_GIFS, config.animateGifs)
+ put(CROP_THUMBNAILS, config.cropThumbnails)
+ put(SHOW_THUMBNAIL_VIDEO_DURATION, config.showThumbnailVideoDuration)
+ put(SHOW_THUMBNAIL_FILE_TYPES, config.showThumbnailFileTypes)
+ put(SCROLL_HORIZONTALLY, config.scrollHorizontally)
+ put(ENABLE_PULL_TO_REFRESH, config.enablePullToRefresh)
+ put(MAX_BRIGHTNESS, config.maxBrightness)
+ put(BLACK_BACKGROUND, config.blackBackground)
+ put(HIDE_SYSTEM_UI, config.hideSystemUI)
+ put(ALLOW_INSTANT_CHANGE, config.allowInstantChange)
+ put(ALLOW_PHOTO_GESTURES, config.allowPhotoGestures)
+ put(ALLOW_DOWN_GESTURE, config.allowDownGesture)
+ put(ALLOW_ROTATING_WITH_GESTURES, config.allowRotatingWithGestures)
+ put(SHOW_NOTCH, config.showNotch)
+ put(SCREEN_ROTATION, config.screenRotation)
+ put(ALLOW_ZOOMING_IMAGES, config.allowZoomingImages)
+ put(SHOW_HIGHEST_QUALITY, config.showHighestQuality)
+ put(ALLOW_ONE_TO_ONE_ZOOM, config.allowOneToOneZoom)
+ put(SHOW_EXTENDED_DETAILS, config.showExtendedDetails)
+ put(HIDE_EXTENDED_DETAILS, config.hideExtendedDetails)
+ put(EXTENDED_DETAILS, config.extendedDetails)
+ put(DELETE_EMPTY_FOLDERS, config.deleteEmptyFolders)
+ put(KEEP_LAST_MODIFIED, config.keepLastModified)
+ put(SKIP_DELETE_CONFIRMATION, config.skipDeleteConfirmation)
+ put(BOTTOM_ACTIONS, config.bottomActions)
+ put(VISIBLE_BOTTOM_ACTIONS, config.visibleBottomActions)
+ put(USE_RECYCLE_BIN, config.useRecycleBin)
+ put(SHOW_RECYCLE_BIN_AT_FOLDERS, config.showRecycleBinAtFolders)
+ put(SHOW_RECYCLE_BIN_LAST, config.showRecycleBinLast)
+ put(SORT_ORDER, config.sorting)
+ put(DIRECTORY_SORT_ORDER, config.directorySorting)
+ put(GROUP_BY, config.groupBy)
+ put(GROUP_DIRECT_SUBFOLDERS, config.groupDirectSubfolders)
+ put(PINNED_FOLDERS, TextUtils.join(",", config.pinnedFolders))
+ put(DISPLAY_FILE_NAMES, config.displayFileNames)
+ put(FILTER_MEDIA, config.filterMedia)
+ put(DIR_COLUMN_CNT, config.dirColumnCnt)
+ put(MEDIA_COLUMN_CNT, config.mediaColumnCnt)
+ put(SHOW_ALL, config.showAll)
+ put(SHOW_WIDGET_FOLDER_NAME, config.showWidgetFolderName)
+ put(VIEW_TYPE_FILES, config.viewTypeFiles)
+ put(VIEW_TYPE_FOLDERS, config.viewTypeFolders)
+ put(SLIDESHOW_INTERVAL, config.slideshowInterval)
+ put(SLIDESHOW_INCLUDE_VIDEOS, config.slideshowIncludeVideos)
+ put(SLIDESHOW_INCLUDE_GIFS, config.slideshowIncludeGIFs)
+ put(SLIDESHOW_RANDOM_ORDER, config.slideshowRandomOrder)
+ put(SLIDESHOW_MOVE_BACKWARDS, config.slideshowMoveBackwards)
+ put(SLIDESHOW_LOOP, config.loopSlideshow)
+ put(LAST_EDITOR_CROP_ASPECT_RATIO, config.lastEditorCropAspectRatio)
+ put(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X, config.lastEditorCropOtherAspectRatioX)
+ put(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y, config.lastEditorCropOtherAspectRatioY)
+ put(LAST_CONFLICT_RESOLUTION, config.lastConflictResolution)
+ put(LAST_CONFLICT_APPLY_TO_ALL, config.lastConflictApplyToAll)
+ put(EDITOR_BRUSH_COLOR, config.editorBrushColor)
+ put(EDITOR_BRUSH_HARDNESS, config.editorBrushHardness)
+ put(EDITOR_BRUSH_SIZE, config.editorBrushSize)
+ put(ALBUM_COVERS, config.albumCovers)
+ put(FOLDER_THUMBNAIL_STYLE, config.folderStyle)
+ put(FOLDER_MEDIA_COUNT, config.showFolderMediaCount)
+ put(LIMIT_FOLDER_TITLE, config.limitFolderTitle)
+ put(THUMBNAIL_SPACING, config.thumbnailSpacing)
+ put(FILE_ROUNDED_CORNERS, config.fileRoundedCorners)
+ }
+
+ exportSettings(configItems)
+ }
+ }
+
+ private fun setupImportSettings() {
+ settings_import_holder.setOnClickListener {
+ if (isQPlus()) {
+ Intent(Intent.ACTION_GET_CONTENT).apply {
+ addCategory(Intent.CATEGORY_OPENABLE)
+ type = "text/plain"
+ startActivityForResult(this, PICK_IMPORT_SOURCE_INTENT)
+ }
+ } else {
+ handlePermission(PERMISSION_READ_STORAGE) {
+ if (it) {
+ FilePickerDialog(this) {
+ ensureBackgroundThread {
+ parseFile(File(it).inputStream())
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private fun parseFile(inputStream: InputStream?) {
+ if (inputStream == null) {
+ toast(R.string.unknown_error_occurred)
+ return
+ }
+
+ var importedItems = 0
+ val configValues = LinkedHashMap()
+ inputStream.bufferedReader().use {
+ while (true) {
+ try {
+ val line = it.readLine() ?: break
+ val split = line.split("=".toRegex(), 2)
+ if (split.size == 2) {
+ configValues[split[0]] = split[1]
+ }
+ importedItems++
+ } catch (e: Exception) {
+ showErrorToast(e)
+ }
+ }
+ }
+
+ for ((key, value) in configValues) {
+ when (key) {
+ IS_USING_SHARED_THEME -> config.isUsingSharedTheme = value.toBoolean()
+ TEXT_COLOR -> config.textColor = value.toInt()
+ BACKGROUND_COLOR -> config.backgroundColor = value.toInt()
+ PRIMARY_COLOR -> config.primaryColor = value.toInt()
+ APP_ICON_COLOR -> {
+ if (getAppIconColors().contains(value.toInt())) {
+ config.appIconColor = value.toInt()
+ checkAppIconColor()
+ }
+ }
+ USE_ENGLISH -> config.useEnglish = value.toBoolean()
+ WAS_USE_ENGLISH_TOGGLED -> config.wasUseEnglishToggled = value.toBoolean()
+ WIDGET_BG_COLOR -> config.widgetBgColor = value.toInt()
+ WIDGET_TEXT_COLOR -> config.widgetTextColor = value.toInt()
+ DATE_FORMAT -> config.dateFormat = value.toString()
+ USE_24_HOUR_FORMAT -> config.use24HourFormat = value.toBoolean()
+ INCLUDED_FOLDERS -> config.addIncludedFolders(value.toStringSet())
+ EXCLUDED_FOLDERS -> config.addExcludedFolders(value.toStringSet())
+ SHOW_HIDDEN_MEDIA -> config.showHiddenMedia = value.toBoolean()
+ FILE_LOADING_PRIORITY -> config.fileLoadingPriority = value.toInt()
+ AUTOPLAY_VIDEOS -> config.autoplayVideos = value.toBoolean()
+ REMEMBER_LAST_VIDEO_POSITION -> config.rememberLastVideoPosition = value.toBoolean()
+ LOOP_VIDEOS -> config.loopVideos = value.toBoolean()
+ OPEN_VIDEOS_ON_SEPARATE_SCREEN -> config.openVideosOnSeparateScreen = value.toBoolean()
+ ALLOW_VIDEO_GESTURES -> config.allowVideoGestures = value.toBoolean()
+ ANIMATE_GIFS -> config.animateGifs = value.toBoolean()
+ CROP_THUMBNAILS -> config.cropThumbnails = value.toBoolean()
+ SHOW_THUMBNAIL_VIDEO_DURATION -> config.showThumbnailVideoDuration = value.toBoolean()
+ SHOW_THUMBNAIL_FILE_TYPES -> config.showThumbnailFileTypes = value.toBoolean()
+ SCROLL_HORIZONTALLY -> config.scrollHorizontally = value.toBoolean()
+ ENABLE_PULL_TO_REFRESH -> config.enablePullToRefresh = value.toBoolean()
+ MAX_BRIGHTNESS -> config.maxBrightness = value.toBoolean()
+ BLACK_BACKGROUND -> config.blackBackground = value.toBoolean()
+ HIDE_SYSTEM_UI -> config.hideSystemUI = value.toBoolean()
+ ALLOW_INSTANT_CHANGE -> config.allowInstantChange = value.toBoolean()
+ ALLOW_PHOTO_GESTURES -> config.allowPhotoGestures = value.toBoolean()
+ ALLOW_DOWN_GESTURE -> config.allowDownGesture = value.toBoolean()
+ ALLOW_ROTATING_WITH_GESTURES -> config.allowRotatingWithGestures = value.toBoolean()
+ SHOW_NOTCH -> config.showNotch = value.toBoolean()
+ SCREEN_ROTATION -> config.screenRotation = value.toInt()
+ ALLOW_ZOOMING_IMAGES -> config.allowZoomingImages = value.toBoolean()
+ SHOW_HIGHEST_QUALITY -> config.showHighestQuality = value.toBoolean()
+ ALLOW_ONE_TO_ONE_ZOOM -> config.allowOneToOneZoom = value.toBoolean()
+ SHOW_EXTENDED_DETAILS -> config.showExtendedDetails = value.toBoolean()
+ HIDE_EXTENDED_DETAILS -> config.hideExtendedDetails = value.toBoolean()
+ EXTENDED_DETAILS -> config.extendedDetails = value.toInt()
+ DELETE_EMPTY_FOLDERS -> config.deleteEmptyFolders = value.toBoolean()
+ KEEP_LAST_MODIFIED -> config.keepLastModified = value.toBoolean()
+ SKIP_DELETE_CONFIRMATION -> config.skipDeleteConfirmation = value.toBoolean()
+ BOTTOM_ACTIONS -> config.bottomActions = value.toBoolean()
+ VISIBLE_BOTTOM_ACTIONS -> config.visibleBottomActions = value.toInt()
+ USE_RECYCLE_BIN -> config.useRecycleBin = value.toBoolean()
+ SHOW_RECYCLE_BIN_AT_FOLDERS -> config.showRecycleBinAtFolders = value.toBoolean()
+ SHOW_RECYCLE_BIN_LAST -> config.showRecycleBinLast = value.toBoolean()
+ SORT_ORDER -> config.sorting = value.toInt()
+ DIRECTORY_SORT_ORDER -> config.directorySorting = value.toInt()
+ GROUP_BY -> config.groupBy = value.toInt()
+ GROUP_DIRECT_SUBFOLDERS -> config.groupDirectSubfolders = value.toBoolean()
+ PINNED_FOLDERS -> config.addPinnedFolders(value.toStringSet())
+ DISPLAY_FILE_NAMES -> config.displayFileNames = value.toBoolean()
+ FILTER_MEDIA -> config.filterMedia = value.toInt()
+ DIR_COLUMN_CNT -> config.dirColumnCnt = value.toInt()
+ MEDIA_COLUMN_CNT -> config.mediaColumnCnt = value.toInt()
+ SHOW_ALL -> config.showAll = value.toBoolean()
+ SHOW_WIDGET_FOLDER_NAME -> config.showWidgetFolderName = value.toBoolean()
+ VIEW_TYPE_FILES -> config.viewTypeFiles = value.toInt()
+ VIEW_TYPE_FOLDERS -> config.viewTypeFolders = value.toInt()
+ SLIDESHOW_INTERVAL -> config.slideshowInterval = value.toInt()
+ SLIDESHOW_INCLUDE_VIDEOS -> config.slideshowIncludeVideos = value.toBoolean()
+ SLIDESHOW_INCLUDE_GIFS -> config.slideshowIncludeGIFs = value.toBoolean()
+ SLIDESHOW_RANDOM_ORDER -> config.slideshowRandomOrder = value.toBoolean()
+ SLIDESHOW_MOVE_BACKWARDS -> config.slideshowMoveBackwards = value.toBoolean()
+ SLIDESHOW_LOOP -> config.loopSlideshow = value.toBoolean()
+ LAST_EDITOR_CROP_ASPECT_RATIO -> config.lastEditorCropAspectRatio = value.toInt()
+ LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X -> config.lastEditorCropOtherAspectRatioX = value.toString().toFloat()
+ LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y -> config.lastEditorCropOtherAspectRatioY = value.toString().toFloat()
+ LAST_CONFLICT_RESOLUTION -> config.lastConflictResolution = value.toInt()
+ LAST_CONFLICT_APPLY_TO_ALL -> config.lastConflictApplyToAll = value.toBoolean()
+ EDITOR_BRUSH_COLOR -> config.editorBrushColor = value.toInt()
+ EDITOR_BRUSH_HARDNESS -> config.editorBrushHardness = value.toString().toFloat()
+ EDITOR_BRUSH_SIZE -> config.editorBrushSize = value.toString().toFloat()
+ FOLDER_THUMBNAIL_STYLE -> config.folderStyle = value.toInt()
+ FOLDER_MEDIA_COUNT -> config.showFolderMediaCount = value.toInt()
+ LIMIT_FOLDER_TITLE -> config.limitFolderTitle = value.toBoolean()
+ THUMBNAIL_SPACING -> config.thumbnailSpacing = value.toInt()
+ FILE_ROUNDED_CORNERS -> config.fileRoundedCorners = value.toBoolean()
+ ALBUM_COVERS -> {
+ val existingCovers = config.parseAlbumCovers()
+ val existingCoverPaths = existingCovers.map { it.path }.toMutableList() as ArrayList
+
+ val listType = object : TypeToken>() {}.type
+ val covers = Gson().fromJson>(value.toString(), listType) ?: ArrayList(1)
+ covers.filter { !existingCoverPaths.contains(it.path) && getDoesFilePathExist(it.tmb) }.forEach {
+ existingCovers.add(it)
+ }
+
+ config.albumCovers = Gson().toJson(existingCovers)
+ }
+ }
+ }
+
+ toast(if (configValues.size > 0) R.string.settings_imported_successfully else R.string.no_entries_for_importing)
+ runOnUiThread {
+ setupSettingItems()
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SimpleActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SimpleActivity.kt
new file mode 100644
index 000000000..6824b7038
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SimpleActivity.kt
@@ -0,0 +1,97 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.annotation.SuppressLint
+import android.database.ContentObserver
+import android.net.Uri
+import android.provider.MediaStore.Images
+import android.provider.MediaStore.Video
+import android.view.WindowManager
+import com.simplemobiletools.commons.activities.BaseSimpleActivity
+import com.simplemobiletools.commons.dialogs.FilePickerDialog
+import com.simplemobiletools.commons.extensions.getParentPath
+import com.simplemobiletools.commons.extensions.getRealPathFromURI
+import com.simplemobiletools.commons.extensions.scanPathRecursively
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.commons.helpers.isPiePlus
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.extensions.addPathToDB
+import com.simplemobiletools.gallery.pro.extensions.config
+import com.simplemobiletools.gallery.pro.extensions.updateDirectoryPath
+
+open class SimpleActivity : BaseSimpleActivity() {
+ val observer = object : ContentObserver(null) {
+ override fun onChange(selfChange: Boolean, uri: Uri) {
+ super.onChange(selfChange, uri)
+ val path = getRealPathFromURI(uri)
+ if (path != null) {
+ updateDirectoryPath(path.getParentPath())
+ addPathToDB(path)
+ }
+ }
+ }
+
+ override fun getAppIconIDs() = arrayListOf(
+ R.mipmap.ic_launcher_red,
+ R.mipmap.ic_launcher_pink,
+ R.mipmap.ic_launcher_purple,
+ R.mipmap.ic_launcher_deep_purple,
+ R.mipmap.ic_launcher_indigo,
+ R.mipmap.ic_launcher_blue,
+ R.mipmap.ic_launcher_light_blue,
+ R.mipmap.ic_launcher_cyan,
+ R.mipmap.ic_launcher_teal,
+ R.mipmap.ic_launcher_green,
+ R.mipmap.ic_launcher_light_green,
+ R.mipmap.ic_launcher_lime,
+ R.mipmap.ic_launcher_yellow,
+ R.mipmap.ic_launcher_amber,
+ R.mipmap.ic_launcher,
+ R.mipmap.ic_launcher_deep_orange,
+ R.mipmap.ic_launcher_brown,
+ R.mipmap.ic_launcher_blue_grey,
+ R.mipmap.ic_launcher_grey_black
+ )
+
+ override fun getAppLauncherName() = getString(R.string.app_launcher_name)
+
+ @SuppressLint("InlinedApi")
+ protected fun checkNotchSupport() {
+ if (isPiePlus()) {
+ val cutoutMode = when {
+ config.showNotch -> WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ else -> WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
+ }
+
+ window.attributes.layoutInDisplayCutoutMode = cutoutMode
+ if (config.showNotch) {
+ window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
+ }
+ }
+ }
+
+ protected fun registerFileUpdateListener() {
+ try {
+ contentResolver.registerContentObserver(Images.Media.EXTERNAL_CONTENT_URI, true, observer)
+ contentResolver.registerContentObserver(Video.Media.EXTERNAL_CONTENT_URI, true, observer)
+ } catch (ignored: Exception) {
+ }
+ }
+
+ protected fun unregisterFileUpdateListener() {
+ try {
+ contentResolver.unregisterContentObserver(observer)
+ } catch (ignored: Exception) {
+ }
+ }
+
+ protected fun showAddIncludedFolderDialog(callback: () -> Unit) {
+ FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden, false, true) {
+ config.lastFilepickerPath = it
+ config.addIncludedFolder(it)
+ callback()
+ ensureBackgroundThread {
+ scanPathRecursively(it)
+ }
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SplashActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SplashActivity.kt
new file mode 100644
index 000000000..9d0c0cc79
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SplashActivity.kt
@@ -0,0 +1,44 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.content.Intent
+import com.simplemobiletools.commons.activities.BaseSplashActivity
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.gallery.pro.extensions.config
+import com.simplemobiletools.gallery.pro.extensions.favoritesDB
+import com.simplemobiletools.gallery.pro.extensions.getFavoriteFromPath
+import com.simplemobiletools.gallery.pro.extensions.mediaDB
+import com.simplemobiletools.gallery.pro.models.Favorite
+
+class SplashActivity : BaseSplashActivity() {
+ override fun initActivity() {
+
+ // check if previously selected favorite items have been properly migrated into the new Favorites table
+ if (config.wereFavoritesMigrated) {
+ launchActivity()
+ } else {
+ if (config.appRunCount == 0) {
+ config.wereFavoritesMigrated = true
+ launchActivity()
+ } else {
+ config.wereFavoritesMigrated = true
+ ensureBackgroundThread {
+ val favorites = ArrayList()
+ val favoritePaths = mediaDB.getFavorites().map { it.path }.toMutableList() as ArrayList
+ favoritePaths.forEach {
+ favorites.add(getFavoriteFromPath(it))
+ }
+ favoritesDB.insertAll(favorites)
+
+ runOnUiThread {
+ launchActivity()
+ }
+ }
+ }
+ }
+ }
+
+ private fun launchActivity() {
+ startActivity(Intent(this, MainActivity::class.java))
+ finish()
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/VideoActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/VideoActivity.kt
similarity index 66%
rename from app/src/main/kotlin/com/simplemobiletools/gallery/activities/VideoActivity.kt
rename to app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/VideoActivity.kt
index fa38734e3..78fa61955 100644
--- a/app/src/main/kotlin/com/simplemobiletools/gallery/activities/VideoActivity.kt
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/VideoActivity.kt
@@ -1,11 +1,11 @@
-package com.simplemobiletools.gallery.activities
+package com.simplemobiletools.gallery.pro.activities
import android.os.Bundle
class VideoActivity : PhotoVideoActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
- PhotoVideoActivity.mIsVideo = true
+ mIsVideo = true
super.onCreate(savedInstanceState)
}
}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/VideoPlayerActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/VideoPlayerActivity.kt
new file mode 100644
index 000000000..b1c319a1e
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/VideoPlayerActivity.kt
@@ -0,0 +1,633 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.app.Activity
+import android.content.Intent
+import android.content.pm.ActivityInfo
+import android.content.res.Configuration
+import android.graphics.Color
+import android.graphics.Point
+import android.graphics.SurfaceTexture
+import android.graphics.drawable.ColorDrawable
+import android.net.Uri
+import android.os.Bundle
+import android.os.Handler
+import android.util.DisplayMetrics
+import android.view.*
+import android.widget.SeekBar
+import com.google.android.exoplayer2.*
+import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
+import com.google.android.exoplayer2.source.ExtractorMediaSource
+import com.google.android.exoplayer2.source.TrackGroupArray
+import com.google.android.exoplayer2.trackselection.TrackSelectionArray
+import com.google.android.exoplayer2.upstream.ContentDataSource
+import com.google.android.exoplayer2.upstream.DataSource
+import com.google.android.exoplayer2.upstream.DataSpec
+import com.google.android.exoplayer2.video.VideoListener
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.*
+import kotlinx.android.synthetic.main.activity_video_player.*
+import kotlinx.android.synthetic.main.bottom_video_time_holder.*
+
+open class VideoPlayerActivity : SimpleActivity(), SeekBar.OnSeekBarChangeListener, TextureView.SurfaceTextureListener {
+ private val PLAY_WHEN_READY_DRAG_DELAY = 100L
+
+ private var mIsFullscreen = false
+ private var mIsPlaying = false
+ private var mWasVideoStarted = false
+ private var mIsDragged = false
+ private var mIsOrientationLocked = false
+ private var mScreenWidth = 0
+ private var mCurrTime = 0
+ private var mDuration = 0
+ private var mDragThreshold = 0f
+ private var mTouchDownX = 0f
+ private var mTouchDownY = 0f
+ private var mTouchDownTime = 0L
+ private var mProgressAtDown = 0L
+ private var mCloseDownThreshold = 100f
+
+ private var mUri: Uri? = null
+ private var mExoPlayer: SimpleExoPlayer? = null
+ private var mVideoSize = Point(0, 0)
+ private var mTimerHandler = Handler()
+ private var mPlayWhenReadyHandler = Handler()
+
+ private var mIgnoreCloseDown = false
+
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_video_player)
+ setupOrientation()
+ checkNotchSupport()
+ initPlayer()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ top_shadow.layoutParams.height = statusBarHeight + actionBarHeight
+ supportActionBar?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
+ window.statusBarColor = Color.TRANSPARENT
+ window.navigationBarColor = Color.TRANSPARENT
+ if (config.blackBackground) {
+ video_player_holder.background = ColorDrawable(Color.BLACK)
+ }
+
+ if (config.maxBrightness) {
+ val attributes = window.attributes
+ attributes.screenBrightness = 1f
+ window.attributes = attributes
+ }
+
+ updateTextColors(video_player_holder)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ pauseVideo()
+
+ if (config.rememberLastVideoPosition && mWasVideoStarted) {
+ saveVideoProgress()
+ }
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ if (!isChangingConfigurations) {
+ pauseVideo()
+ video_curr_time.text = 0.getFormattedDuration()
+ releaseExoPlayer()
+ video_seekbar.progress = 0
+ mTimerHandler.removeCallbacksAndMessages(null)
+ mPlayWhenReadyHandler.removeCallbacksAndMessages(null)
+ }
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_video_player, menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ when (item.itemId) {
+ R.id.menu_change_orientation -> changeOrientation()
+ R.id.menu_open_with -> openPath(mUri!!.toString(), true)
+ R.id.menu_share -> shareMediumPath(mUri!!.toString())
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ setVideoSize()
+ initTimeHolder()
+ video_surface_frame.onGlobalLayout {
+ video_surface_frame.controller.resetState()
+ }
+ }
+
+ private fun setupOrientation() {
+ if (!mIsOrientationLocked) {
+ if (config.screenRotation == ROTATE_BY_DEVICE_ROTATION) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
+ } else if (config.screenRotation == ROTATE_BY_SYSTEM_SETTING) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
+ }
+ }
+ }
+
+ private fun initPlayer() {
+ mUri = intent.data ?: return
+ supportActionBar?.title = getFilenameFromUri(mUri!!)
+ initTimeHolder()
+
+ showSystemUI(true)
+ window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
+ val isFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
+ fullscreenToggled(isFullscreen)
+ }
+
+ video_curr_time.setOnClickListener { doSkip(false) }
+ video_duration.setOnClickListener { doSkip(true) }
+ video_toggle_play_pause.setOnClickListener { togglePlayPause() }
+ video_surface_frame.setOnClickListener { toggleFullscreen() }
+ video_surface_frame.controller.settings.swallowDoubleTaps = true
+
+ video_next_file.beVisibleIf(intent.getBooleanExtra(SHOW_NEXT_ITEM, false))
+ video_next_file.setOnClickListener { handleNextFile() }
+
+ video_prev_file.beVisibleIf(intent.getBooleanExtra(SHOW_PREV_ITEM, false))
+ video_prev_file.setOnClickListener { handlePrevFile() }
+
+
+ val gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
+ override fun onDoubleTap(e: MotionEvent?): Boolean {
+ if (e != null) {
+ handleDoubleTap(e.rawX)
+ }
+
+ return true
+ }
+ })
+
+ video_surface_frame.setOnTouchListener { view, event ->
+ handleEvent(event)
+ gestureDetector.onTouchEvent(event)
+ false
+ }
+
+ initExoPlayer()
+ video_surface.surfaceTextureListener = this
+
+ if (config.allowVideoGestures) {
+ video_brightness_controller.initialize(this, slide_info, true, video_player_holder, singleTap = { x, y ->
+ toggleFullscreen()
+ }, doubleTap = { x, y ->
+ doSkip(false)
+ })
+
+ video_volume_controller.initialize(this, slide_info, false, video_player_holder, singleTap = { x, y ->
+ toggleFullscreen()
+ }, doubleTap = { x, y ->
+ doSkip(true)
+ })
+ } else {
+ video_brightness_controller.beGone()
+ video_volume_controller.beGone()
+ }
+
+ if (config.hideSystemUI) {
+ Handler().postDelayed({
+ fullscreenToggled(true)
+ }, HIDE_SYSTEM_UI_DELAY)
+ }
+
+ mDragThreshold = DRAG_THRESHOLD * resources.displayMetrics.density
+ }
+
+ private fun initExoPlayer() {
+ val dataSpec = DataSpec(mUri)
+ val fileDataSource = ContentDataSource(applicationContext)
+ try {
+ fileDataSource.open(dataSpec)
+ } catch (e: Exception) {
+ showErrorToast(e)
+ }
+
+ val factory = DataSource.Factory { fileDataSource }
+ val audioSource = ExtractorMediaSource(fileDataSource.uri, factory, DefaultExtractorsFactory(), null, null)
+ mExoPlayer = ExoPlayerFactory.newSimpleInstance(applicationContext).apply {
+ seekParameters = SeekParameters.CLOSEST_SYNC
+ audioStreamType = C.STREAM_TYPE_MUSIC
+ if (config.loopVideos) {
+ repeatMode = Player.REPEAT_MODE_ONE
+ }
+ prepare(audioSource)
+ }
+ initExoPlayerListeners()
+ }
+
+ private fun initExoPlayerListeners() {
+ mExoPlayer!!.addListener(object : Player.EventListener {
+ override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) {}
+
+ override fun onSeekProcessed() {}
+
+ override fun onTracksChanged(trackGroups: TrackGroupArray?, trackSelections: TrackSelectionArray?) {}
+
+ override fun onPlayerError(error: ExoPlaybackException?) {}
+
+ override fun onLoadingChanged(isLoading: Boolean) {}
+
+ override fun onPositionDiscontinuity(reason: Int) {
+ // Reset progress views when video loops.
+ if (reason == Player.DISCONTINUITY_REASON_PERIOD_TRANSITION) {
+ video_seekbar.progress = 0
+ video_curr_time.text = 0.getFormattedDuration()
+ }
+ }
+
+ override fun onRepeatModeChanged(repeatMode: Int) {}
+
+ override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) {}
+
+ override fun onTimelineChanged(timeline: Timeline?, manifest: Any?, reason: Int) {}
+
+ override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
+ when (playbackState) {
+ Player.STATE_READY -> videoPrepared()
+ Player.STATE_ENDED -> videoCompleted()
+ }
+ }
+ })
+
+ mExoPlayer!!.addVideoListener(object : VideoListener {
+ override fun onVideoSizeChanged(width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float) {
+ mVideoSize.x = width
+ mVideoSize.y = height
+ setVideoSize()
+ }
+
+ override fun onRenderedFirstFrame() {}
+ })
+ }
+
+ private fun videoPrepared() {
+ if (!mWasVideoStarted) {
+ video_toggle_play_pause.beVisible()
+ mDuration = (mExoPlayer!!.duration / 1000).toInt()
+ video_seekbar.max = mDuration
+ video_duration.text = mDuration.getFormattedDuration()
+ setPosition(mCurrTime)
+
+ if (config.rememberLastVideoPosition) {
+ setLastVideoSavedPosition()
+ }
+
+ if (config.autoplayVideos) {
+ resumeVideo()
+ } else {
+ video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
+ }
+ }
+ }
+
+ private fun handleDoubleTap(x: Float) {
+ val instantWidth = mScreenWidth / 7
+ when {
+ x <= instantWidth -> doSkip(false)
+ x >= mScreenWidth - instantWidth -> doSkip(true)
+ else -> togglePlayPause()
+ }
+ }
+
+ private fun resumeVideo() {
+ video_toggle_play_pause.setImageResource(R.drawable.ic_pause_outline_vector)
+ if (mExoPlayer == null) {
+ return
+ }
+
+ val wasEnded = didVideoEnd()
+ if (wasEnded) {
+ setPosition(0)
+ }
+
+ mWasVideoStarted = true
+ mIsPlaying = true
+ mExoPlayer?.playWhenReady = true
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+
+ private fun pauseVideo() {
+ video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector)
+ if (mExoPlayer == null) {
+ return
+ }
+
+ mIsPlaying = false
+ if (!didVideoEnd()) {
+ mExoPlayer?.playWhenReady = false
+ }
+
+ window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+
+ private fun togglePlayPause() {
+ mIsPlaying = !mIsPlaying
+ if (mIsPlaying) {
+ resumeVideo()
+ } else {
+ pauseVideo()
+ }
+ }
+
+ private fun setPosition(seconds: Int) {
+ mExoPlayer?.seekTo(seconds * 1000L)
+ video_seekbar.progress = seconds
+ video_curr_time.text = seconds.getFormattedDuration()
+ }
+
+ private fun setLastVideoSavedPosition() {
+ val pos = config.getLastVideoPosition(mUri.toString())
+ if (pos > 0) {
+ setPosition(pos)
+ }
+ }
+
+ private fun videoCompleted() {
+ if (mExoPlayer == null) {
+ return
+ }
+
+ clearLastVideoSavedProgress()
+ mCurrTime = (mExoPlayer!!.duration / 1000).toInt()
+ video_seekbar.progress = video_seekbar.max
+ video_curr_time.text = mDuration.getFormattedDuration()
+ pauseVideo()
+ }
+
+ private fun didVideoEnd(): Boolean {
+ val currentPos = mExoPlayer?.currentPosition ?: 0
+ val duration = mExoPlayer?.duration ?: 0
+ return currentPos != 0L && currentPos >= duration
+ }
+
+ private fun saveVideoProgress() {
+ if (!didVideoEnd()) {
+ config.saveLastVideoPosition(mUri.toString(), mExoPlayer!!.currentPosition.toInt() / 1000)
+ }
+ }
+
+ private fun clearLastVideoSavedProgress() {
+ config.removeLastVideoPosition(mUri.toString())
+ }
+
+ private fun setVideoSize() {
+ val videoProportion = mVideoSize.x.toFloat() / mVideoSize.y.toFloat()
+ val display = windowManager.defaultDisplay
+ val screenWidth: Int
+ val screenHeight: Int
+
+ val realMetrics = DisplayMetrics()
+ display.getRealMetrics(realMetrics)
+ screenWidth = realMetrics.widthPixels
+ screenHeight = realMetrics.heightPixels
+
+ val screenProportion = screenWidth.toFloat() / screenHeight.toFloat()
+
+ video_surface.layoutParams.apply {
+ if (videoProportion > screenProportion) {
+ width = screenWidth
+ height = (screenWidth.toFloat() / videoProportion).toInt()
+ } else {
+ width = (videoProportion * screenHeight.toFloat()).toInt()
+ height = screenHeight
+ }
+ video_surface.layoutParams = this
+ }
+
+ val multiplier = if (screenWidth > screenHeight) 0.5 else 0.8
+ mScreenWidth = (screenWidth * multiplier).toInt()
+
+ if (config.screenRotation == ROTATE_BY_ASPECT_RATIO) {
+ if (mVideoSize.x > mVideoSize.y) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
+ } else if (mVideoSize.x < mVideoSize.y) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+ }
+ }
+ }
+
+ private fun changeOrientation() {
+ mIsOrientationLocked = true
+ requestedOrientation = if (resources.configuration.orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
+ ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
+ } else {
+ ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+ }
+ }
+
+ private fun toggleFullscreen() {
+ fullscreenToggled(!mIsFullscreen)
+ }
+
+ private fun fullscreenToggled(isFullScreen: Boolean) {
+ mIsFullscreen = isFullScreen
+ if (isFullScreen) {
+ hideSystemUI(true)
+ } else {
+ showSystemUI(true)
+ }
+
+ val newAlpha = if (isFullScreen) 0f else 1f
+ arrayOf(video_prev_file, video_toggle_play_pause, video_next_file, video_curr_time, video_seekbar, video_duration, top_shadow, video_bottom_gradient).forEach {
+ it.animate().alpha(newAlpha).start()
+ }
+ video_seekbar.setOnSeekBarChangeListener(if (mIsFullscreen) null else this)
+ arrayOf(video_prev_file, video_next_file, video_curr_time, video_duration).forEach {
+ it.isClickable = !mIsFullscreen
+ }
+ }
+
+ private fun initTimeHolder() {
+ var right = 0
+ var bottom = 0
+
+ if (hasNavBar()) {
+ if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
+ bottom += navigationBarHeight
+ } else {
+ right += navigationBarWidth
+ bottom += navigationBarHeight
+ }
+ }
+
+ video_time_holder.setPadding(0, 0, right, bottom)
+ video_seekbar.setOnSeekBarChangeListener(this)
+ video_seekbar.max = mDuration
+ video_duration.text = mDuration.getFormattedDuration()
+ video_curr_time.text = mCurrTime.getFormattedDuration()
+ setupTimer()
+ }
+
+ private fun setupTimer() {
+ runOnUiThread(object : Runnable {
+ override fun run() {
+ if (mExoPlayer != null && !mIsDragged && mIsPlaying) {
+ mCurrTime = (mExoPlayer!!.currentPosition / 1000).toInt()
+ video_seekbar.progress = mCurrTime
+ video_curr_time.text = mCurrTime.getFormattedDuration()
+ }
+
+ mTimerHandler.postDelayed(this, 1000)
+ }
+ })
+ }
+
+ private fun doSkip(forward: Boolean) {
+ if (mExoPlayer == null) {
+ return
+ }
+
+ val curr = mExoPlayer!!.currentPosition
+ val newProgress = if (forward) curr + FAST_FORWARD_VIDEO_MS else curr - FAST_FORWARD_VIDEO_MS
+ val roundProgress = Math.round(newProgress / 1000f)
+ val limitedProgress = Math.max(Math.min(mExoPlayer!!.duration.toInt() / 1000, roundProgress), 0)
+ setPosition(limitedProgress)
+ if (!mIsPlaying) {
+ togglePlayPause()
+ }
+ }
+
+ private fun handleEvent(event: MotionEvent) {
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ mTouchDownX = event.x
+ mTouchDownY = event.y
+ mTouchDownTime = System.currentTimeMillis()
+ mProgressAtDown = mExoPlayer!!.currentPosition
+ }
+ MotionEvent.ACTION_POINTER_DOWN -> mIgnoreCloseDown = true
+ MotionEvent.ACTION_MOVE -> {
+ val diffX = event.x - mTouchDownX
+ val diffY = event.y - mTouchDownY
+
+ if (mIsDragged || (Math.abs(diffX) > mDragThreshold && Math.abs(diffX) > Math.abs(diffY)) && video_surface_frame.controller.state.zoom == 1f) {
+ if (!mIsDragged) {
+ arrayOf(video_curr_time, video_seekbar, video_duration).forEach {
+ it.animate().alpha(1f).start()
+ }
+ }
+ mIgnoreCloseDown = true
+ mIsDragged = true
+ var percent = ((diffX / mScreenWidth) * 100).toInt()
+ percent = Math.min(100, Math.max(-100, percent))
+
+ val skipLength = (mDuration * 1000f) * (percent / 100f)
+ var newProgress = mProgressAtDown + skipLength
+ newProgress = Math.max(Math.min(mExoPlayer!!.duration.toFloat(), newProgress), 0f)
+ val newSeconds = (newProgress / 1000).toInt()
+ setPosition(newSeconds)
+ resetPlayWhenReady()
+ }
+ }
+ MotionEvent.ACTION_UP -> {
+ val diffX = mTouchDownX - event.x
+ val diffY = mTouchDownY - event.y
+
+ val downGestureDuration = System.currentTimeMillis() - mTouchDownTime
+ if (config.allowDownGesture && !mIgnoreCloseDown && Math.abs(diffY) > Math.abs(diffX) && diffY < -mCloseDownThreshold &&
+ downGestureDuration < MAX_CLOSE_DOWN_GESTURE_DURATION &&
+ video_surface_frame.controller.state.zoom == 1f) {
+ supportFinishAfterTransition()
+ }
+
+ mIgnoreCloseDown = false
+ if (mIsDragged) {
+ if (mIsFullscreen) {
+ arrayOf(video_curr_time, video_seekbar, video_duration).forEach {
+ it.animate().alpha(0f).start()
+ }
+ }
+
+ if (!mIsPlaying) {
+ togglePlayPause()
+ }
+ }
+ mIsDragged = false
+ }
+ }
+ }
+
+ private fun handleNextFile() {
+ Intent().apply {
+ putExtra(GO_TO_NEXT_ITEM, true)
+ setResult(Activity.RESULT_OK, this)
+ }
+ finish()
+ }
+
+ private fun handlePrevFile() {
+ Intent().apply {
+ putExtra(GO_TO_PREV_ITEM, true)
+ setResult(Activity.RESULT_OK, this)
+ }
+ finish()
+ }
+
+ private fun resetPlayWhenReady() {
+ mExoPlayer?.playWhenReady = false
+ mPlayWhenReadyHandler.removeCallbacksAndMessages(null)
+ mPlayWhenReadyHandler.postDelayed({
+ mExoPlayer?.playWhenReady = true
+ }, PLAY_WHEN_READY_DRAG_DELAY)
+ }
+
+ private fun releaseExoPlayer() {
+ mExoPlayer?.stop()
+ ensureBackgroundThread {
+ mExoPlayer?.release()
+ mExoPlayer = null
+ }
+ }
+
+ override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
+ if (mExoPlayer != null && fromUser) {
+ setPosition(progress)
+ resetPlayWhenReady()
+ }
+ }
+
+ override fun onStartTrackingTouch(seekBar: SeekBar?) {
+ mIsDragged = true
+ }
+
+ override fun onStopTrackingTouch(seekBar: SeekBar?) {
+ if (mExoPlayer == null)
+ return
+
+ if (mIsPlaying) {
+ mExoPlayer!!.playWhenReady = true
+ } else {
+ togglePlayPause()
+ }
+
+ mIsDragged = false
+ }
+
+ override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) {
+ }
+
+ override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?) = false
+
+ override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) {
+ ensureBackgroundThread {
+ mExoPlayer?.setVideoSurface(Surface(video_surface!!.surfaceTexture))
+ }
+ }
+
+ override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) {}
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/ViewPagerActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/ViewPagerActivity.kt
new file mode 100644
index 000000000..264133ecd
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/ViewPagerActivity.kt
@@ -0,0 +1,1309 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.animation.Animator
+import android.animation.ValueAnimator
+import android.annotation.SuppressLint
+import android.annotation.TargetApi
+import android.app.Activity
+import android.content.Intent
+import android.content.pm.ActivityInfo
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.content.res.Configuration
+import android.database.Cursor
+import android.graphics.Bitmap
+import android.graphics.Color
+import android.graphics.drawable.ColorDrawable
+import android.graphics.drawable.Icon
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.provider.MediaStore.Images
+import android.view.Menu
+import android.view.MenuItem
+import android.view.View
+import android.view.WindowManager
+import android.view.animation.DecelerateInterpolator
+import android.widget.Toast
+import androidx.exifinterface.media.ExifInterface
+import androidx.print.PrintHelper
+import androidx.viewpager.widget.ViewPager
+import com.bumptech.glide.Glide
+import com.bumptech.glide.load.DataSource
+import com.bumptech.glide.load.engine.DiskCacheStrategy
+import com.bumptech.glide.load.engine.GlideException
+import com.bumptech.glide.request.RequestListener
+import com.bumptech.glide.request.RequestOptions
+import com.bumptech.glide.request.target.Target
+import com.simplemobiletools.commons.dialogs.PropertiesDialog
+import com.simplemobiletools.commons.dialogs.RenameItemDialog
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.*
+import com.simplemobiletools.commons.models.FileDirItem
+import com.simplemobiletools.gallery.pro.BuildConfig
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.adapters.MyPagerAdapter
+import com.simplemobiletools.gallery.pro.asynctasks.GetMediaAsynctask
+import com.simplemobiletools.gallery.pro.dialogs.DeleteWithRememberDialog
+import com.simplemobiletools.gallery.pro.dialogs.ResizeWithPathDialog
+import com.simplemobiletools.gallery.pro.dialogs.SaveAsDialog
+import com.simplemobiletools.gallery.pro.dialogs.SlideshowDialog
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.fragments.PhotoFragment
+import com.simplemobiletools.gallery.pro.fragments.VideoFragment
+import com.simplemobiletools.gallery.pro.fragments.ViewPagerFragment
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.models.Medium
+import com.simplemobiletools.gallery.pro.models.ThumbnailItem
+import kotlinx.android.synthetic.main.activity_medium.*
+import kotlinx.android.synthetic.main.bottom_actions.*
+import java.io.File
+import java.io.OutputStream
+import java.util.*
+
+class ViewPagerActivity : SimpleActivity(), ViewPager.OnPageChangeListener, ViewPagerFragment.FragmentListener {
+ private val REQUEST_VIEW_VIDEO = 1
+
+ private var mPath = ""
+ private var mDirectory = ""
+ private var mIsFullScreen = false
+ private var mPos = -1
+ private var mShowAll = false
+ private var mIsSlideshowActive = false
+ private var mPrevHashcode = 0
+
+ private var mSlideshowHandler = Handler()
+ private var mSlideshowInterval = SLIDESHOW_DEFAULT_INTERVAL
+ private var mSlideshowMoveBackwards = false
+ private var mSlideshowMedia = mutableListOf()
+ private var mAreSlideShowMediaVisible = false
+
+ private var mIsOrientationLocked = false
+
+ private var mMediaFiles = ArrayList()
+ private var mFavoritePaths = ArrayList()
+ private var mIgnoredPaths = ArrayList()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ useDynamicTheme = false
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_medium)
+
+ window.decorView.setBackgroundColor(config.backgroundColor)
+ top_shadow.layoutParams.height = statusBarHeight + actionBarHeight
+ checkNotchSupport()
+ (MediaActivity.mMedia.clone() as ArrayList).filter { it is Medium }.mapTo(mMediaFiles) { it as Medium }
+
+ handlePermission(PERMISSION_WRITE_STORAGE) {
+ if (it) {
+ initViewPager()
+ } else {
+ toast(R.string.no_storage_permissions)
+ finish()
+ }
+ }
+
+ initFavorites()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ if (!hasPermission(PERMISSION_WRITE_STORAGE)) {
+ finish()
+ return
+ }
+
+ if (config.bottomActions) {
+ window.navigationBarColor = Color.TRANSPARENT
+ } else {
+ setTranslucentNavigation()
+ }
+
+ initBottomActions()
+
+ if (config.maxBrightness) {
+ val attributes = window.attributes
+ attributes.screenBrightness = 1f
+ window.attributes = attributes
+ }
+
+ setupOrientation()
+ invalidateOptionsMenu()
+
+ supportActionBar?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
+ val filename = getCurrentMedium()?.name ?: mPath.getFilenameFromPath()
+ supportActionBar?.title = filename
+ window.statusBarColor = Color.TRANSPARENT
+ }
+
+ override fun onPause() {
+ super.onPause()
+ stopSlideshow()
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) {
+ config.temporarilyShowHidden = false
+ }
+
+ if (config.isThirdPartyIntent) {
+ config.isThirdPartyIntent = false
+
+ if (intent.extras == null || !intent.getBooleanExtra(IS_FROM_GALLERY, false)) {
+ mMediaFiles.clear()
+ }
+ }
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.menu_viewpager, menu)
+ val currentMedium = getCurrentMedium() ?: return true
+ currentMedium.isFavorite = mFavoritePaths.contains(currentMedium.path)
+ val visibleBottomActions = if (config.bottomActions) config.visibleBottomActions else 0
+
+ val rotationDegrees = getCurrentPhotoFragment()?.mCurrentRotationDegrees ?: 0
+ menu.apply {
+ findItem(R.id.menu_show_on_map).isVisible = visibleBottomActions and BOTTOM_ACTION_SHOW_ON_MAP == 0
+ findItem(R.id.menu_slideshow).isVisible = visibleBottomActions and BOTTOM_ACTION_SLIDESHOW == 0
+ findItem(R.id.menu_properties).isVisible = visibleBottomActions and BOTTOM_ACTION_PROPERTIES == 0
+ findItem(R.id.menu_delete).isVisible = visibleBottomActions and BOTTOM_ACTION_DELETE == 0
+ findItem(R.id.menu_share).isVisible = visibleBottomActions and BOTTOM_ACTION_SHARE == 0
+ findItem(R.id.menu_edit).isVisible = visibleBottomActions and BOTTOM_ACTION_EDIT == 0 && !currentMedium.isSVG()
+ findItem(R.id.menu_rename).isVisible = visibleBottomActions and BOTTOM_ACTION_RENAME == 0 && !currentMedium.getIsInRecycleBin()
+ findItem(R.id.menu_rotate).isVisible = currentMedium.isImage() && visibleBottomActions and BOTTOM_ACTION_ROTATE == 0
+ findItem(R.id.menu_set_as).isVisible = visibleBottomActions and BOTTOM_ACTION_SET_AS == 0
+ findItem(R.id.menu_copy_to).isVisible = visibleBottomActions and BOTTOM_ACTION_COPY == 0
+ findItem(R.id.menu_move_to).isVisible = visibleBottomActions and BOTTOM_ACTION_MOVE == 0
+ findItem(R.id.menu_save_as).isVisible = rotationDegrees != 0
+ findItem(R.id.menu_print).isVisible = currentMedium.isImage() || currentMedium.isRaw()
+ findItem(R.id.menu_resize).isVisible = visibleBottomActions and BOTTOM_ACTION_RESIZE == 0 && currentMedium.isImage()
+ findItem(R.id.menu_hide).isVisible = !currentMedium.isHidden() && visibleBottomActions and BOTTOM_ACTION_TOGGLE_VISIBILITY == 0 && !currentMedium.getIsInRecycleBin()
+ findItem(R.id.menu_unhide).isVisible = currentMedium.isHidden() && visibleBottomActions and BOTTOM_ACTION_TOGGLE_VISIBILITY == 0 && !currentMedium.getIsInRecycleBin()
+ findItem(R.id.menu_add_to_favorites).isVisible = !currentMedium.isFavorite && visibleBottomActions and BOTTOM_ACTION_TOGGLE_FAVORITE == 0 && !currentMedium.getIsInRecycleBin()
+ findItem(R.id.menu_remove_from_favorites).isVisible = currentMedium.isFavorite && visibleBottomActions and BOTTOM_ACTION_TOGGLE_FAVORITE == 0 && !currentMedium.getIsInRecycleBin()
+ findItem(R.id.menu_restore_file).isVisible = currentMedium.path.startsWith(recycleBinPath)
+ findItem(R.id.menu_create_shortcut).isVisible = isOreoPlus()
+ findItem(R.id.menu_change_orientation).isVisible = rotationDegrees == 0 && visibleBottomActions and BOTTOM_ACTION_CHANGE_ORIENTATION == 0
+ findItem(R.id.menu_change_orientation).icon = resources.getDrawable(getChangeOrientationIcon())
+ findItem(R.id.menu_rotate).setShowAsAction(
+ if (rotationDegrees != 0) {
+ MenuItem.SHOW_AS_ACTION_ALWAYS
+ } else {
+ MenuItem.SHOW_AS_ACTION_IF_ROOM
+ })
+ }
+
+ if (visibleBottomActions != 0) {
+ updateBottomActionIcons(currentMedium)
+ }
+
+ updateMenuItemColors(menu, baseColor = Color.BLACK)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ if (getCurrentMedium() == null)
+ return true
+
+ when (item.itemId) {
+ R.id.menu_set_as -> setAs(getCurrentPath())
+ R.id.menu_slideshow -> initSlideshow()
+ R.id.menu_copy_to -> copyMoveTo(true)
+ R.id.menu_move_to -> moveFileTo()
+ R.id.menu_open_with -> openPath(getCurrentPath(), true)
+ R.id.menu_hide -> toggleFileVisibility(true)
+ R.id.menu_unhide -> toggleFileVisibility(false)
+ R.id.menu_share -> shareMediumPath(getCurrentPath())
+ R.id.menu_delete -> checkDeleteConfirmation()
+ R.id.menu_rename -> renameFile()
+ R.id.menu_print -> printFile()
+ R.id.menu_edit -> openEditor(getCurrentPath())
+ R.id.menu_properties -> showProperties()
+ R.id.menu_show_on_map -> showFileOnMap(getCurrentPath())
+ R.id.menu_rotate_right -> rotateImage(90)
+ R.id.menu_rotate_left -> rotateImage(-90)
+ R.id.menu_rotate_one_eighty -> rotateImage(180)
+ R.id.menu_add_to_favorites -> toggleFavorite()
+ R.id.menu_remove_from_favorites -> toggleFavorite()
+ R.id.menu_restore_file -> restoreFile()
+ R.id.menu_force_portrait -> toggleOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
+ R.id.menu_force_landscape -> toggleOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
+ R.id.menu_default_orientation -> toggleOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
+ R.id.menu_save_as -> saveImageAs()
+ R.id.menu_create_shortcut -> createShortcut()
+ R.id.menu_resize -> resizeImage()
+ R.id.menu_settings -> launchSettings()
+ else -> return super.onOptionsItemSelected(item)
+ }
+ return true
+ }
+
+ override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
+ if (requestCode == REQUEST_EDIT_IMAGE && resultCode == Activity.RESULT_OK && resultData != null) {
+ mPos = -1
+ mPrevHashcode = 0
+ refreshViewPager()
+ } else if (requestCode == REQUEST_SET_AS && resultCode == Activity.RESULT_OK) {
+ toast(R.string.wallpaper_set_successfully)
+ } else if (requestCode == REQUEST_VIEW_VIDEO && resultCode == Activity.RESULT_OK && resultData != null) {
+ if (resultData.getBooleanExtra(GO_TO_NEXT_ITEM, false)) {
+ goToNextItem()
+ } else if (resultData.getBooleanExtra(GO_TO_PREV_ITEM, false)) {
+ goToPrevItem()
+ }
+ }
+ super.onActivityResult(requestCode, resultCode, resultData)
+ }
+
+ private fun initViewPager() {
+ val uri = intent.data
+ if (uri != null) {
+ var cursor: Cursor? = null
+ try {
+ val proj = arrayOf(Images.Media.DATA)
+ cursor = contentResolver.query(uri, proj, null, null, null)
+ if (cursor?.moveToFirst() == true) {
+ mPath = cursor.getStringValue(Images.Media.DATA)
+ }
+ } finally {
+ cursor?.close()
+ }
+ } else {
+ try {
+ mPath = intent.getStringExtra(PATH)
+ mShowAll = config.showAll
+ } catch (e: Exception) {
+ showErrorToast(e)
+ finish()
+ return
+ }
+ }
+
+ if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
+ mPath = intent.extras!!.getString(REAL_FILE_PATH)!!
+ }
+
+ if (mPath.isEmpty()) {
+ toast(R.string.unknown_error_occurred)
+ finish()
+ return
+ }
+
+ if (mPath.isPortrait() && getPortraitPath() == "") {
+ val newIntent = Intent(this, ViewPagerActivity::class.java)
+ newIntent.putExtras(intent!!.extras!!)
+ newIntent.putExtra(PORTRAIT_PATH, mPath)
+ newIntent.putExtra(PATH, "${mPath.getParentPath().getParentPath()}/${mPath.getFilenameFromPath()}")
+
+ startActivity(newIntent)
+ finish()
+ return
+ }
+
+ if (!getDoesFilePathExist(mPath) && getPortraitPath() == "") {
+ finish()
+ return
+ }
+
+ showSystemUI(true)
+
+ if (intent.getBooleanExtra(SKIP_AUTHENTICATION, false)) {
+ initContinue()
+ } else {
+ handleLockedFolderOpening(mPath.getParentPath()) { success ->
+ if (success) {
+ initContinue()
+ } else {
+ finish()
+ }
+ }
+ }
+ }
+
+ private fun initContinue() {
+ if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) {
+ if (isShowHiddenFlagNeeded()) {
+ if (!config.isHiddenPasswordProtectionOn) {
+ config.temporarilyShowHidden = true
+ }
+ }
+
+ config.isThirdPartyIntent = true
+ }
+
+ val isShowingFavorites = intent.getBooleanExtra(SHOW_FAVORITES, false)
+ val isShowingRecycleBin = intent.getBooleanExtra(SHOW_RECYCLE_BIN, false)
+ mDirectory = when {
+ isShowingFavorites -> FAVORITES
+ isShowingRecycleBin -> RECYCLE_BIN
+ else -> mPath.getParentPath()
+ }
+ supportActionBar?.title = mPath.getFilenameFromPath()
+
+ view_pager.onGlobalLayout {
+ if (!isDestroyed) {
+ if (mMediaFiles.isNotEmpty()) {
+ gotMedia(mMediaFiles as ArrayList)
+ checkSlideshowOnEnter()
+ }
+ }
+ }
+
+ refreshViewPager()
+ view_pager.offscreenPageLimit = 2
+
+ if (config.blackBackground) {
+ view_pager.background = ColorDrawable(Color.BLACK)
+ }
+
+ if (config.hideSystemUI) {
+ view_pager.onGlobalLayout {
+ Handler().postDelayed({
+ fragmentClicked()
+ }, HIDE_SYSTEM_UI_DELAY)
+ }
+ }
+
+ window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
+ mIsFullScreen = if (visibility and View.SYSTEM_UI_FLAG_LOW_PROFILE == 0) {
+ false
+ } else {
+ visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
+ }
+
+ checkSystemUI()
+ fullscreenToggled()
+ }
+
+ if (intent.action == "com.android.camera.action.REVIEW") {
+ ensureBackgroundThread {
+ if (mediaDB.getMediaFromPath(mPath).isEmpty()) {
+ val type = when {
+ mPath.isVideoFast() -> TYPE_VIDEOS
+ mPath.isGif() -> TYPE_GIFS
+ mPath.isSvg() -> TYPE_SVGS
+ mPath.isRawFast() -> TYPE_RAWS
+ mPath.isPortrait() -> TYPE_PORTRAITS
+ else -> TYPE_IMAGES
+ }
+
+ val isFavorite = favoritesDB.isFavorite(mPath)
+ val duration = if (type == TYPE_VIDEOS) getDuration(mPath) ?: 0 else 0
+ val ts = System.currentTimeMillis()
+ val medium = Medium(null, mPath.getFilenameFromPath(), mPath, mPath.getParentPath(), ts, ts, File(mPath).length(), type, duration, isFavorite, 0)
+ mediaDB.insert(medium)
+ }
+ }
+ }
+ }
+
+ private fun initBottomActions() {
+ initBottomActionButtons()
+ initBottomActionsLayout()
+ }
+
+ private fun initFavorites() {
+ ensureBackgroundThread {
+ mFavoritePaths = getFavoritePaths()
+ }
+ }
+
+ private fun setupOrientation() {
+ if (!mIsOrientationLocked) {
+ if (config.screenRotation == ROTATE_BY_DEVICE_ROTATION) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
+ } else if (config.screenRotation == ROTATE_BY_SYSTEM_SETTING) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
+ }
+ }
+ }
+
+ private fun updatePagerItems(media: MutableList) {
+ val pagerAdapter = MyPagerAdapter(this, supportFragmentManager, media)
+ if (!isDestroyed) {
+ pagerAdapter.shouldInitFragment = mPos < 5
+ view_pager.apply {
+ adapter = pagerAdapter
+ pagerAdapter.shouldInitFragment = true
+ currentItem = mPos
+ removeOnPageChangeListener(this@ViewPagerActivity)
+ addOnPageChangeListener(this@ViewPagerActivity)
+ }
+ }
+ }
+
+ private fun checkSlideshowOnEnter() {
+ if (intent.getBooleanExtra(SLIDESHOW_START_ON_ENTER, false)) {
+ initSlideshow()
+ }
+ }
+
+ private fun initSlideshow() {
+ SlideshowDialog(this) {
+ startSlideshow()
+ }
+ }
+
+ private fun startSlideshow() {
+ if (getMediaForSlideshow()) {
+ view_pager.onGlobalLayout {
+ if (!isDestroyed) {
+ if (config.slideshowAnimation == SLIDESHOW_ANIMATION_FADE) {
+ view_pager.setPageTransformer(false, FadePageTransformer())
+ }
+
+ hideSystemUI(true)
+ mSlideshowInterval = config.slideshowInterval
+ mSlideshowMoveBackwards = config.slideshowMoveBackwards
+ mIsSlideshowActive = true
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ scheduleSwipe()
+ }
+ }
+ }
+ }
+
+ private fun goToNextMedium(forward: Boolean) {
+ val oldPosition = view_pager.currentItem
+ val newPosition = if (forward) oldPosition + 1 else oldPosition - 1
+ if (newPosition == -1 || newPosition > view_pager.adapter!!.count - 1) {
+ slideshowEnded(forward)
+ } else {
+ view_pager.setCurrentItem(newPosition, false)
+ }
+ }
+
+ private fun animatePagerTransition(forward: Boolean) {
+ val oldPosition = view_pager.currentItem
+ val animator = ValueAnimator.ofInt(0, view_pager.width)
+ animator.addListener(object : Animator.AnimatorListener {
+ override fun onAnimationRepeat(animation: Animator?) {
+ }
+
+ override fun onAnimationEnd(animation: Animator?) {
+ if (view_pager.isFakeDragging) {
+ try {
+ view_pager.endFakeDrag()
+ } catch (ignored: Exception) {
+ stopSlideshow()
+ }
+
+ if (view_pager.currentItem == oldPosition) {
+ slideshowEnded(forward)
+ }
+ }
+ }
+
+ override fun onAnimationCancel(animation: Animator?) {
+ view_pager.endFakeDrag()
+ }
+
+ override fun onAnimationStart(animation: Animator?) {
+ }
+ })
+
+ if (config.slideshowAnimation == SLIDESHOW_ANIMATION_SLIDE) {
+ animator.interpolator = DecelerateInterpolator()
+ animator.duration = SLIDESHOW_SLIDE_DURATION
+ } else {
+ animator.duration = SLIDESHOW_FADE_DURATION
+ }
+
+ animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
+ var oldDragPosition = 0
+ override fun onAnimationUpdate(animation: ValueAnimator) {
+ if (view_pager?.isFakeDragging == true) {
+ val dragPosition = animation.animatedValue as Int
+ val dragOffset = dragPosition - oldDragPosition
+ oldDragPosition = dragPosition
+ try {
+ view_pager.fakeDragBy(dragOffset * (if (forward) -1f else 1f))
+ } catch (e: Exception) {
+ stopSlideshow()
+ }
+ }
+ }
+ })
+
+ view_pager.beginFakeDrag()
+ animator.start()
+ }
+
+ private fun slideshowEnded(forward: Boolean) {
+ if (config.loopSlideshow) {
+ if (forward) {
+ view_pager.setCurrentItem(0, false)
+ } else {
+ view_pager.setCurrentItem(view_pager.adapter!!.count - 1, false)
+ }
+ } else {
+ stopSlideshow()
+ toast(R.string.slideshow_ended)
+ }
+ }
+
+ private fun stopSlideshow() {
+ if (mIsSlideshowActive) {
+ view_pager.setPageTransformer(false, DefaultPageTransformer())
+ mIsSlideshowActive = false
+ showSystemUI(true)
+ mSlideshowHandler.removeCallbacksAndMessages(null)
+ window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+ }
+
+ private fun scheduleSwipe() {
+ mSlideshowHandler.removeCallbacksAndMessages(null)
+ if (mIsSlideshowActive) {
+ if (getCurrentMedium()!!.isImage() || getCurrentMedium()!!.isGIF() || getCurrentMedium()!!.isPortrait()) {
+ mSlideshowHandler.postDelayed({
+ if (mIsSlideshowActive && !isDestroyed) {
+ swipeToNextMedium()
+ }
+ }, mSlideshowInterval * 1000L)
+ } else {
+ (getCurrentFragment() as? VideoFragment)!!.playVideo()
+ }
+ }
+ }
+
+ private fun swipeToNextMedium() {
+ if (config.slideshowAnimation == SLIDESHOW_ANIMATION_NONE) {
+ goToNextMedium(!mSlideshowMoveBackwards)
+ } else {
+ animatePagerTransition(!mSlideshowMoveBackwards)
+ }
+ }
+
+ private fun getMediaForSlideshow(): Boolean {
+ mSlideshowMedia = mMediaFiles.filter {
+ it.isImage() || it.isPortrait() || (config.slideshowIncludeVideos && it.isVideo() || (config.slideshowIncludeGIFs && it.isGIF()))
+ }.toMutableList()
+
+ if (config.slideshowRandomOrder) {
+ mSlideshowMedia.shuffle()
+ mPos = 0
+ } else {
+ mPath = getCurrentPath()
+ mPos = getPositionInList(mSlideshowMedia)
+ }
+
+ return if (mSlideshowMedia.isEmpty()) {
+ toast(R.string.no_media_for_slideshow)
+ false
+ } else {
+ updatePagerItems(mSlideshowMedia)
+ mAreSlideShowMediaVisible = true
+ true
+ }
+ }
+
+ private fun moveFileTo() {
+ handleDeletePasswordProtection {
+ copyMoveTo(false)
+ }
+ }
+
+ private fun copyMoveTo(isCopyOperation: Boolean) {
+ val currPath = getCurrentPath()
+ if (!isCopyOperation && currPath.startsWith(recycleBinPath)) {
+ toast(R.string.moving_recycle_bin_items_disabled, Toast.LENGTH_LONG)
+ return
+ }
+
+ val fileDirItems = arrayListOf(FileDirItem(currPath, currPath.getFilenameFromPath()))
+ tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
+ val newPath = "$it/${currPath.getFilenameFromPath()}"
+ rescanPaths(arrayListOf(newPath)) {
+ fixDateTaken(arrayListOf(newPath), false)
+ }
+
+ config.tempFolderPath = ""
+ if (!isCopyOperation) {
+ refreshViewPager()
+ updateFavoritePaths(fileDirItems, it)
+ }
+ }
+ }
+
+ private fun toggleFileVisibility(hide: Boolean, callback: (() -> Unit)? = null) {
+ toggleFileVisibility(getCurrentPath(), hide) {
+ val newFileName = it.getFilenameFromPath()
+ supportActionBar?.title = newFileName
+
+ getCurrentMedium()!!.apply {
+ name = newFileName
+ path = it
+ getCurrentMedia()[mPos] = this
+ }
+ invalidateOptionsMenu()
+ callback?.invoke()
+ }
+ }
+
+ private fun rotateImage(degrees: Int) {
+ val currentPath = getCurrentPath()
+ if (needsStupidWritePermissions(currentPath)) {
+ handleSAFDialog(currentPath) {
+ if (it) {
+ rotateBy(degrees)
+ }
+ }
+ } else {
+ rotateBy(degrees)
+ }
+ }
+
+ private fun rotateBy(degrees: Int) {
+ getCurrentPhotoFragment()?.rotateImageViewBy(degrees)
+ supportInvalidateOptionsMenu()
+ }
+
+ private fun toggleOrientation(orientation: Int) {
+ requestedOrientation = orientation
+ mIsOrientationLocked = orientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
+ invalidateOptionsMenu()
+ }
+
+ private fun getChangeOrientationIcon(): Int {
+ return if (mIsOrientationLocked) {
+ if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
+ R.drawable.ic_orientation_portrait_vector
+ } else {
+ R.drawable.ic_orientation_landscape_vector
+ }
+ } else {
+ R.drawable.ic_orientation_auto_vector
+ }
+ }
+
+ private fun saveImageAs() {
+ val currPath = getCurrentPath()
+ SaveAsDialog(this, currPath, false) {
+ val newPath = it
+ handleSAFDialog(it) {
+ if (!it) {
+ return@handleSAFDialog
+ }
+
+ toast(R.string.saving)
+ ensureBackgroundThread {
+ val photoFragment = getCurrentPhotoFragment() ?: return@ensureBackgroundThread
+ saveRotatedImageToFile(currPath, newPath, photoFragment.mCurrentRotationDegrees, true) {
+ toast(R.string.file_saved)
+ getCurrentPhotoFragment()?.mCurrentRotationDegrees = 0
+ invalidateOptionsMenu()
+ }
+ }
+ }
+ }
+ }
+
+ @SuppressLint("NewApi")
+ private fun createShortcut() {
+ val manager = getSystemService(ShortcutManager::class.java)
+ if (manager.isRequestPinShortcutSupported) {
+ val medium = getCurrentMedium() ?: return
+ val path = medium.path
+ val drawable = resources.getDrawable(R.drawable.shortcut_image).mutate()
+ getShortcutImage(path, drawable) {
+ val intent = Intent(this, ViewPagerActivity::class.java).apply {
+ putExtra(PATH, path)
+ putExtra(SHOW_ALL, config.showAll)
+ putExtra(SHOW_FAVORITES, path == FAVORITES)
+ putExtra(SHOW_RECYCLE_BIN, path == RECYCLE_BIN)
+ action = Intent.ACTION_VIEW
+ flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
+ }
+
+ val shortcut = ShortcutInfo.Builder(this, path)
+ .setShortLabel(medium.name)
+ .setIcon(Icon.createWithBitmap(drawable.convertToBitmap()))
+ .setIntent(intent)
+ .build()
+
+ manager.requestPinShortcut(shortcut, null)
+ }
+ }
+ }
+
+ private fun getCurrentPhotoFragment() = getCurrentFragment() as? PhotoFragment
+
+ private fun getPortraitPath() = intent.getStringExtra(PORTRAIT_PATH) ?: ""
+
+ private fun isShowHiddenFlagNeeded(): Boolean {
+ val file = File(mPath)
+ if (file.isHidden) {
+ return true
+ }
+
+ var parent = file.parentFile ?: return false
+ while (true) {
+ if (parent.isHidden || parent.list()?.any { it.startsWith(NOMEDIA) } == true) {
+ return true
+ }
+
+ if (parent.absolutePath == "/") {
+ break
+ }
+ parent = parent.parentFile ?: return false
+ }
+
+ return false
+ }
+
+ private fun getCurrentFragment() = (view_pager.adapter as? MyPagerAdapter)?.getCurrentFragment(view_pager.currentItem)
+
+ private fun showProperties() {
+ if (getCurrentMedium() != null) {
+ PropertiesDialog(this, getCurrentPath(), false)
+ }
+ }
+
+ private fun initBottomActionsLayout() {
+ bottom_actions.layoutParams.height = resources.getDimension(R.dimen.bottom_actions_height).toInt() + navigationBarHeight
+ if (config.bottomActions) {
+ bottom_actions.beVisible()
+ } else {
+ bottom_actions.beGone()
+ }
+ }
+
+ private fun initBottomActionButtons() {
+ val currentMedium = getCurrentMedium()
+ val visibleBottomActions = if (config.bottomActions) config.visibleBottomActions else 0
+ bottom_favorite.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_TOGGLE_FAVORITE != 0 && currentMedium?.getIsInRecycleBin() == false)
+ bottom_favorite.setOnClickListener {
+ toggleFavorite()
+ }
+
+ bottom_edit.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_EDIT != 0 && currentMedium?.isSVG() == false)
+ bottom_edit.setOnClickListener {
+ openEditor(getCurrentPath())
+ }
+
+ bottom_share.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SHARE != 0)
+ bottom_share.setOnClickListener {
+ shareMediumPath(getCurrentPath())
+ }
+
+ bottom_delete.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_DELETE != 0)
+ bottom_delete.setOnClickListener {
+ checkDeleteConfirmation()
+ }
+
+ bottom_rotate.setOnClickListener {
+ rotateImage(90)
+ }
+
+ bottom_properties.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_PROPERTIES != 0)
+ bottom_properties.setOnClickListener {
+ showProperties()
+ }
+
+ bottom_change_orientation.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_CHANGE_ORIENTATION != 0)
+ bottom_change_orientation.setOnClickListener {
+ requestedOrientation = when (requestedOrientation) {
+ ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
+ ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
+ else -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+ }
+ mIsOrientationLocked = requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
+ updateBottomActionIcons(currentMedium)
+ }
+
+ bottom_slideshow.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SLIDESHOW != 0)
+ bottom_slideshow.setOnClickListener {
+ initSlideshow()
+ }
+
+ bottom_show_on_map.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SHOW_ON_MAP != 0)
+ bottom_show_on_map.setOnClickListener {
+ showFileOnMap(getCurrentPath())
+ }
+
+ bottom_toggle_file_visibility.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_TOGGLE_VISIBILITY != 0)
+ bottom_toggle_file_visibility.setOnClickListener {
+ currentMedium?.apply {
+ toggleFileVisibility(!isHidden()) {
+ updateBottomActionIcons(currentMedium)
+ }
+ }
+ }
+
+ bottom_rename.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_RENAME != 0 && currentMedium?.getIsInRecycleBin() == false)
+ bottom_rename.setOnClickListener {
+ renameFile()
+ }
+
+ bottom_set_as.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SET_AS != 0)
+ bottom_set_as.setOnClickListener {
+ setAs(getCurrentPath())
+ }
+
+ bottom_copy.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_COPY != 0)
+ bottom_copy.setOnClickListener {
+ copyMoveTo(true)
+ }
+
+ bottom_move.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_MOVE != 0)
+ bottom_move.setOnClickListener {
+ moveFileTo()
+ }
+
+ bottom_resize.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_RESIZE != 0 && currentMedium?.isImage() == true)
+ bottom_resize.setOnClickListener {
+ resizeImage()
+ }
+ }
+
+ private fun updateBottomActionIcons(medium: Medium?) {
+ if (medium == null) {
+ return
+ }
+
+ val favoriteIcon = if (medium.isFavorite) R.drawable.ic_star_on_vector else R.drawable.ic_star_off_vector
+ bottom_favorite.setImageResource(favoriteIcon)
+
+ val hideIcon = if (medium.isHidden()) R.drawable.ic_unhide_vector else R.drawable.ic_hide
+ bottom_toggle_file_visibility.setImageResource(hideIcon)
+
+ bottom_rotate.beVisibleIf(config.visibleBottomActions and BOTTOM_ACTION_ROTATE != 0 && getCurrentMedium()?.isImage() == true)
+ bottom_change_orientation.setImageResource(getChangeOrientationIcon())
+ }
+
+ private fun toggleFavorite() {
+ val medium = getCurrentMedium() ?: return
+ medium.isFavorite = !medium.isFavorite
+ ensureBackgroundThread {
+ updateFavorite(medium.path, medium.isFavorite)
+ if (medium.isFavorite) {
+ mFavoritePaths.add(medium.path)
+ } else {
+ mFavoritePaths.remove(medium.path)
+ }
+ invalidateOptionsMenu()
+ }
+ }
+
+ private fun printFile() {
+ sendPrintIntent(getCurrentPath())
+ }
+
+ private fun sendPrintIntent(path: String) {
+ val printHelper = PrintHelper(this)
+ printHelper.scaleMode = PrintHelper.SCALE_MODE_FIT
+ printHelper.orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+
+ try {
+ val resolution = path.getImageResolution()
+ if (resolution == null) {
+ toast(R.string.unknown_error_occurred)
+ return
+ }
+
+ var requestedWidth = resolution.x
+ var requestedHeight = resolution.y
+
+ if (requestedWidth >= MAX_PRINT_SIDE_SIZE) {
+ requestedHeight = (requestedHeight / (requestedWidth / MAX_PRINT_SIDE_SIZE.toFloat())).toInt()
+ requestedWidth = MAX_PRINT_SIDE_SIZE
+ } else if (requestedHeight >= MAX_PRINT_SIDE_SIZE) {
+ requestedWidth = (requestedWidth / (requestedHeight / MAX_PRINT_SIDE_SIZE.toFloat())).toInt()
+ requestedHeight = MAX_PRINT_SIDE_SIZE
+ }
+
+ val options = RequestOptions()
+ .skipMemoryCache(true)
+ .diskCacheStrategy(DiskCacheStrategy.NONE)
+
+ Glide.with(this)
+ .asBitmap()
+ .load(path)
+ .apply(options)
+ .listener(object : RequestListener {
+ override fun onLoadFailed(e: GlideException?, model: Any?, target: Target?, isFirstResource: Boolean): Boolean {
+ showErrorToast(e?.localizedMessage ?: "")
+ return false
+ }
+
+ override fun onResourceReady(bitmap: Bitmap?, model: Any?, target: Target?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
+ if (bitmap != null) {
+ printHelper.printBitmap(path.getFilenameFromPath(), bitmap)
+ }
+
+ return false
+ }
+ }).submit(requestedWidth, requestedHeight)
+ } catch (e: Exception) {
+ }
+ }
+
+ private fun restoreFile() {
+ restoreRecycleBinPath(getCurrentPath()) {
+ refreshViewPager()
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.N)
+ private fun resizeImage() {
+ val oldPath = getCurrentPath()
+ val originalSize = oldPath.getImageResolution() ?: return
+ ResizeWithPathDialog(this, originalSize, oldPath) { newSize, newPath ->
+ ensureBackgroundThread {
+ try {
+ var oldExif: ExifInterface? = null
+ if (isNougatPlus()) {
+ val inputStream = contentResolver.openInputStream(Uri.fromFile(File(oldPath)))
+ oldExif = ExifInterface(inputStream!!)
+ }
+
+ val newBitmap = Glide.with(applicationContext).asBitmap().load(oldPath).submit(newSize.x, newSize.y).get()
+
+ val newFile = File(newPath)
+ val newFileDirItem = FileDirItem(newPath, newPath.getFilenameFromPath())
+ getFileOutputStream(newFileDirItem, true) {
+ if (it != null) {
+ saveBitmap(newFile, newBitmap, it, oldExif, File(oldPath).lastModified())
+ } else {
+ toast(R.string.image_editing_failed)
+ }
+ }
+ } catch (e: OutOfMemoryError) {
+ toast(R.string.out_of_memory_error)
+ } catch (e: Exception) {
+ showErrorToast(e)
+ }
+ }
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.N)
+ private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream, oldExif: ExifInterface?, lastModified: Long) {
+ try {
+ bitmap.compress(file.absolutePath.getCompressionFormat(), 90, out)
+
+ if (isNougatPlus()) {
+ val newExif = ExifInterface(file.absolutePath)
+ oldExif?.copyNonDimensionAttributesTo(newExif)
+ }
+ } catch (e: Exception) {
+ }
+
+ toast(R.string.file_saved)
+ val paths = arrayListOf(file.absolutePath)
+ rescanPaths(paths) {
+ fixDateTaken(paths, false)
+
+ if (config.keepLastModified) {
+ File(file.absolutePath).setLastModified(lastModified)
+ updateLastModified(file.absolutePath, lastModified)
+ }
+ }
+ out.close()
+ }
+
+ private fun checkDeleteConfirmation() {
+ if (getCurrentMedium() == null) {
+ return
+ }
+
+ if (config.isDeletePasswordProtectionOn) {
+ handleDeletePasswordProtection {
+ deleteConfirmed()
+ }
+ } else if (config.tempSkipDeleteConfirmation || config.skipDeleteConfirmation) {
+ deleteConfirmed()
+ } else {
+ askConfirmDelete()
+ }
+ }
+
+ private fun askConfirmDelete() {
+ val filename = "\"${getCurrentPath().getFilenameFromPath()}\""
+
+ val baseString = if (config.useRecycleBin && !getCurrentMedium()!!.getIsInRecycleBin()) {
+ R.string.move_to_recycle_bin_confirmation
+ } else {
+ R.string.deletion_confirmation
+ }
+
+ val message = String.format(resources.getString(baseString), filename)
+ DeleteWithRememberDialog(this, message) {
+ config.tempSkipDeleteConfirmation = it
+ deleteConfirmed()
+ }
+ }
+
+ private fun deleteConfirmed() {
+ val path = getCurrentMedia().getOrNull(mPos)?.path ?: return
+ if (getIsPathDirectory(path) || !path.isMediaFile()) {
+ return
+ }
+
+ val fileDirItem = FileDirItem(path, path.getFilenameFromPath())
+ if (config.useRecycleBin && !getCurrentMedium()!!.getIsInRecycleBin()) {
+ mIgnoredPaths.add(fileDirItem.path)
+ val media = mMediaFiles.filter { !mIgnoredPaths.contains(it.path) } as ArrayList
+ runOnUiThread {
+ gotMedia(media, true)
+ }
+
+ movePathsInRecycleBin(arrayListOf(path)) {
+ if (it) {
+ tryDeleteFileDirItem(fileDirItem, false, false) {
+ mIgnoredPaths.remove(fileDirItem.path)
+ deleteDirectoryIfEmpty()
+ }
+ } else {
+ toast(R.string.unknown_error_occurred)
+ }
+ }
+ } else {
+ handleDeletion(fileDirItem)
+ }
+ }
+
+ private fun handleDeletion(fileDirItem: FileDirItem) {
+ mIgnoredPaths.add(fileDirItem.path)
+ val media = mMediaFiles.filter { !mIgnoredPaths.contains(it.path) } as ArrayList
+ runOnUiThread {
+ gotMedia(media, true)
+ }
+
+ tryDeleteFileDirItem(fileDirItem, false, true) {
+ mIgnoredPaths.remove(fileDirItem.path)
+ deleteDirectoryIfEmpty()
+ }
+ }
+
+ private fun isDirEmpty(media: ArrayList): Boolean {
+ return if (media.isEmpty()) {
+ deleteDirectoryIfEmpty()
+ finish()
+ true
+ } else {
+ false
+ }
+ }
+
+ private fun renameFile() {
+ val oldPath = getCurrentPath()
+ RenameItemDialog(this, oldPath) {
+ getCurrentMedia()[mPos].apply {
+ path = it
+ name = it.getFilenameFromPath()
+ }
+
+ ensureBackgroundThread {
+ updateDBMediaPath(oldPath, it)
+ }
+ updateActionbarTitle()
+ }
+ }
+
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ initBottomActionsLayout()
+ }
+
+ private fun refreshViewPager() {
+ if (config.getFolderSorting(mDirectory) and SORT_BY_RANDOM == 0) {
+ GetMediaAsynctask(applicationContext, mDirectory, false, false, mShowAll) {
+ gotMedia(it)
+ }.execute()
+ }
+ }
+
+ private fun gotMedia(thumbnailItems: ArrayList, ignorePlayingVideos: Boolean = false) {
+ val media = thumbnailItems.asSequence().filter { it is Medium && !mIgnoredPaths.contains(it.path) }.map { it as Medium }.toMutableList() as ArrayList
+ if (isDirEmpty(media) || media.hashCode() == mPrevHashcode) {
+ return
+ }
+
+ if (!ignorePlayingVideos && (getCurrentFragment() as? VideoFragment)?.mIsPlaying == true) {
+ return
+ }
+
+ mPrevHashcode = media.hashCode()
+ mMediaFiles = media
+ mPos = if (mPos == -1) {
+ getPositionInList(media)
+ } else {
+ Math.min(mPos, mMediaFiles.size - 1)
+ }
+
+ updateActionbarTitle()
+ updatePagerItems(mMediaFiles.toMutableList())
+ invalidateOptionsMenu()
+ checkOrientation()
+ initBottomActions()
+ }
+
+ private fun getPositionInList(items: MutableList): Int {
+ mPos = 0
+ for ((i, medium) in items.withIndex()) {
+ val portraitPath = getPortraitPath()
+ if (portraitPath != "") {
+ val portraitPaths = File(portraitPath).parentFile?.list()
+ if (portraitPaths != null) {
+ for (path in portraitPaths) {
+ if (medium.name == path) {
+ return i
+ }
+ }
+ }
+ } else if (medium.path == mPath) {
+ return i
+ }
+ }
+ return mPos
+ }
+
+ private fun deleteDirectoryIfEmpty() {
+ val fileDirItem = FileDirItem(mDirectory, mDirectory.getFilenameFromPath(), File(mDirectory).isDirectory)
+ if (config.deleteEmptyFolders && !fileDirItem.isDownloadsFolder() && fileDirItem.isDirectory && fileDirItem.getProperFileCount(this, true) == 0) {
+ tryDeleteFileDirItem(fileDirItem, true, true)
+ scanPathRecursively(mDirectory)
+ }
+ }
+
+ @SuppressLint("SourceLockedOrientationActivity")
+ private fun checkOrientation() {
+ if (!mIsOrientationLocked && config.screenRotation == ROTATE_BY_ASPECT_RATIO) {
+ var flipSides = false
+ try {
+ val pathToLoad = getCurrentPath()
+ val exif = ExifInterface(pathToLoad)
+ val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)
+ flipSides = orientation == ExifInterface.ORIENTATION_ROTATE_90 || orientation == ExifInterface.ORIENTATION_ROTATE_270
+ } catch (e: Exception) {
+ }
+ val resolution = applicationContext.getResolution(getCurrentPath()) ?: return
+ val width = if (flipSides) resolution.y else resolution.x
+ val height = if (flipSides) resolution.x else resolution.y
+ if (width > height) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
+ } else if (width < height) {
+ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+ }
+ }
+ }
+
+ override fun fragmentClicked() {
+ mIsFullScreen = !mIsFullScreen
+ checkSystemUI()
+ fullscreenToggled()
+ }
+
+ override fun videoEnded(): Boolean {
+ if (mIsSlideshowActive) {
+ swipeToNextMedium()
+ }
+ return mIsSlideshowActive
+ }
+
+ override fun isSlideShowActive() = mIsSlideshowActive
+
+ override fun goToPrevItem() {
+ view_pager.setCurrentItem(view_pager.currentItem - 1, false)
+ checkOrientation()
+ }
+
+ override fun goToNextItem() {
+ view_pager.setCurrentItem(view_pager.currentItem + 1, false)
+ checkOrientation()
+ }
+
+ override fun launchViewVideoIntent(path: String) {
+ ensureBackgroundThread {
+ val newUri = getFinalUriFromPath(path, BuildConfig.APPLICATION_ID) ?: return@ensureBackgroundThread
+ val mimeType = getUriMimeType(path, newUri)
+ Intent().apply {
+ action = Intent.ACTION_VIEW
+ setDataAndType(newUri, mimeType)
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ putExtra(IS_FROM_GALLERY, true)
+ putExtra(REAL_FILE_PATH, path)
+ putExtra(SHOW_PREV_ITEM, view_pager.currentItem != 0)
+ putExtra(SHOW_NEXT_ITEM, view_pager.currentItem != mMediaFiles.size - 1)
+
+ if (resolveActivity(packageManager) != null) {
+ try {
+ startActivityForResult(this, REQUEST_VIEW_VIDEO)
+ } catch (e: NullPointerException) {
+ showErrorToast(e)
+ }
+ } else {
+ if (!tryGenericMimeType(this, mimeType, newUri)) {
+ toast(R.string.no_app_found)
+ }
+ }
+ }
+ }
+ }
+
+ private fun checkSystemUI() {
+ if (mIsFullScreen) {
+ hideSystemUI(true)
+ } else {
+ stopSlideshow()
+ showSystemUI(true)
+ }
+ }
+
+ private fun fullscreenToggled() {
+ view_pager.adapter?.let {
+ (it as MyPagerAdapter).toggleFullscreen(mIsFullScreen)
+ val newAlpha = if (mIsFullScreen) 0f else 1f
+ top_shadow.animate().alpha(newAlpha).start()
+ if (bottom_actions.isVisible()) {
+ bottom_actions.animate().alpha(newAlpha).start()
+ arrayOf(bottom_favorite, bottom_edit, bottom_share, bottom_delete, bottom_rotate, bottom_properties, bottom_change_orientation,
+ bottom_slideshow, bottom_show_on_map, bottom_toggle_file_visibility, bottom_rename, bottom_set_as, bottom_copy, bottom_move,
+ bottom_resize).forEach {
+ it.isClickable = !mIsFullScreen
+ }
+ }
+ }
+ }
+
+ private fun updateActionbarTitle() {
+ runOnUiThread {
+ if (mPos < getCurrentMedia().size) {
+ supportActionBar?.title = getCurrentMedia()[mPos].path.getFilenameFromPath()
+ }
+ }
+ }
+
+ private fun getCurrentMedium(): Medium? {
+ return if (getCurrentMedia().isEmpty() || mPos == -1) {
+ null
+ } else {
+ getCurrentMedia()[Math.min(mPos, getCurrentMedia().size - 1)]
+ }
+ }
+
+ private fun getCurrentMedia() = if (mAreSlideShowMediaVisible) mSlideshowMedia else mMediaFiles
+
+ private fun getCurrentPath() = getCurrentMedium()?.path ?: ""
+
+ override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
+
+ override fun onPageSelected(position: Int) {
+ if (mPos != position) {
+ mPos = position
+ updateActionbarTitle()
+ invalidateOptionsMenu()
+ scheduleSwipe()
+ }
+ }
+
+ override fun onPageScrollStateChanged(state: Int) {
+ if (state == ViewPager.SCROLL_STATE_IDLE && getCurrentMedium() != null) {
+ checkOrientation()
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/WidgetConfigureActivity.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/WidgetConfigureActivity.kt
new file mode 100644
index 000000000..4521e64a1
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/WidgetConfigureActivity.kt
@@ -0,0 +1,183 @@
+package com.simplemobiletools.gallery.pro.activities
+
+import android.app.Activity
+import android.appwidget.AppWidgetManager
+import android.content.Intent
+import android.graphics.Color
+import android.graphics.drawable.ColorDrawable
+import android.os.Bundle
+import android.widget.RelativeLayout
+import android.widget.RemoteViews
+import com.bumptech.glide.signature.ObjectKey
+import com.simplemobiletools.commons.dialogs.ColorPickerDialog
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.ensureBackgroundThread
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.dialogs.PickDirectoryDialog
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.MyWidgetProvider
+import com.simplemobiletools.gallery.pro.helpers.ROUNDED_CORNERS_NONE
+import com.simplemobiletools.gallery.pro.models.Directory
+import com.simplemobiletools.gallery.pro.models.Widget
+import kotlinx.android.synthetic.main.activity_widget_config.*
+
+class WidgetConfigureActivity : SimpleActivity() {
+ private var mBgAlpha = 0f
+ private var mWidgetId = 0
+ private var mBgColor = 0
+ private var mBgColorWithoutTransparency = 0
+ private var mTextColor = 0
+ private var mFolderPath = ""
+ private var mDirectories = ArrayList()
+
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ useDynamicTheme = false
+ super.onCreate(savedInstanceState)
+ setResult(RESULT_CANCELED)
+ setContentView(R.layout.activity_widget_config)
+ initVariables()
+
+ mWidgetId = intent.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID
+
+ if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
+ finish()
+ }
+
+ config_save.setOnClickListener { saveConfig() }
+ config_bg_color.setOnClickListener { pickBackgroundColor() }
+ config_text_color.setOnClickListener { pickTextColor() }
+ folder_picker_value.setOnClickListener { changeSelectedFolder() }
+ config_image_holder.setOnClickListener { changeSelectedFolder() }
+ folder_picker_show_folder_name.isChecked = config.showWidgetFolderName
+ handleFolderNameDisplay()
+ folder_picker_show_folder_name_holder.setOnClickListener {
+ folder_picker_show_folder_name.toggle()
+ handleFolderNameDisplay()
+ }
+
+ updateTextColors(folder_picker_holder)
+ folder_picker_holder.background = ColorDrawable(config.backgroundColor)
+
+ getCachedDirectories(false, false) {
+ mDirectories = it
+ val path = it.firstOrNull()?.path
+ if (path != null) {
+ updateFolderImage(path)
+ }
+ }
+ }
+
+ private fun initVariables() {
+ mBgColor = config.widgetBgColor
+ mBgAlpha = Color.alpha(mBgColor) / 255f
+
+ mBgColorWithoutTransparency = Color.rgb(Color.red(mBgColor), Color.green(mBgColor), Color.blue(mBgColor))
+ config_bg_seekbar.apply {
+ progress = (mBgAlpha * 100).toInt()
+
+ onSeekBarChangeListener {
+ mBgAlpha = it / 100f
+ updateBackgroundColor()
+ }
+ }
+ updateBackgroundColor()
+
+ mTextColor = config.widgetTextColor
+ updateTextColor()
+ }
+
+ private fun saveConfig() {
+ val views = RemoteViews(packageName, R.layout.widget)
+ views.setBackgroundColor(R.id.widget_holder, mBgColor)
+ AppWidgetManager.getInstance(this).updateAppWidget(mWidgetId, views)
+ config.showWidgetFolderName = folder_picker_show_folder_name.isChecked
+ val widget = Widget(null, mWidgetId, mFolderPath)
+ ensureBackgroundThread {
+ widgetsDB.insertOrUpdate(widget)
+ }
+
+ storeWidgetColors()
+ requestWidgetUpdate()
+
+ Intent().apply {
+ putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId)
+ setResult(Activity.RESULT_OK, this)
+ }
+ finish()
+ }
+
+ private fun storeWidgetColors() {
+ config.apply {
+ widgetBgColor = mBgColor
+ widgetTextColor = mTextColor
+ }
+ }
+
+ private fun requestWidgetUpdate() {
+ Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidgetProvider::class.java).apply {
+ putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(mWidgetId))
+ sendBroadcast(this)
+ }
+ }
+
+ private fun updateBackgroundColor() {
+ mBgColor = mBgColorWithoutTransparency.adjustAlpha(mBgAlpha)
+ config_save.setBackgroundColor(mBgColor)
+ config_image_holder.setBackgroundColor(mBgColor)
+ config_bg_color.setFillWithStroke(mBgColor, Color.BLACK)
+ }
+
+ private fun updateTextColor() {
+ config_save.setTextColor(mTextColor)
+ config_folder_name.setTextColor(mTextColor)
+ config_text_color.setFillWithStroke(mTextColor, Color.BLACK)
+ }
+
+ private fun pickBackgroundColor() {
+ ColorPickerDialog(this, mBgColorWithoutTransparency) { wasPositivePressed, color ->
+ if (wasPositivePressed) {
+ mBgColorWithoutTransparency = color
+ updateBackgroundColor()
+ }
+ }
+ }
+
+ private fun pickTextColor() {
+ ColorPickerDialog(this, mTextColor) { wasPositivePressed, color ->
+ if (wasPositivePressed) {
+ mTextColor = color
+ updateTextColor()
+ }
+ }
+ }
+
+ private fun changeSelectedFolder() {
+ PickDirectoryDialog(this, "", false, true) {
+ updateFolderImage(it)
+ }
+ }
+
+ private fun updateFolderImage(folderPath: String) {
+ mFolderPath = folderPath
+ runOnUiThread {
+ folder_picker_value.text = getFolderNameFromPath(folderPath)
+ config_folder_name.text = getFolderNameFromPath(folderPath)
+ }
+
+ ensureBackgroundThread {
+ val path = directoryDao.getDirectoryThumbnail(folderPath)
+ if (path != null) {
+ runOnUiThread {
+ val signature = ObjectKey(System.currentTimeMillis().toString())
+ loadJpg(path, config_image, config.cropThumbnails, ROUNDED_CORNERS_NONE, signature)
+ }
+ }
+ }
+ }
+
+ private fun handleFolderNameDisplay() {
+ val showFolderName = folder_picker_show_folder_name.isChecked
+ config_folder_name.beVisibleIf(showFolderName)
+ (config_image.layoutParams as RelativeLayout.LayoutParams).bottomMargin = if (showFolderName) 0 else resources.getDimension(R.dimen.normal_margin).toInt()
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/DirectoryAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/DirectoryAdapter.kt
new file mode 100644
index 000000000..177bb91e8
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/DirectoryAdapter.kt
@@ -0,0 +1,760 @@
+package com.simplemobiletools.gallery.pro.adapters
+
+import android.annotation.SuppressLint
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.ColorDrawable
+import android.graphics.drawable.Icon
+import android.text.TextUtils
+import android.view.Menu
+import android.view.View
+import android.view.ViewGroup
+import android.widget.RelativeLayout
+import com.bumptech.glide.Glide
+import com.google.gson.Gson
+import com.simplemobiletools.commons.activities.BaseSimpleActivity
+import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
+import com.simplemobiletools.commons.dialogs.*
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.*
+import com.simplemobiletools.commons.models.FileDirItem
+import com.simplemobiletools.commons.views.FastScroller
+import com.simplemobiletools.commons.views.MyRecyclerView
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.activities.MediaActivity
+import com.simplemobiletools.gallery.pro.dialogs.ConfirmDeleteFolderDialog
+import com.simplemobiletools.gallery.pro.dialogs.ExcludeFolderDialog
+import com.simplemobiletools.gallery.pro.dialogs.PickMediumDialog
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.interfaces.DirectoryOperationsListener
+import com.simplemobiletools.gallery.pro.models.AlbumCover
+import com.simplemobiletools.gallery.pro.models.Directory
+import kotlinx.android.synthetic.main.directory_item_grid_square.view.dir_check
+import kotlinx.android.synthetic.main.directory_item_grid_square.view.dir_location
+import kotlinx.android.synthetic.main.directory_item_grid_square.view.dir_lock
+import kotlinx.android.synthetic.main.directory_item_grid_square.view.dir_name
+import kotlinx.android.synthetic.main.directory_item_grid_square.view.dir_pin
+import kotlinx.android.synthetic.main.directory_item_grid_square.view.dir_thumbnail
+import kotlinx.android.synthetic.main.directory_item_list.view.*
+import java.io.File
+
+class DirectoryAdapter(activity: BaseSimpleActivity, var dirs: ArrayList, val listener: DirectoryOperationsListener?, recyclerView: MyRecyclerView,
+ val isPickIntent: Boolean, fastScroller: FastScroller? = null, itemClick: (Any) -> Unit) :
+ MyRecyclerViewAdapter(activity, recyclerView, fastScroller, itemClick) {
+
+ private val config = activity.config
+ private val isListViewType = config.viewTypeFolders == VIEW_TYPE_LIST
+ private var pinnedFolders = config.pinnedFolders
+ private var scrollHorizontally = config.scrollHorizontally
+ private var animateGifs = config.animateGifs
+ private var cropThumbnails = config.cropThumbnails
+ private var groupDirectSubfolders = config.groupDirectSubfolders
+ private var currentDirectoriesHash = dirs.hashCode()
+ private var lockedFolderPaths = ArrayList()
+
+ private var showMediaCount = config.showFolderMediaCount
+ private var folderStyle = config.folderStyle
+ private var limitFolderTitle = config.limitFolderTitle
+
+ init {
+ setupDragListener(true)
+ fillLockedFolders()
+ }
+
+ override fun getActionMenuId() = R.menu.cab_directories
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
+ val layoutType = when {
+ isListViewType -> R.layout.directory_item_list
+ folderStyle == FOLDER_STYLE_SQUARE -> R.layout.directory_item_grid_square
+ else -> R.layout.directory_item_grid_rounded_corners
+ }
+
+ return createViewHolder(layoutType, parent)
+ }
+
+ override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) {
+ val dir = dirs.getOrNull(position) ?: return
+ holder.bindView(dir, true, !isPickIntent) { itemView, adapterPosition ->
+ setupView(itemView, dir)
+ }
+ bindViewHolder(holder)
+ }
+
+ override fun getItemCount() = dirs.size
+
+ override fun prepareActionMode(menu: Menu) {
+ val selectedPaths = getSelectedPaths()
+ if (selectedPaths.isEmpty()) {
+ return
+ }
+
+ val isOneItemSelected = isOneItemSelected()
+ menu.apply {
+ findItem(R.id.cab_rename).isVisible = !selectedPaths.contains(FAVORITES) && !selectedPaths.contains(RECYCLE_BIN)
+ findItem(R.id.cab_change_cover_image).isVisible = isOneItemSelected
+
+ findItem(R.id.cab_lock).isVisible = selectedPaths.any { !config.isFolderProtected(it) }
+ findItem(R.id.cab_unlock).isVisible = selectedPaths.any { config.isFolderProtected(it) }
+
+ findItem(R.id.cab_empty_recycle_bin).isVisible = isOneItemSelected && selectedPaths.first() == RECYCLE_BIN
+ findItem(R.id.cab_empty_disable_recycle_bin).isVisible = isOneItemSelected && selectedPaths.first() == RECYCLE_BIN
+
+ findItem(R.id.cab_create_shortcut).isVisible = isOreoPlus() && isOneItemSelected
+
+ checkHideBtnVisibility(this, selectedPaths)
+ checkPinBtnVisibility(this, selectedPaths)
+ }
+ }
+
+ override fun actionItemPressed(id: Int) {
+ if (selectedKeys.isEmpty()) {
+ return
+ }
+
+ when (id) {
+ R.id.cab_properties -> showProperties()
+ R.id.cab_rename -> renameDir()
+ R.id.cab_pin -> pinFolders(true)
+ R.id.cab_unpin -> pinFolders(false)
+ R.id.cab_empty_recycle_bin -> tryEmptyRecycleBin(true)
+ R.id.cab_empty_disable_recycle_bin -> emptyAndDisableRecycleBin()
+ R.id.cab_hide -> toggleFoldersVisibility(true)
+ R.id.cab_unhide -> toggleFoldersVisibility(false)
+ R.id.cab_exclude -> tryExcludeFolder()
+ R.id.cab_lock -> tryLockFolder()
+ R.id.cab_unlock -> unlockFolder()
+ R.id.cab_copy_to -> copyMoveTo(true)
+ R.id.cab_move_to -> moveFilesTo()
+ R.id.cab_select_all -> selectAll()
+ R.id.cab_create_shortcut -> tryCreateShortcut()
+ R.id.cab_delete -> askConfirmDelete()
+ R.id.cab_select_photo -> tryChangeAlbumCover(false)
+ R.id.cab_use_default -> tryChangeAlbumCover(true)
+ }
+ }
+
+ override fun getSelectableItemCount() = dirs.size
+
+ override fun getIsItemSelectable(position: Int) = true
+
+ override fun getItemSelectionKey(position: Int) = dirs.getOrNull(position)?.path?.hashCode()
+
+ override fun getItemKeyPosition(key: Int) = dirs.indexOfFirst { it.path.hashCode() == key }
+
+ override fun onActionModeCreated() {}
+
+ override fun onActionModeDestroyed() {}
+
+ override fun onViewRecycled(holder: ViewHolder) {
+ super.onViewRecycled(holder)
+ if (!activity.isDestroyed) {
+ Glide.with(activity).clear(holder.itemView.dir_thumbnail!!)
+ }
+ }
+
+ private fun checkHideBtnVisibility(menu: Menu, selectedPaths: ArrayList) {
+ menu.findItem(R.id.cab_hide).isVisible = selectedPaths.any { !it.doesThisOrParentHaveNoMedia(HashMap(), null) }
+ menu.findItem(R.id.cab_unhide).isVisible = selectedPaths.any { it.doesThisOrParentHaveNoMedia(HashMap(), null) }
+ }
+
+ private fun checkPinBtnVisibility(menu: Menu, selectedPaths: ArrayList) {
+ val pinnedFolders = config.pinnedFolders
+ menu.findItem(R.id.cab_pin).isVisible = selectedPaths.any { !pinnedFolders.contains(it) }
+ menu.findItem(R.id.cab_unpin).isVisible = selectedPaths.any { pinnedFolders.contains(it) }
+ }
+
+ private fun showProperties() {
+ if (selectedKeys.size <= 1) {
+ val path = getFirstSelectedItemPath() ?: return
+ if (path != FAVORITES && path != RECYCLE_BIN) {
+ activity.handleLockedFolderOpening(path) { success ->
+ if (success) {
+ PropertiesDialog(activity, path, config.shouldShowHidden)
+ }
+ }
+ }
+ } else {
+ PropertiesDialog(activity, getSelectedPaths().filter {
+ it != FAVORITES && it != RECYCLE_BIN && !config.isFolderProtected(it)
+ }.toMutableList(), config.shouldShowHidden)
+ }
+ }
+
+ private fun renameDir() {
+ if (selectedKeys.size == 1) {
+ val firstDir = getFirstSelectedItem() ?: return
+ val sourcePath = firstDir.path
+ val dir = File(sourcePath)
+ if (activity.isAStorageRootFolder(dir.absolutePath)) {
+ activity.toast(R.string.rename_folder_root)
+ return
+ }
+
+ activity.handleLockedFolderOpening(sourcePath) { success ->
+ if (success) {
+ RenameItemDialog(activity, dir.absolutePath) {
+ activity.runOnUiThread {
+ firstDir.apply {
+ path = it
+ name = it.getFilenameFromPath()
+ tmb = File(it, tmb.getFilenameFromPath()).absolutePath
+ }
+ updateDirs(dirs)
+ ensureBackgroundThread {
+ try {
+ activity.directoryDao.updateDirectoryAfterRename(firstDir.tmb, firstDir.name, firstDir.path, sourcePath)
+ listener?.refreshItems()
+ } catch (e: Exception) {
+ activity.showErrorToast(e)
+ }
+ }
+ }
+ }
+ }
+ }
+ } else {
+ val paths = getSelectedPaths().filter { !activity.isAStorageRootFolder(it) && !config.isFolderProtected(it) } as ArrayList
+ RenameItemsDialog(activity, paths) {
+ listener?.refreshItems()
+ }
+ }
+ }
+
+ private fun toggleFoldersVisibility(hide: Boolean) {
+ val selectedPaths = getSelectedPaths()
+ if (hide && selectedPaths.contains(RECYCLE_BIN)) {
+ config.showRecycleBinAtFolders = false
+ if (selectedPaths.size == 1) {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+
+ if (hide) {
+ if (config.wasHideFolderTooltipShown) {
+ hideFolders(selectedPaths)
+ } else {
+ config.wasHideFolderTooltipShown = true
+ ConfirmationDialog(activity, activity.getString(R.string.hide_folder_description)) {
+ hideFolders(selectedPaths)
+ }
+ }
+ } else {
+ selectedPaths.filter { it != FAVORITES && it != RECYCLE_BIN && (selectedPaths.size == 1 || !config.isFolderProtected(it)) }.forEach {
+ val path = it
+ activity.handleLockedFolderOpening(path) { success ->
+ if (success) {
+ if (path.containsNoMedia()) {
+ activity.removeNoMedia(path) {
+ if (config.shouldShowHidden) {
+ updateFolderNames()
+ } else {
+ activity.runOnUiThread {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private fun hideFolders(paths: ArrayList) {
+ for (path in paths) {
+ activity.handleLockedFolderOpening(path) { success ->
+ if (success) {
+ hideFolder(path)
+ }
+ }
+ }
+ }
+
+ private fun tryEmptyRecycleBin(askConfirmation: Boolean) {
+ if (askConfirmation) {
+ activity.showRecycleBinEmptyingDialog {
+ emptyRecycleBin()
+ }
+ } else {
+ emptyRecycleBin()
+ }
+ }
+
+ private fun emptyRecycleBin() {
+ activity.handleLockedFolderOpening(RECYCLE_BIN) { success ->
+ if (success) {
+ activity.emptyTheRecycleBin {
+ listener?.refreshItems()
+ }
+ }
+ }
+ }
+
+ private fun emptyAndDisableRecycleBin() {
+ activity.handleLockedFolderOpening(RECYCLE_BIN) { success ->
+ if (success) {
+ activity.showRecycleBinEmptyingDialog {
+ activity.emptyAndDisableTheRecycleBin {
+ listener?.refreshItems()
+ }
+ }
+ }
+ }
+ }
+
+ private fun updateFolderNames() {
+ val includedFolders = config.includedFolders
+ val hidden = activity.getString(R.string.hidden)
+ dirs.forEach {
+ it.name = activity.checkAppendingHidden(it.path, hidden, includedFolders, ArrayList())
+ }
+ listener?.updateDirectories(dirs.toMutableList() as ArrayList)
+ activity.runOnUiThread {
+ updateDirs(dirs)
+ }
+ }
+
+ private fun hideFolder(path: String) {
+ activity.addNoMedia(path) {
+ if (config.shouldShowHidden) {
+ updateFolderNames()
+ } else {
+ val affectedPositions = ArrayList()
+ val includedFolders = config.includedFolders
+ val newDirs = dirs.filterIndexed { index, directory ->
+ val removeDir = directory.path.doesThisOrParentHaveNoMedia(HashMap(), null) && !includedFolders.contains(directory.path)
+ if (removeDir) {
+ affectedPositions.add(index)
+ }
+ !removeDir
+ } as ArrayList
+
+ activity.runOnUiThread {
+ affectedPositions.sortedDescending().forEach {
+ notifyItemRemoved(it)
+ }
+
+ currentDirectoriesHash = newDirs.hashCode()
+ dirs = newDirs
+
+ finishActMode()
+ listener?.updateDirectories(newDirs)
+ }
+ }
+ }
+ }
+
+ private fun tryExcludeFolder() {
+ val selectedPaths = getSelectedPaths()
+ val paths = selectedPaths.filter { it != PATH && it != RECYCLE_BIN && it != FAVORITES }.toSet()
+ if (selectedPaths.contains(RECYCLE_BIN)) {
+ config.showRecycleBinAtFolders = false
+ if (selectedPaths.size == 1) {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+
+ if (paths.size == 1) {
+ ExcludeFolderDialog(activity, paths.toMutableList()) {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ } else if (paths.size > 1) {
+ config.addExcludedFolders(paths)
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+
+ private fun tryLockFolder() {
+ if (config.wasFolderLockingNoticeShown) {
+ lockFolder()
+ } else {
+ FolderLockingNoticeDialog(activity) {
+ lockFolder()
+ }
+ }
+ }
+
+ private fun lockFolder() {
+ SecurityDialog(activity, "", SHOW_ALL_TABS) { hash, type, success ->
+ if (success) {
+ getSelectedPaths().filter { !config.isFolderProtected(it) }.forEach {
+ config.addFolderProtection(it, hash, type)
+ lockedFolderPaths.add(it)
+ }
+
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+
+ private fun unlockFolder() {
+ val paths = getSelectedPaths()
+ val firstPath = paths.first()
+ val tabToShow = config.getFolderProtectionType(firstPath)
+ val hashToCheck = config.getFolderProtectionHash(firstPath)
+ SecurityDialog(activity, hashToCheck, tabToShow) { hash, type, success ->
+ if (success) {
+ paths.filter { config.isFolderProtected(it) && config.getFolderProtectionType(it) == tabToShow && config.getFolderProtectionHash(it) == hashToCheck }.forEach {
+ config.removeFolderProtection(it)
+ lockedFolderPaths.remove(it)
+ }
+
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+
+ private fun pinFolders(pin: Boolean) {
+ if (pin) {
+ config.addPinnedFolders(getSelectedPaths().toHashSet())
+ } else {
+ config.removePinnedFolders(getSelectedPaths().toHashSet())
+ }
+
+ currentDirectoriesHash = 0
+ pinnedFolders = config.pinnedFolders
+ listener?.recheckPinnedFolders()
+ }
+
+ private fun moveFilesTo() {
+ activity.handleDeletePasswordProtection {
+ copyMoveTo(false)
+ }
+ }
+
+ private fun copyMoveTo(isCopyOperation: Boolean) {
+ val paths = ArrayList()
+ val showHidden = config.shouldShowHidden
+ getSelectedPaths().forEach {
+ val filter = config.filterMedia
+ File(it).listFiles()?.filter {
+ !File(it.absolutePath).isDirectory &&
+ it.absolutePath.isMediaFile() && (showHidden || !it.name.startsWith('.')) &&
+ ((it.isImageFast() && filter and TYPE_IMAGES != 0) ||
+ (it.isVideoFast() && filter and TYPE_VIDEOS != 0) ||
+ (it.isGif() && filter and TYPE_GIFS != 0) ||
+ (it.isRawFast() && filter and TYPE_RAWS != 0) ||
+ (it.isSvg() && filter and TYPE_SVGS != 0))
+ }?.mapTo(paths) { it.absolutePath }
+ }
+
+ val fileDirItems = paths.map { FileDirItem(it, it.getFilenameFromPath()) } as ArrayList
+ activity.tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
+ val destinationPath = it
+ val newPaths = fileDirItems.map { "$destinationPath/${it.name}" }.toMutableList() as java.util.ArrayList
+ activity.rescanPaths(newPaths) {
+ activity.fixDateTaken(newPaths, false)
+ }
+
+ config.tempFolderPath = ""
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+
+ private fun tryCreateShortcut() {
+ activity.handleLockedFolderOpening(getFirstSelectedItemPath() ?: "") { success ->
+ if (success) {
+ createShortcut()
+ }
+ }
+ }
+
+ @SuppressLint("NewApi")
+ private fun createShortcut() {
+ val manager = activity.getSystemService(ShortcutManager::class.java)
+ if (manager.isRequestPinShortcutSupported) {
+ val dir = getFirstSelectedItem() ?: return
+ val path = dir.path
+ val drawable = resources.getDrawable(R.drawable.shortcut_image).mutate()
+ val coverThumbnail = config.parseAlbumCovers().firstOrNull { it.tmb == dir.path }?.tmb ?: dir.tmb
+ activity.getShortcutImage(coverThumbnail, drawable) {
+ val intent = Intent(activity, MediaActivity::class.java)
+ intent.action = Intent.ACTION_VIEW
+ intent.flags = intent.flags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
+ intent.putExtra(DIRECTORY, path)
+
+ val shortcut = ShortcutInfo.Builder(activity, path)
+ .setShortLabel(dir.name)
+ .setIcon(Icon.createWithBitmap(drawable.convertToBitmap()))
+ .setIntent(intent)
+ .build()
+
+ manager.requestPinShortcut(shortcut, null)
+ }
+ }
+ }
+
+ private fun askConfirmDelete() {
+ when {
+ config.isDeletePasswordProtectionOn -> activity.handleDeletePasswordProtection {
+ deleteFolders()
+ }
+ config.skipDeleteConfirmation -> deleteFolders()
+ else -> {
+ val itemsCnt = selectedKeys.size
+ val items = if (itemsCnt == 1) {
+ var folder = getSelectedPaths().first().getFilenameFromPath()
+ if (folder == RECYCLE_BIN) {
+ folder = activity.getString(R.string.recycle_bin)
+ }
+ "\"$folder\""
+ } else {
+ resources.getQuantityString(R.plurals.delete_items, itemsCnt, itemsCnt)
+ }
+
+ val fileDirItem = getFirstSelectedItem() ?: return
+ val baseString = if (!config.useRecycleBin || (isOneItemSelected() && fileDirItem.isRecycleBin()) || (isOneItemSelected() && fileDirItem.areFavorites())) {
+ R.string.deletion_confirmation
+ } else {
+ R.string.move_to_recycle_bin_confirmation
+ }
+
+ val question = String.format(resources.getString(baseString), items)
+ val warning = resources.getQuantityString(R.plurals.delete_warning, itemsCnt, itemsCnt)
+ ConfirmDeleteFolderDialog(activity, question, warning) {
+ deleteFolders()
+ }
+ }
+ }
+ }
+
+ private fun deleteFolders() {
+ if (selectedKeys.isEmpty()) {
+ return
+ }
+
+ var SAFPath = ""
+ val selectedDirs = getSelectedItems()
+ selectedDirs.forEach {
+ val path = it.path
+ if (activity.needsStupidWritePermissions(path) && config.treeUri.isEmpty()) {
+ SAFPath = path
+ }
+ }
+
+ activity.handleSAFDialog(SAFPath) {
+ if (!it) {
+ return@handleSAFDialog
+ }
+
+ var foldersToDelete = ArrayList(selectedKeys.size)
+ selectedDirs.forEach {
+ if (it.areFavorites() || it.isRecycleBin()) {
+ if (it.isRecycleBin()) {
+ tryEmptyRecycleBin(false)
+ } else {
+ ensureBackgroundThread {
+ activity.mediaDB.clearFavorites()
+ activity.favoritesDB.clearFavorites()
+ listener?.refreshItems()
+ }
+ }
+
+ if (selectedKeys.size == 1) {
+ finishActMode()
+ }
+ } else {
+ foldersToDelete.add(File(it.path))
+ }
+ }
+
+ if (foldersToDelete.size == 1) {
+ activity.handleLockedFolderOpening(foldersToDelete.first().absolutePath) { success ->
+ if (success) {
+ listener?.deleteFolders(foldersToDelete)
+ }
+ }
+ } else {
+ foldersToDelete = foldersToDelete.filter { !config.isFolderProtected(it.absolutePath) }.toMutableList() as ArrayList
+ listener?.deleteFolders(foldersToDelete)
+ }
+ }
+ }
+
+ private fun tryChangeAlbumCover(useDefault: Boolean) {
+ activity.handleLockedFolderOpening(getFirstSelectedItemPath() ?: "") { success ->
+ if (success) {
+ changeAlbumCover(useDefault)
+ }
+ }
+ }
+
+ private fun changeAlbumCover(useDefault: Boolean) {
+ if (selectedKeys.size != 1)
+ return
+
+ val path = getFirstSelectedItemPath() ?: return
+
+ if (useDefault) {
+ val albumCovers = getAlbumCoversWithout(path)
+ storeCovers(albumCovers)
+ } else {
+ pickMediumFrom(path, path)
+ }
+ }
+
+ private fun pickMediumFrom(targetFolder: String, path: String) {
+ PickMediumDialog(activity, path) {
+ if (File(it).isDirectory) {
+ pickMediumFrom(targetFolder, it)
+ } else {
+ val albumCovers = getAlbumCoversWithout(path)
+ val cover = AlbumCover(targetFolder, it)
+ albumCovers.add(cover)
+ storeCovers(albumCovers)
+ }
+ }
+ }
+
+ private fun getAlbumCoversWithout(path: String) = config.parseAlbumCovers().filterNot { it.path == path } as ArrayList
+
+ private fun storeCovers(albumCovers: ArrayList) {
+ config.albumCovers = Gson().toJson(albumCovers)
+ finishActMode()
+ listener?.refreshItems()
+ }
+
+ private fun getSelectedItems() = selectedKeys.mapNotNull { getItemWithKey(it) } as ArrayList
+
+ private fun getSelectedPaths() = getSelectedItems().map { it.path } as ArrayList
+
+ private fun getFirstSelectedItem() = getItemWithKey(selectedKeys.first())
+
+ private fun getFirstSelectedItemPath() = getFirstSelectedItem()?.path
+
+ private fun getItemWithKey(key: Int): Directory? = dirs.firstOrNull { it.path.hashCode() == key }
+
+ private fun fillLockedFolders() {
+ lockedFolderPaths.clear()
+ dirs.map { it.path }.filter { config.isFolderProtected(it) }.forEach {
+ lockedFolderPaths.add(it)
+ }
+ }
+
+ fun updateDirs(newDirs: ArrayList) {
+ val directories = newDirs.clone() as ArrayList
+ if (directories.hashCode() != currentDirectoriesHash) {
+ currentDirectoriesHash = directories.hashCode()
+ dirs = directories
+ fillLockedFolders()
+ notifyDataSetChanged()
+ finishActMode()
+ }
+ }
+
+ fun updateAnimateGifs(animateGifs: Boolean) {
+ this.animateGifs = animateGifs
+ notifyDataSetChanged()
+ }
+
+ fun updateCropThumbnails(cropThumbnails: Boolean) {
+ this.cropThumbnails = cropThumbnails
+ notifyDataSetChanged()
+ }
+
+ private fun setupView(view: View, directory: Directory) {
+ val isSelected = selectedKeys.contains(directory.path.hashCode())
+ view.apply {
+ dir_path?.text = "${directory.path.substringBeforeLast("/")}/"
+ val thumbnailType = when {
+ directory.tmb.isVideoFast() -> TYPE_VIDEOS
+ directory.tmb.isGif() -> TYPE_GIFS
+ directory.tmb.isRawFast() -> TYPE_RAWS
+ directory.tmb.isSvg() -> TYPE_SVGS
+ else -> TYPE_IMAGES
+ }
+
+ dir_check?.beVisibleIf(isSelected)
+ if (isSelected) {
+ dir_check.background?.applyColorFilter(primaryColor)
+ }
+
+ if (isListViewType) {
+ dir_holder.isSelected = isSelected
+ }
+
+ if (scrollHorizontally && !isListViewType && folderStyle == FOLDER_STYLE_ROUNDED_CORNERS) {
+ (dir_thumbnail.layoutParams as RelativeLayout.LayoutParams).addRule(RelativeLayout.ABOVE, dir_name.id)
+
+ val photoCntParams = (photo_cnt.layoutParams as RelativeLayout.LayoutParams)
+ val nameParams = (dir_name.layoutParams as RelativeLayout.LayoutParams)
+ nameParams.removeRule(RelativeLayout.BELOW)
+
+ if (config.showFolderMediaCount == FOLDER_MEDIA_CNT_LINE) {
+ nameParams.addRule(RelativeLayout.ABOVE, photo_cnt.id)
+ nameParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
+
+ photoCntParams.removeRule(RelativeLayout.BELOW)
+ photoCntParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
+ } else {
+ nameParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
+ }
+ }
+
+ if (lockedFolderPaths.contains(directory.path)) {
+ dir_lock.beVisible()
+ dir_lock.background = ColorDrawable(config.backgroundColor)
+ dir_lock.applyColorFilter(config.backgroundColor.getContrastColor())
+ } else {
+ dir_lock.beGone()
+ val roundedCorners = when {
+ isListViewType -> ROUNDED_CORNERS_SMALL
+ folderStyle == FOLDER_STYLE_SQUARE -> ROUNDED_CORNERS_NONE
+ else -> ROUNDED_CORNERS_BIG
+ }
+
+ activity.loadImage(thumbnailType, directory.tmb, dir_thumbnail, scrollHorizontally, animateGifs, cropThumbnails, roundedCorners, directory.getKey())
+ }
+
+ dir_pin.beVisibleIf(pinnedFolders.contains(directory.path))
+ dir_location.beVisibleIf(directory.location != LOCATION_INTERNAL)
+ if (dir_location.isVisible()) {
+ dir_location.setImageResource(if (directory.location == LOCATION_SD) R.drawable.ic_sd_card_vector else R.drawable.ic_usb_vector)
+ }
+
+ photo_cnt.text = directory.subfoldersMediaCount.toString()
+ photo_cnt.beVisibleIf(showMediaCount == FOLDER_MEDIA_CNT_LINE)
+
+ if (limitFolderTitle) {
+ dir_name.setSingleLine()
+ dir_name.ellipsize = TextUtils.TruncateAt.MIDDLE
+ }
+
+ var nameCount = directory.name
+ if (showMediaCount == FOLDER_MEDIA_CNT_BRACKETS) {
+ nameCount += " (${directory.subfoldersMediaCount})"
+ }
+
+ if (groupDirectSubfolders) {
+ if (directory.subfoldersCount > 1) {
+ nameCount += " [${directory.subfoldersCount}]"
+ }
+ }
+
+ dir_name.text = nameCount
+
+ if (isListViewType || folderStyle == FOLDER_STYLE_ROUNDED_CORNERS) {
+ photo_cnt.setTextColor(textColor)
+ dir_name.setTextColor(textColor)
+ dir_location.applyColorFilter(textColor)
+ }
+
+ if (isListViewType) {
+ dir_path.setTextColor(textColor)
+ dir_pin.applyColorFilter(textColor)
+ dir_location.applyColorFilter(textColor)
+ }
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/FiltersAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/FiltersAdapter.kt
new file mode 100644
index 000000000..b614787b8
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/FiltersAdapter.kt
@@ -0,0 +1,58 @@
+package com.simplemobiletools.gallery.pro.adapters
+
+import android.content.Context
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.recyclerview.widget.RecyclerView
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.models.FilterItem
+import kotlinx.android.synthetic.main.editor_filter_item.view.*
+import java.util.*
+
+class FiltersAdapter(val context: Context, val filterItems: ArrayList, val itemClick: (Int) -> Unit) : RecyclerView.Adapter() {
+
+ private var currentSelection = filterItems.first()
+ private var strokeBackground = context.resources.getDrawable(R.drawable.stroke_background)
+
+ override fun onBindViewHolder(holder: ViewHolder, position: Int) {
+ holder.bindView(filterItems[position])
+ }
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
+ val view = LayoutInflater.from(parent.context).inflate(R.layout.editor_filter_item, parent, false)
+ return ViewHolder(view)
+ }
+
+ override fun getItemCount() = filterItems.size
+
+ fun getCurrentFilter() = currentSelection
+
+ private fun setCurrentFilter(position: Int) {
+ val filterItem = filterItems.getOrNull(position) ?: return
+ if (currentSelection != filterItem) {
+ currentSelection = filterItem
+ notifyDataSetChanged()
+ itemClick.invoke(position)
+ }
+ }
+
+ inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ fun bindView(filterItem: FilterItem): View {
+ itemView.apply {
+ editor_filter_item_label.text = filterItem.filter.name
+ editor_filter_item_thumbnail.setImageBitmap(filterItem.bitmap)
+ editor_filter_item_thumbnail.background = if (getCurrentFilter() == filterItem) {
+ strokeBackground
+ } else {
+ null
+ }
+
+ setOnClickListener {
+ setCurrentFilter(adapterPosition)
+ }
+ }
+ return itemView
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/ManageFoldersAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/ManageFoldersAdapter.kt
new file mode 100644
index 000000000..670174413
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/ManageFoldersAdapter.kt
@@ -0,0 +1,89 @@
+package com.simplemobiletools.gallery.pro.adapters
+
+import android.view.Menu
+import android.view.View
+import android.view.ViewGroup
+import com.simplemobiletools.commons.activities.BaseSimpleActivity
+import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
+import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
+import com.simplemobiletools.commons.views.MyRecyclerView
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.extensions.config
+import kotlinx.android.synthetic.main.item_manage_folder.view.*
+import java.util.*
+
+class ManageFoldersAdapter(activity: BaseSimpleActivity, var folders: ArrayList, val isShowingExcludedFolders: Boolean, val listener: RefreshRecyclerViewListener?,
+ recyclerView: MyRecyclerView, itemClick: (Any) -> Unit) : MyRecyclerViewAdapter(activity, recyclerView, null, itemClick) {
+
+ private val config = activity.config
+
+ init {
+ setupDragListener(true)
+ }
+
+ override fun getActionMenuId() = R.menu.cab_remove_only
+
+ override fun prepareActionMode(menu: Menu) {}
+
+ override fun actionItemPressed(id: Int) {
+ when (id) {
+ R.id.cab_remove -> removeSelection()
+ }
+ }
+
+ override fun getSelectableItemCount() = folders.size
+
+ override fun getIsItemSelectable(position: Int) = true
+
+ override fun getItemSelectionKey(position: Int) = folders.getOrNull(position)?.hashCode()
+
+ override fun getItemKeyPosition(key: Int) = folders.indexOfFirst { it.hashCode() == key }
+
+ override fun onActionModeCreated() {}
+
+ override fun onActionModeDestroyed() {}
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.item_manage_folder, parent)
+
+ override fun onBindViewHolder(holder: ViewHolder, position: Int) {
+ val folder = folders[position]
+ holder.bindView(folder, true, true) { itemView, adapterPosition ->
+ setupView(itemView, folder)
+ }
+ bindViewHolder(holder)
+ }
+
+ override fun getItemCount() = folders.size
+
+ private fun getSelectedItems() = folders.filter { selectedKeys.contains(it.hashCode()) } as ArrayList
+
+ private fun setupView(view: View, folder: String) {
+ view.apply {
+ manage_folder_holder?.isSelected = selectedKeys.contains(folder.hashCode())
+ manage_folder_title.apply {
+ text = folder
+ setTextColor(config.textColor)
+ }
+ }
+ }
+
+ private fun removeSelection() {
+ val removeFolders = ArrayList(selectedKeys.size)
+ val positions = getSelectedItemPositions()
+
+ getSelectedItems().forEach {
+ removeFolders.add(it)
+ if (isShowingExcludedFolders) {
+ config.removeExcludedFolder(it)
+ } else {
+ config.removeIncludedFolder(it)
+ }
+ }
+
+ folders.removeAll(removeFolders)
+ removeSelectedItems(positions)
+ if (folders.isEmpty()) {
+ listener?.refreshItems()
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/ManageHiddenFoldersAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/ManageHiddenFoldersAdapter.kt
new file mode 100644
index 000000000..972d3e7a1
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/ManageHiddenFoldersAdapter.kt
@@ -0,0 +1,106 @@
+package com.simplemobiletools.gallery.pro.adapters
+
+import android.view.Menu
+import android.view.View
+import android.view.ViewGroup
+import com.simplemobiletools.commons.activities.BaseSimpleActivity
+import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
+import com.simplemobiletools.commons.extensions.isPathOnSD
+import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
+import com.simplemobiletools.commons.views.MyRecyclerView
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.extensions.config
+import com.simplemobiletools.gallery.pro.extensions.removeNoMedia
+import kotlinx.android.synthetic.main.item_manage_folder.view.*
+import java.util.*
+
+class ManageHiddenFoldersAdapter(activity: BaseSimpleActivity, var folders: ArrayList, val listener: RefreshRecyclerViewListener?,
+ recyclerView: MyRecyclerView, itemClick: (Any) -> Unit) : MyRecyclerViewAdapter(activity, recyclerView, null, itemClick) {
+
+ private val config = activity.config
+
+ init {
+ setupDragListener(true)
+ }
+
+ override fun getActionMenuId() = R.menu.cab_hidden_folders
+
+ override fun prepareActionMode(menu: Menu) {}
+
+ override fun actionItemPressed(id: Int) {
+ when (id) {
+ R.id.cab_unhide -> tryUnhideFolders()
+ }
+ }
+
+ override fun getSelectableItemCount() = folders.size
+
+ override fun getIsItemSelectable(position: Int) = true
+
+ override fun getItemSelectionKey(position: Int) = folders.getOrNull(position)?.hashCode()
+
+ override fun getItemKeyPosition(key: Int) = folders.indexOfFirst { it.hashCode() == key }
+
+ override fun onActionModeCreated() {}
+
+ override fun onActionModeDestroyed() {}
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.item_manage_folder, parent)
+
+ override fun onBindViewHolder(holder: ViewHolder, position: Int) {
+ val folder = folders[position]
+ holder.bindView(folder, true, true) { itemView, adapterPosition ->
+ setupView(itemView, folder)
+ }
+ bindViewHolder(holder)
+ }
+
+ override fun getItemCount() = folders.size
+
+ private fun getSelectedItems() = folders.filter { selectedKeys.contains(it.hashCode()) } as ArrayList
+
+ private fun setupView(view: View, folder: String) {
+ view.apply {
+ manage_folder_holder?.isSelected = selectedKeys.contains(folder.hashCode())
+ manage_folder_title.apply {
+ text = folder
+ setTextColor(config.textColor)
+ }
+ }
+ }
+
+ private fun tryUnhideFolders() {
+ val removeFolders = ArrayList(selectedKeys.size)
+
+ val sdCardPaths = ArrayList()
+ getSelectedItems().forEach {
+ if (activity.isPathOnSD(it)) {
+ sdCardPaths.add(it)
+ }
+ }
+
+ if (sdCardPaths.isNotEmpty()) {
+ activity.handleSAFDialog(sdCardPaths.first()) {
+ if (it) {
+ unhideFolders(removeFolders)
+ }
+ }
+ } else {
+ unhideFolders(removeFolders)
+ }
+ }
+
+ private fun unhideFolders(removeFolders: ArrayList) {
+ val position = getSelectedItemPositions()
+ getSelectedItems().forEach {
+ removeFolders.add(it)
+ activity.removeNoMedia(it)
+ }
+
+ folders.removeAll(removeFolders)
+ removeSelectedItems(position)
+ if (folders.isEmpty()) {
+ listener?.refreshItems()
+ }
+ }
+}
diff --git a/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/MediaAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/MediaAdapter.kt
new file mode 100644
index 000000000..9139e10f9
--- /dev/null
+++ b/app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/MediaAdapter.kt
@@ -0,0 +1,588 @@
+package com.simplemobiletools.gallery.pro.adapters
+
+import android.annotation.SuppressLint
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.Icon
+import android.os.Handler
+import android.os.Looper
+import android.view.Menu
+import android.view.View
+import android.view.ViewGroup
+import android.widget.Toast
+import com.bumptech.glide.Glide
+import com.simplemobiletools.commons.activities.BaseSimpleActivity
+import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
+import com.simplemobiletools.commons.dialogs.PropertiesDialog
+import com.simplemobiletools.commons.dialogs.RenameDialog
+import com.simplemobiletools.commons.dialogs.RenameItemDialog
+import com.simplemobiletools.commons.extensions.*
+import com.simplemobiletools.commons.helpers.*
+import com.simplemobiletools.commons.models.FileDirItem
+import com.simplemobiletools.commons.views.FastScroller
+import com.simplemobiletools.commons.views.MyRecyclerView
+import com.simplemobiletools.gallery.pro.R
+import com.simplemobiletools.gallery.pro.activities.ViewPagerActivity
+import com.simplemobiletools.gallery.pro.dialogs.DeleteWithRememberDialog
+import com.simplemobiletools.gallery.pro.extensions.*
+import com.simplemobiletools.gallery.pro.helpers.*
+import com.simplemobiletools.gallery.pro.interfaces.MediaOperationsListener
+import com.simplemobiletools.gallery.pro.models.Medium
+import com.simplemobiletools.gallery.pro.models.ThumbnailItem
+import com.simplemobiletools.gallery.pro.models.ThumbnailSection
+import kotlinx.android.synthetic.main.photo_video_item_grid.view.*
+import kotlinx.android.synthetic.main.thumbnail_section.view.*
+import java.util.*
+
+class MediaAdapter(activity: BaseSimpleActivity, var media: ArrayList, val listener: MediaOperationsListener?, val isAGetIntent: Boolean,
+ val allowMultiplePicks: Boolean, val path: String, recyclerView: MyRecyclerView, fastScroller: FastScroller? = null, itemClick: (Any) -> Unit) :
+ MyRecyclerViewAdapter(activity, recyclerView, fastScroller, itemClick) {
+
+ private val INSTANT_LOAD_DURATION = 2000L
+ private val IMAGE_LOAD_DELAY = 100L
+ private val ITEM_SECTION = 0
+ private val ITEM_MEDIUM = 1
+
+ private val config = activity.config
+ private val viewType = config.getFolderViewType(if (config.showAll) SHOW_ALL else path)
+ private val isListViewType = viewType == VIEW_TYPE_LIST
+ private var visibleItemPaths = ArrayList()
+ private var rotatedImagePaths = ArrayList()
+ private var loadImageInstantly = false
+ private var delayHandler = Handler(Looper.getMainLooper())
+ private var currentMediaHash = media.hashCode()
+ private val hasOTGConnected = activity.hasOTGConnected()
+
+ private var scrollHorizontally = config.scrollHorizontally
+ private var animateGifs = config.animateGifs
+ private var cropThumbnails = config.cropThumbnails
+ private var displayFilenames = config.displayFileNames
+ private var showFileTypes = config.showThumbnailFileTypes
+
+ init {
+ setupDragListener(true)
+ enableInstantLoad()
+ }
+
+ override fun getActionMenuId() = R.menu.cab_media
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
+ val layoutType = if (viewType == ITEM_SECTION) {
+ R.layout.thumbnail_section
+ } else {
+ if (isListViewType) {
+ R.layout.photo_video_item_list
+ } else {
+ R.layout.photo_video_item_grid
+ }
+ }
+ return createViewHolder(layoutType, parent)
+ }
+
+ override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) {
+ val tmbItem = media.getOrNull(position) ?: return
+ if (tmbItem is Medium) {
+ visibleItemPaths.add(tmbItem.path)
+ }
+
+ val allowLongPress = (!isAGetIntent || allowMultiplePicks) && tmbItem is Medium
+ holder.bindView(tmbItem, tmbItem is Medium, allowLongPress) { itemView, adapterPosition ->
+ if (tmbItem is Medium) {
+ setupThumbnail(itemView, tmbItem)
+ } else {
+ setupSection(itemView, tmbItem as ThumbnailSection)
+ }
+ }
+ bindViewHolder(holder)
+ }
+
+ override fun getItemCount() = media.size
+
+ override fun getItemViewType(position: Int): Int {
+ val tmbItem = media[position]
+ return if (tmbItem is ThumbnailSection) {
+ ITEM_SECTION
+ } else {
+ ITEM_MEDIUM
+ }
+ }
+
+ override fun prepareActionMode(menu: Menu) {
+ val selectedItems = getSelectedItems()
+ if (selectedItems.isEmpty()) {
+ return
+ }
+
+ val isOneItemSelected = isOneItemSelected()
+ val selectedPaths = selectedItems.map { it.path } as ArrayList
+ val isInRecycleBin = selectedItems.firstOrNull()?.getIsInRecycleBin() == true
+ menu.apply {
+ findItem(R.id.cab_rename).isVisible = !isInRecycleBin
+ findItem(R.id.cab_add_to_favorites).isVisible = !isInRecycleBin
+ findItem(R.id.cab_fix_date_taken).isVisible = !isInRecycleBin
+ findItem(R.id.cab_move_to).isVisible = !isInRecycleBin
+ findItem(R.id.cab_open_with).isVisible = isOneItemSelected
+ findItem(R.id.cab_confirm_selection).isVisible = isAGetIntent && allowMultiplePicks && selectedKeys.isNotEmpty()
+ findItem(R.id.cab_restore_recycle_bin_files).isVisible = selectedPaths.all { it.startsWith(activity.recycleBinPath) }
+ findItem(R.id.cab_create_shortcut).isVisible = isOreoPlus() && isOneItemSelected
+
+ checkHideBtnVisibility(this, selectedItems)
+ checkFavoriteBtnVisibility(this, selectedItems)
+ }
+ }
+
+ override fun actionItemPressed(id: Int) {
+ if (selectedKeys.isEmpty()) {
+ return
+ }
+
+ when (id) {
+ R.id.cab_confirm_selection -> confirmSelection()
+ R.id.cab_properties -> showProperties()
+ R.id.cab_rename -> renameFile()
+ R.id.cab_edit -> editFile()
+ R.id.cab_hide -> toggleFileVisibility(true)
+ R.id.cab_unhide -> toggleFileVisibility(false)
+ R.id.cab_add_to_favorites -> toggleFavorites(true)
+ R.id.cab_remove_from_favorites -> toggleFavorites(false)
+ R.id.cab_restore_recycle_bin_files -> restoreFiles()
+ R.id.cab_share -> shareMedia()
+ R.id.cab_rotate_right -> rotateSelection(90)
+ R.id.cab_rotate_left -> rotateSelection(270)
+ R.id.cab_rotate_one_eighty -> rotateSelection(180)
+ R.id.cab_copy_to -> copyMoveTo(true)
+ R.id.cab_move_to -> moveFilesTo()
+ R.id.cab_create_shortcut -> createShortcut()
+ R.id.cab_select_all -> selectAll()
+ R.id.cab_open_with -> openPath()
+ R.id.cab_fix_date_taken -> fixDateTaken()
+ R.id.cab_set_as -> setAs()
+ R.id.cab_delete -> checkDeleteConfirmation()
+ }
+ }
+
+ override fun getSelectableItemCount() = media.filter { it is Medium }.size
+
+ override fun getIsItemSelectable(position: Int) = !isASectionTitle(position)
+
+ override fun getItemSelectionKey(position: Int) = (media.getOrNull(position) as? Medium)?.path?.hashCode()
+
+ override fun getItemKeyPosition(key: Int) = media.indexOfFirst { (it as? Medium)?.path?.hashCode() == key }
+
+ override fun onActionModeCreated() {}
+
+ override fun onActionModeDestroyed() {}
+
+ override fun onViewRecycled(holder: ViewHolder) {
+ super.onViewRecycled(holder)
+ if (!activity.isDestroyed) {
+ val itemView = holder.itemView
+ visibleItemPaths.remove(itemView.medium_name?.tag)
+ val tmb = itemView.medium_thumbnail
+ if (tmb != null) {
+ Glide.with(activity).clear(tmb)
+ }
+ }
+ }
+
+ fun isASectionTitle(position: Int) = media.getOrNull(position) is ThumbnailSection
+
+ private fun checkHideBtnVisibility(menu: Menu, selectedItems: ArrayList) {
+ val isInRecycleBin = selectedItems.firstOrNull()?.getIsInRecycleBin() == true
+ menu.findItem(R.id.cab_hide).isVisible = !isInRecycleBin && selectedItems.any { !it.isHidden() }
+ menu.findItem(R.id.cab_unhide).isVisible = !isInRecycleBin && selectedItems.any { it.isHidden() }
+ }
+
+ private fun checkFavoriteBtnVisibility(menu: Menu, selectedItems: ArrayList) {
+ menu.findItem(R.id.cab_add_to_favorites).isVisible = selectedItems.none { it.getIsInRecycleBin() } && selectedItems.any { !it.isFavorite }
+ menu.findItem(R.id.cab_remove_from_favorites).isVisible = selectedItems.none { it.getIsInRecycleBin() } && selectedItems.any { it.isFavorite }
+ }
+
+ private fun confirmSelection() {
+ listener?.selectedPaths(getSelectedPaths())
+ }
+
+ private fun showProperties() {
+ if (selectedKeys.size <= 1) {
+ val path = getFirstSelectedItemPath() ?: return
+ PropertiesDialog(activity, path, config.shouldShowHidden)
+ } else {
+ val paths = getSelectedPaths()
+ PropertiesDialog(activity, paths, config.shouldShowHidden)
+ }
+ }
+
+ private fun renameFile() {
+ if (selectedKeys.size == 1) {
+ val oldPath = getFirstSelectedItemPath() ?: return
+ RenameItemDialog(activity, oldPath) {
+ ensureBackgroundThread {
+ activity.updateDBMediaPath(oldPath, it)
+
+ activity.runOnUiThread {
+ enableInstantLoad()
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+ } else {
+ RenameDialog(activity, getSelectedPaths(), true) {
+ enableInstantLoad()
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+
+ private fun editFile() {
+ val path = getFirstSelectedItemPath() ?: return
+ activity.openEditor(path)
+ }
+
+ private fun openPath() {
+ val path = getFirstSelectedItemPath() ?: return
+ activity.openPath(path, true)
+ }
+
+ private fun setAs() {
+ val path = getFirstSelectedItemPath() ?: return
+ activity.setAs(path)
+ }
+
+ private fun toggleFileVisibility(hide: Boolean) {
+ ensureBackgroundThread {
+ getSelectedItems().forEach {
+ activity.toggleFileVisibility(it.path, hide)
+ }
+ activity.runOnUiThread {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+
+ private fun toggleFavorites(add: Boolean) {
+ ensureBackgroundThread {
+ getSelectedItems().forEach {
+ it.isFavorite = add
+ activity.updateFavorite(it.path, add)
+ }
+ activity.runOnUiThread {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+
+ private fun restoreFiles() {
+ activity.restoreRecycleBinPaths(getSelectedPaths()) {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+
+ private fun shareMedia() {
+ if (selectedKeys.size == 1 && selectedKeys.first() != -1) {
+ activity.shareMediumPath(getSelectedItems().first().path)
+ } else if (selectedKeys.size > 1) {
+ activity.shareMediaPaths(getSelectedPaths())
+ }
+ }
+
+ private fun rotateSelection(degrees: Int) {
+ activity.toast(R.string.saving)
+ ensureBackgroundThread {
+ val paths = getSelectedPaths().filter { it.isImageFast() }
+ var fileCnt = paths.size
+ rotatedImagePaths.clear()
+ paths.forEach {
+ rotatedImagePaths.add(it)
+ activity.saveRotatedImageToFile(it, it, degrees, true) {
+ fileCnt--
+ if (fileCnt == 0) {
+ activity.runOnUiThread {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private fun moveFilesTo() {
+ activity.handleDeletePasswordProtection {
+ copyMoveTo(false)
+ }
+ }
+
+ private fun copyMoveTo(isCopyOperation: Boolean) {
+ val paths = getSelectedPaths()
+
+ val recycleBinPath = activity.recycleBinPath
+ val fileDirItems = paths.asSequence().filter { isCopyOperation || !it.startsWith(recycleBinPath) }.map {
+ FileDirItem(it, it.getFilenameFromPath())
+ }.toMutableList() as ArrayList
+
+ if (!isCopyOperation && paths.any { it.startsWith(recycleBinPath) }) {
+ activity.toast(R.string.moving_recycle_bin_items_disabled, Toast.LENGTH_LONG)
+ }
+
+ if (fileDirItems.isEmpty()) {
+ return
+ }
+
+ activity.tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
+ val destinationPath = it
+ config.tempFolderPath = ""
+ activity.applicationContext.rescanFolderMedia(destinationPath)
+ activity.applicationContext.rescanFolderMedia(fileDirItems.first().getParentPath())
+
+ val newPaths = fileDirItems.map { "$destinationPath/${it.name}" }.toMutableList() as ArrayList
+ activity.rescanPaths(newPaths) {
+ activity.fixDateTaken(newPaths, false)
+ }
+ if (!isCopyOperation) {
+ listener?.refreshItems()
+ activity.updateFavoritePaths(fileDirItems, destinationPath)
+ }
+ }
+ }
+
+ @SuppressLint("NewApi")
+ private fun createShortcut() {
+ val manager = activity.getSystemService(ShortcutManager::class.java)
+ if (manager.isRequestPinShortcutSupported) {
+ val path = getSelectedPaths().first()
+ val drawable = resources.getDrawable(R.drawable.shortcut_image).mutate()
+ activity.getShortcutImage(path, drawable) {
+ val intent = Intent(activity, ViewPagerActivity::class.java).apply {
+ putExtra(PATH, path)
+ putExtra(SHOW_ALL, config.showAll)
+ putExtra(SHOW_FAVORITES, path == FAVORITES)
+ putExtra(SHOW_RECYCLE_BIN, path == RECYCLE_BIN)
+ action = Intent.ACTION_VIEW
+ flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
+ }
+
+ val shortcut = ShortcutInfo.Builder(activity, path)
+ .setShortLabel(path.getFilenameFromPath())
+ .setIcon(Icon.createWithBitmap(drawable.convertToBitmap()))
+ .setIntent(intent)
+ .build()
+
+ manager.requestPinShortcut(shortcut, null)
+ }
+ }
+ }
+
+ private fun fixDateTaken() {
+ ensureBackgroundThread {
+ activity.fixDateTaken(getSelectedPaths(), true) {
+ listener?.refreshItems()
+ finishActMode()
+ }
+ }
+ }
+
+ private fun checkDeleteConfirmation() {
+ if (config.isDeletePasswordProtectionOn) {
+ activity.handleDeletePasswordProtection {
+ deleteFiles()
+ }
+ } else if (config.tempSkipDeleteConfirmation || config.skipDeleteConfirmation) {
+ deleteFiles()
+ } else {
+ askConfirmDelete()
+ }
+ }
+
+ private fun askConfirmDelete() {
+ val itemsCnt = selectedKeys.size
+ val firstPath = getSelectedPaths().first()
+ val items = if (itemsCnt == 1) {
+ "\"${firstPath.getFilenameFromPath()}\""
+ } else {
+ resources.getQuantityString(R.plurals.delete_items, itemsCnt, itemsCnt)
+ }
+
+ val isRecycleBin = firstPath.startsWith(activity.recycleBinPath)
+ val baseString = if (config.useRecycleBin && !isRecycleBin) R.string.move_to_recycle_bin_confirmation else R.string.deletion_confirmation
+ val question = String.format(resources.getString(baseString), items)
+ DeleteWithRememberDialog(activity, question) {
+ config.tempSkipDeleteConfirmation = it
+ deleteFiles()
+ }
+ }
+
+ private fun deleteFiles() {
+ if (selectedKeys.isEmpty()) {
+ return
+ }
+
+ val SAFPath = getSelectedPaths().firstOrNull { activity.needsStupidWritePermissions(it) } ?: getFirstSelectedItemPath() ?: return
+ activity.handleSAFDialog(SAFPath) {
+ if (!it) {
+ return@handleSAFDialog
+ }
+
+ val fileDirItems = ArrayList(selectedKeys.size)
+ val removeMedia = ArrayList(selectedKeys.size)
+ val positions = getSelectedItemPositions()
+
+ getSelectedItems().forEach {
+ fileDirItems.add(FileDirItem(it.path, it.name))
+ removeMedia.add(it)
+ }
+
+ media.removeAll(removeMedia)
+ listener?.tryDeleteFiles(fileDirItems)
+ listener?.updateMediaGridDecoration(media)
+ removeSelectedItems(positions)
+ currentMediaHash = media.hashCode()
+ }
+ }
+
+ private fun getSelectedItems() = selectedKeys.mapNotNull { getItemWithKey(it) } as ArrayList
+
+ private fun getSelectedPaths() = getSelectedItems().map { it.path } as ArrayList