Merge pull request #3 from SimpleMobileTools/master

traer cambios
This commit is contained in:
Xose M 2020-06-12 15:27:57 +02:00 committed by GitHub
commit cfcbd9bb20
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
474 changed files with 33037 additions and 9816 deletions

23
.editorconfig Normal file
View file

@ -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

3
.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1,3 @@
github: [tibbi]
patreon: tiborkaputa
custom: ["https://www.paypal.me/SimpleMobileTools", "https://www.simplemobiletools.com/donate"]

6
.gitignore vendored
View file

@ -1,10 +1,10 @@
*.iml
*.aab
.gradle
/local.properties
/gradle.properties
/.idea/
.DS_Store
/build
/captures
release.keystore
signing.properties
keystore.jks
keystore.properties

View file

@ -1,6 +1,885 @@
Changelog
==========
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)*
----------------------------

811
LICENSE
View file

@ -1,201 +1,674 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
1. Definitions.
Preamble
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
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.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
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.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
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.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
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.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
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.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
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.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
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.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
The precise terms and conditions for copying, distribution and
modification follow.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
TERMS AND CONDITIONS
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
0. Definitions.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
"This License" refers to version 3 of the GNU General Public License.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
"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.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
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.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
A "covered work" means either the unmodified Program or a work based
on the Program.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
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.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
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.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
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.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
1. Source Code.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
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.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
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.
END OF TERMS AND CONDITIONS
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.
APPENDIX: How to apply the Apache License to your work.
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.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
Copyright 2017 SimpleMobileTools
The Corresponding Source for a work in source code form is that
same work.
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
2. Basic Permissions.
http://www.apache.org/licenses/LICENSE-2.0
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.
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.
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

128
README.md
View file

@ -1,38 +1,114 @@
# Simple Gallery
<img alt="Logo" src="app/src/main/res/mipmap-xxxhdpi/ic_launcher.png" width="80" />
<img alt="Logo" src="fastlane/metadata/android/en-US/images/icon.png" width="120" />
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
<a href='https://play.google.com/store/apps/details?id=com.simplemobiletools.gallery'><img src='http://simplemobiletools.github.io/assets/public/google-play.png' alt='Get it on Google Play' height='45' /></a>
<a href='https://f-droid.org/packages/com.simplemobiletools.gallery'><img src='http://simplemobiletools.github.io/assets/public/f-droid.png' alt='Get it on F-Droid' height='45' /></a>
• No unnecessary permissions required
• Quickly search images, videos & other files
• 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 youre 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, were also available in over 30 languages!
RECOVER DELETED PHOTOS & VIDEOS
Accidentally deleted a precious photo or video? Dont 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 devices 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 cant 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 :)
<a href='https://play.google.com/store/apps/details?id=com.simplemobiletools.gallery.pro'><img src='https://simplemobiletools.com/assets/images/google-play.png' alt='Get it on Google Play' height='45' /></a>
<a href='https://f-droid.org/packages/com.simplemobiletools.gallery.pro'><img src='https://simplemobiletools.com/assets/images/f-droid.png' alt='Get it on F-Droid' height='45' /></a>
<div style="display:flex;">
<img alt="App image" src="fastlane/metadata/android/en-US/images/phoneScreenshots/app.jpg" width="30%">
<img alt="App image" src="fastlane/metadata/android/en-US/images/phoneScreenshots/app_1.jpg" width="30%">
<img alt="App image" src="fastlane/metadata/android/en-US/images/phoneScreenshots/app_2.jpg" width="30%">
<img alt="App image" src="fastlane/metadata/android/en-US/images/phoneScreenshots/app_5.jpg" width="30%">
<img alt="App image" src="fastlane/metadata/android/en-US/images/phoneScreenshots/app_3.jpg" width="30%">
</div>
License
-------
Copyright 2016-present 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.

View file

@ -3,83 +3,127 @@ 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 27
buildToolsVersion "27.0.3"
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.simplemobiletools.gallery"
minSdkVersion 16
targetSdkVersion 27
versionCode 179
versionName "4.1.1"
applicationId "com.simplemobiletools.gallery.pro"
minSdkVersion 21
targetSdkVersion 29
versionCode 312
versionName "6.15.0"
multiDexEnabled true
setProperty("archivesBaseName", "gallery")
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 {
applicationIdSuffix ".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
}
}
ext {
leakCanaryVersion = '1.5.4'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
exclude 'META-INF/library_release.kotlin_module'
}
}
dependencies {
implementation 'com.simplemobiletools:commons:4.1.4'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.simplemobiletools:commons:5.29.1'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'it.sephiroth.android.exif:library:1.0.1'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.12'
implementation 'com.github.chrisbanes:PhotoView:2.1.3'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.19'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta6'
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'
kapt "android.arch.persistence.room:compiler:1.1.0"
implementation "android.arch.persistence.room:runtime:1.1.0"
annotationProcessor "android.arch.persistence.room:compiler:1.1.0"
kapt 'com.github.bumptech.glide:compiler:4.10.0'
//implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.9.0'
implementation 'com.github.tibbi:subsampling-scale-image-view:v3.10.0-fork'
debugImplementation "com.squareup.leakcanary:leakcanary-android:$leakCanaryVersion"
releaseImplementation "com.squareup.leakcanary:leakcanary-android-no-op:$leakCanaryVersion"
kapt 'androidx.room:room-compiler:2.2.5'
implementation 'androidx.room:room-runtime:2.2.5'
annotationProcessor 'androidx.room:room-compiler:2.2.5'
}
Properties props = new Properties()
def propFile = new File('signing.properties')
if (propFile.canRead()) {
props.load(new FileInputStream(propFile))
// Apply the PESDKPlugin
if (is_proprietary) {
apply plugin: 'ly.img.android.sdk'
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
imglyConfig {
pesdk {
enabled true
licencePath 'pesdk_license'
}
modules {
include 'ui:core'
include 'ui:text'
include 'ui:focus'
include 'ui:brush'
include 'ui:filter'
include 'ui:transform'
include 'ui:adjustment'
include 'backend:serializer'
include 'assets:font-basic'
include 'assets:filter-basic'
}
}
} else {
println 'signing.properties not found'
android.buildTypes.release.signingConfig = null
}

View file

@ -1,2 +1,20 @@
-keep class com.simplemobiletools.** { *; }
-dontwarn android.graphics.Canvas
-dontwarn com.simplemobiletools.**
-dontwarn org.apache.**
# 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 <methods>;
}
-keep class androidx.renderscript.** { *; }

View file

@ -1,11 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.simplemobiletools.gallery"
xmlns:tools="http://schemas.android.com/tools"
package="com.simplemobiletools.gallery.pro"
android:installLocation="auto">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"
tools:node="remove"/>
<uses-permission
android:name="android.permission.CAMERA"
tools:node="remove"/>
<uses-sdk
tools:overrideLibrary="com.google.vr.widgets.common, com.google.vr.sdk.widgets.pano"/>
<uses-feature
android:name="android.hardware.faketouch"
android:required="false"/>
<application
android:name=".App"
@ -13,21 +28,27 @@
android:icon="@mipmap/ic_launcher"
android:label="@string/app_launcher_name"
android:roundIcon="@mipmap/ic_launcher"
android:requestLegacyExternalStorage="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme"
tools:replace="android:label">
<activity
android:name=".activities.SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
android:theme="@style/SplashTheme"/>
<activity
android:name=".activities.MainActivity"
android:resizeableActivity="true">
<meta-data
android:name="android.app.default_searchable"
android:resource="@xml/searchable"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PICK"/>
<category android:name="android.intent.category.DEFAULT"/>
@ -65,6 +86,21 @@
</activity>
<activity
android:name=".activities.SearchActivity"
android:label="@string/search"
android:parentActivityName=".activities.MainActivity"
android:resizeableActivity="true">
<meta-data
android:name="android.app.default_searchable"
android:resource="@xml/searchable"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
</activity>
<activity
android:name=".activities.ViewPagerActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
@ -110,6 +146,21 @@
android:name=".activities.PhotoVideoActivity"
android:configChanges="orientation|keyboardHidden|screenSize"/>
<activity
android:name=".activities.VideoPlayerActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:parentActivityName=".activities.MediaActivity"/>
<activity
android:name=".activities.PanoramaPhotoActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/FullScreenTheme"/>
<activity
android:name=".activities.PanoramaVideoActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/FullScreenTheme"/>
<activity
android:name=".activities.IncludedFoldersActivity"
android:label="@string/include_folders"
@ -154,7 +205,10 @@
<activity
android:name=".activities.EditActivity"
android:label="@string/editor">
<intent-filter>
<intent-filter
android:name="foss-editor">
<action android:name="android.intent.action.EDIT"/>
<category android:name="android.intent.category.DEFAULT"/>
@ -193,8 +247,17 @@
</intent-filter>
</activity>
<activity
android:name=".activities.WidgetConfigureActivity"
android:screenOrientation="portrait"
android:theme="@style/MyWidgetConfigTheme">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
@ -211,18 +274,31 @@
</intent-filter>
</receiver>
<!-- Do not append ".Orange" to the default alias "name", it would remove the old homescreen launcher of users at upgrade -->
<activity-alias
android:name=".activities.SplashActivity"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher"
android:targetActivity=".activities.SplashActivity">
<receiver
android:name=".helpers.MyWidgetProvider"
android:icon="@drawable/img_widget_preview">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
</activity-alias>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_info"/>
</receiver>
<receiver android:name=".receivers.BootCompletedReceiver"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<service
android:name=".jobs.NewPhotoFetcher"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
<activity-alias
android:name=".activities.SplashActivity.Red"
@ -406,6 +482,18 @@
</intent-filter>
</activity-alias>
<activity-alias
android:name=".activities.SplashActivity.Orange"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher"
android:targetActivity=".activities.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity-alias>
<activity-alias
android:name=".activities.SplashActivity.Deep_orange"
android:enabled="false"

View file

@ -1,21 +0,0 @@
package com.simplemobiletools.gallery
import android.support.multidex.MultiDexApplication
import com.github.ajalt.reprint.core.Reprint
import com.simplemobiletools.commons.extensions.checkUseEnglish
import com.squareup.leakcanary.LeakCanary
class App : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
if (LeakCanary.isInAnalyzerProcess(this)) {
return
}
LeakCanary.install(this)
}
checkUseEnglish()
Reprint.initialize(this)
}
}

View file

@ -1,270 +0,0 @@
package com.simplemobiletools.gallery.activities
import android.app.Activity
import android.content.Intent
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.view.Menu
import android.view.MenuItem
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.OTG_PATH
import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_STORAGE
import com.simplemobiletools.commons.helpers.REAL_FILE_PATH
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.dialogs.ResizeDialog
import com.simplemobiletools.gallery.dialogs.SaveAsDialog
import com.simplemobiletools.gallery.extensions.openEditor
import com.theartofdev.edmodo.cropper.CropImageView
import kotlinx.android.synthetic.main.view_crop_image.*
import java.io.*
class EditActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener {
private val ASPECT_X = "aspectX"
private val ASPECT_Y = "aspectY"
private val CROP = "crop"
private lateinit var uri: Uri
private lateinit var saveUri: Uri
private var resizeWidth = 0
private var resizeHeight = 0
private var isCropIntent = false
private var isEditingWithThirdParty = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.view_crop_image)
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
initEditActivity()
} else {
toast(R.string.no_storage_permissions)
finish()
}
}
}
private fun initEditActivity() {
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
}
if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
val realPath = intent.extras.getString(REAL_FILE_PATH)
uri = when {
realPath.startsWith(OTG_PATH) -> 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"
crop_image_view.apply {
setOnCropImageCompleteListener(this@EditActivity)
setImageUriAsync(uri)
if (isCropIntent && shouldCropSquare())
setFixedAspectRatio(true)
}
}
override fun onResume() {
super.onResume()
isEditingWithThirdParty = false
}
override fun onStop() {
super.onStop()
if (isEditingWithThirdParty) {
finish()
}
}
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)
R.id.edit -> editWith()
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) {
if (saveUri.scheme == "file") {
saveBitmapToFile(result.bitmap, saveUri.path)
} else {
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(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(result.bitmap, it)
}
} else if (saveUri.scheme == "content") {
var newPath = applicationContext.getRealPathFromURI(saveUri) ?: ""
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
}
SaveAsDialog(this, newPath, shouldAppendFilename) {
saveBitmapToFile(result.bitmap, it)
}
} else {
toast(R.string.unknown_file_location)
}
} else {
toast("${getString(R.string.image_editing_failed)}: ${result.error.message}")
}
}
private fun saveBitmapToFile(bitmap: Bitmap, path: String) {
try {
Thread {
val file = File(path)
val fileDirItem = FileDirItem(path, path.getFilenameFromPath())
getFileOutputStream(fileDirItem, true) {
if (it != null) {
saveBitmap(file, bitmap, it)
} else {
toast(R.string.image_editing_failed)
}
}
}.start()
} catch (e: Exception) {
showErrorToast(e)
} catch (e: OutOfMemoryError) {
toast(R.string.out_of_memory_error)
}
}
private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream) {
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)
}
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 editWith() {
openEditor(uri.toString())
isEditingWithThirdParty = true
}
private fun scanFinalPath(path: String) {
scanPathRecursively(path) {
setResult(Activity.RESULT_OK, intent)
toast(R.string.file_saved)
finish()
}
}
}

View file

@ -1,881 +0,0 @@
package com.simplemobiletools.gallery.activities
import android.app.Activity
import android.content.ClipData
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.support.v7.widget.GridLayoutManager
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.Toast
import com.simplemobiletools.commons.dialogs.CreateNewFolderDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.models.Release
import com.simplemobiletools.commons.views.MyGridLayoutManager
import com.simplemobiletools.commons.views.MyRecyclerView
import com.simplemobiletools.gallery.BuildConfig
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.adapters.DirectoryAdapter
import com.simplemobiletools.gallery.databases.GalleryDatabase
import com.simplemobiletools.gallery.dialogs.ChangeSortingDialog
import com.simplemobiletools.gallery.dialogs.FilterMediaDialog
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.*
import com.simplemobiletools.gallery.interfaces.DirectoryDao
import com.simplemobiletools.gallery.models.AlbumCover
import com.simplemobiletools.gallery.models.Directory
import com.simplemobiletools.gallery.models.Medium
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
class MainActivity : SimpleActivity(), DirectoryAdapter.DirOperationsListener {
private val PICK_MEDIA = 2
private val PICK_WALLPAPER = 3
private val LAST_MEDIA_CHECK_PERIOD = 3000L
private val NEW_APP_PACKAGE = "com.simplemobiletools.clock"
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 mLatestMediaId = 0L
private var mLatestMediaDateId = 0L
private var mLastMediaHandler = Handler()
private var mTempShowHiddenHandler = Handler()
private var mZoomListener: MyRecyclerView.MyZoomListener? = null
private var mStoredAnimateGifs = true
private var mStoredCropThumbnails = true
private var mStoredScrollHorizontally = true
private var mStoredShowMediaCount = true
private var mStoredShowInfoBubble = true
private var mStoredTextColor = 0
private var mStoredPrimaryColor = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
appLaunched(BuildConfig.APPLICATION_ID)
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
removeTempFolder()
directories_refresh_layout.setOnRefreshListener { getDirectories() }
storeStateVariables()
checkWhatsNewDialog()
directories_empty_text.setOnClickListener {
showFilterMediaDialog()
}
mIsPasswordProtectionPending = config.appPasswordProtectionOn
setupLatestMediaId()
// notify some users about the Clock app
/*if (System.currentTimeMillis() < 1523750400000 && !config.wasNewAppShown && config.appRunCount > 100 && config.appRunCount % 50 != 0 && !isPackageInstalled(NEW_APP_PACKAGE)) {
config.wasNewAppShown = true
NewAppDialog(this, NEW_APP_PACKAGE, "Simple Clock")
}*/
if (!config.wasOTGHandled && hasPermission(PERMISSION_WRITE_STORAGE)) {
checkOTGInclusion()
}
}
override fun onStart() {
super.onStart()
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
}
override fun onResume() {
super.onResume()
config.isThirdPartyIntent = false
if (mStoredAnimateGifs != config.animateGifs) {
getRecyclerAdapter()?.updateAnimateGifs(config.animateGifs)
}
if (mStoredCropThumbnails != config.cropThumbnails) {
getRecyclerAdapter()?.updateCropThumbnails(config.cropThumbnails)
}
if (mStoredShowMediaCount != config.showMediaCount) {
getRecyclerAdapter()?.updateShowMediaCount(config.showMediaCount)
}
if (mStoredScrollHorizontally != config.scrollHorizontally) {
getRecyclerAdapter()?.updateScrollHorizontally(config.viewTypeFolders != VIEW_TYPE_LIST && config.scrollHorizontally)
setupScrollDirection()
}
if (mStoredTextColor != config.textColor) {
getRecyclerAdapter()?.updateTextColor(config.textColor)
}
if (mStoredPrimaryColor != config.primaryColor) {
getRecyclerAdapter()?.updatePrimaryColor(config.primaryColor)
directories_vertical_fastscroller.updatePrimaryColor()
directories_horizontal_fastscroller.updatePrimaryColor()
}
directories_horizontal_fastscroller.updateBubbleColors()
directories_vertical_fastscroller.updateBubbleColors()
directories_horizontal_fastscroller.allowBubbleDisplay = config.showInfoBubble
directories_vertical_fastscroller.allowBubbleDisplay = config.showInfoBubble
directories_refresh_layout.isEnabled = config.enablePullToRefresh
invalidateOptionsMenu()
directories_empty_text_label.setTextColor(config.textColor)
directories_empty_text.setTextColor(getAdjustedPrimaryColor())
if (mIsPasswordProtectionPending) {
handleAppPasswordProtection {
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) {
mTempShowHiddenHandler.postDelayed({
config.temporarilyShowHidden = false
}, SHOW_TEMP_HIDDEN_DURATION)
} else {
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
}
}
override fun onDestroy() {
super.onDestroy()
config.temporarilyShowHidden = false
config.tempSkipDeleteConfirmation = false
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
removeTempFolder()
if (!isChangingConfigurations) {
GalleryDatabase.destroyInstance()
}
}
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.viewTypeFolders == VIEW_TYPE_GRID && config.dirColumnCnt < MAX_COLUMN_COUNT
menu.findItem(R.id.reduce_column_count).isVisible = config.viewTypeFolders == VIEW_TYPE_GRID && config.dirColumnCnt > 1
}
menu.findItem(R.id.temporarily_show_hidden).isVisible = !config.shouldShowHidden
menu.findItem(R.id.stop_showing_hidden).isVisible = config.temporarilyShowHidden
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.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 getRecyclerAdapter() = directories_grid.adapter as? DirectoryAdapter
private fun storeStateVariables() {
config.apply {
mStoredAnimateGifs = animateGifs
mStoredCropThumbnails = cropThumbnails
mStoredScrollHorizontally = scrollHorizontally
mStoredShowMediaCount = showMediaCount
mStoredShowInfoBubble = showInfoBubble
mStoredTextColor = textColor
mStoredPrimaryColor = primaryColor
}
}
private fun removeTempFolder() {
if (config.tempFolderPath.isNotEmpty()) {
val newFolder = File(config.tempFolderPath)
if (newFolder.exists() && newFolder.isDirectory) {
if (newFolder.list()?.isEmpty() == true) {
toast(String.format(getString(R.string.deleting_folder), config.tempFolderPath), Toast.LENGTH_LONG)
tryDeleteFileDirItem(newFolder.toFileDirItem(applicationContext), true)
}
}
config.tempFolderPath = ""
}
}
private fun checkOTGInclusion() {
Thread {
if (hasOTGConnected()) {
runOnUiThread {
handleOTGPermission {
config.addIncludedFolder(OTG_PATH)
}
}
config.wasOTGHandled = true
}
}.start()
}
private fun tryLoadGallery() {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
if (config.showAll) {
showAllMedia()
} else {
getDirectories()
}
setupLayoutManager()
} else {
toast(R.string.no_storage_permissions)
finish()
}
}
}
private fun getDirectories() {
if (mIsGettingDirs) {
return
}
mIsGettingDirs = true
val getImagesOnly = mIsPickImageIntent || mIsGetImageContentIntent
val getVideosOnly = mIsPickVideoIntent || mIsGetVideoContentIntent
getCachedDirectories(getVideosOnly, getImagesOnly) {
gotDirectories(addTempFolderIfNeeded(it))
}
}
private fun showSortingDialog() {
ChangeSortingDialog(this, true, false) {
if (config.directorySorting and SORT_BY_DATE_MODIFIED > 0 || config.directorySorting and SORT_BY_DATE_TAKEN > 0) {
getDirectories()
} else {
gotDirectories(getCurrentlyDisplayedDirs())
}
}
}
private fun showFilterMediaDialog() {
FilterMediaDialog(this) {
mLoadedInitialPhotos = false
directories_refresh_layout.isRefreshing = true
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() {
val items = arrayListOf(
RadioItem(VIEW_TYPE_GRID, getString(R.string.grid)),
RadioItem(VIEW_TYPE_LIST, getString(R.string.list)))
RadioGroupDialog(this, items, config.viewTypeFolders) {
config.viewTypeFolders = it as Int
invalidateOptionsMenu()
setupLayoutManager()
val dirs = getCurrentlyDisplayedDirs()
directories_grid.adapter = null
setupAdapter(dirs)
}
}
private fun tryToggleTemporarilyShowHidden() {
if (config.temporarilyShowHidden) {
toggleTemporarilyShowHidden(false)
} else {
handleHiddenFolderPasswordProtection {
toggleTemporarilyShowHidden(true)
}
}
}
private fun toggleTemporarilyShowHidden(show: Boolean) {
mLoadedInitialPhotos = false
config.temporarilyShowHidden = show
getDirectories()
invalidateOptionsMenu()
}
override fun deleteFolders(folders: ArrayList<File>) {
val fileDirItems = folders.map { FileDirItem(it.absolutePath, it.name, true) } as ArrayList<FileDirItem>
deleteFolders(fileDirItems) {
runOnUiThread {
refreshItems()
}
Thread {
val directoryDao = galleryDB.DirectoryDao()
folders.filter { !it.exists() }.forEach {
directoryDao.deleteDirPath(it.absolutePath)
}
}.start()
}
}
private fun setupLayoutManager() {
if (config.viewTypeFolders == VIEW_TYPE_GRID) {
setupGridLayoutManager()
} else {
setupListLayoutManager()
}
}
private fun setupGridLayoutManager() {
val layoutManager = directories_grid.layoutManager as MyGridLayoutManager
if (config.scrollHorizontally) {
layoutManager.orientation = GridLayoutManager.HORIZONTAL
directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
} else {
layoutManager.orientation = GridLayoutManager.VERTICAL
directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
layoutManager.spanCount = config.dirColumnCnt
}
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 setupListLayoutManager() {
val layoutManager = directories_grid.layoutManager as MyGridLayoutManager
layoutManager.spanCount = 1
layoutManager.orientation = GridLayoutManager.VERTICAL
directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
mZoomListener = null
}
private fun createNewFolder() {
FilePickerDialog(this, internalStoragePath, false, config.shouldShowHidden) {
CreateNewFolderDialog(this, it) {
config.tempFolderPath = it
gotDirectories(addTempFolderIfNeeded(getCurrentlyDisplayedDirs()))
}
}
}
private fun increaseColumnCount() {
directories_vertical_fastscroller.measureRecyclerViewOnRedraw()
directories_horizontal_fastscroller.measureRecyclerViewOnRedraw()
config.dirColumnCnt = ++(directories_grid.layoutManager as MyGridLayoutManager).spanCount
invalidateOptionsMenu()
directories_grid.adapter?.notifyDataSetChanged()
}
private fun reduceColumnCount() {
directories_vertical_fastscroller.measureRecyclerViewOnRedraw()
directories_horizontal_fastscroller.measureRecyclerViewOnRedraw()
config.dirColumnCnt = --(directories_grid.layoutManager as MyGridLayoutManager).spanCount
invalidateOptionsMenu()
directories_grid.adapter?.notifyDataSetChanged()
}
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 != null) {
val resultIntent = Intent()
if (mIsThirdPartyIntent) {
when {
intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true -> fillExtraOutput(resultData)
resultData.extras?.containsKey(PICKED_PATHS) == true -> fillPickedPaths(resultData, resultIntent)
else -> fillIntentPath(resultData, resultIntent)
}
}
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) {
val path = 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(path))
outputStream = contentResolver.openOutputStream(output)
inputStream.copyTo(outputStream)
} catch (e: SecurityException) {
showErrorToast(e)
} catch (ignored: FileNotFoundException) {
} finally {
inputStream?.close()
outputStream?.close()
}
}
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) {
Intent(this, MediaActivity::class.java).apply {
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<Directory>) {
val dirs = getSortedDirectories(newDirs)
var isPlaceholderVisible = dirs.isEmpty()
runOnUiThread {
checkPlaceholderVisibility(dirs)
val allowHorizontalScroll = config.scrollHorizontally && config.viewTypeFiles == VIEW_TYPE_GRID
directories_vertical_fastscroller.beVisibleIf(directories_grid.isVisible() && !allowHorizontalScroll)
directories_horizontal_fastscroller.beVisibleIf(directories_grid.isVisible() && allowHorizontalScroll)
setupAdapter(dirs)
}
// cached folders have been loaded, recheck folders one by one starting with the first displayed
Thread {
val mediaFetcher = 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 isSortingAscending = config.directorySorting and SORT_DESCENDING == 0
val mediumDao = galleryDB.MediumDao()
val directoryDao = galleryDB.DirectoryDao()
val getProperDateTaken = config.directorySorting and SORT_BY_DATE_TAKEN != 0
for (directory in dirs) {
val curMedia = mediaFetcher.getFilesFrom(directory.path, getImagesOnly, getVideosOnly, getProperDateTaken)
val newDir = if (curMedia.isEmpty()) {
directory
} else {
createDirectoryFromMedia(directory.path, curMedia, albumCovers, hiddenString, includedFolders, isSortingAscending)
}
// we are looping through the already displayed folders looking for changes, do not do anything if nothing changed
if (directory == 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
}
showSortedDirs(dirs)
// update directories and media files in the local db, delete invalid items
updateDBDirectory(directory)
mediumDao.insertAll(curMedia)
getCachedMedia(directory.path, getVideosOnly, getImagesOnly) {
it.forEach {
if (!curMedia.contains(it)) {
mediumDao.deleteMediumPath(it.path)
}
}
}
}
val foldersToScan = mediaFetcher.getFoldersToScan()
dirs.forEach {
foldersToScan.remove(it.path)
}
// check the remaining folders which were not cached at all yet
for (folder in foldersToScan) {
val newMedia = mediaFetcher.getFilesFrom(folder, getImagesOnly, getVideosOnly, getProperDateTaken)
if (newMedia.isEmpty()) {
continue
}
if (isPlaceholderVisible) {
isPlaceholderVisible = false
runOnUiThread {
directories_empty_text_label.beGone()
directories_empty_text.beGone()
directories_grid.beVisible()
}
}
val newDir = createDirectoryFromMedia(folder, newMedia, albumCovers, hiddenString, includedFolders, isSortingAscending)
dirs.add(newDir)
showSortedDirs(dirs)
directoryDao.insert(newDir)
mediumDao.insertAll(newMedia)
}
mIsGettingDirs = false
mLoadedInitialPhotos = true
checkLastMediaChanged()
runOnUiThread {
directories_refresh_layout.isRefreshing = false
directories_vertical_fastscroller.measureRecyclerView()
checkPlaceholderVisibility(dirs)
}
checkInvalidDirectories(dirs, directoryDao)
}.start()
}
private fun checkPlaceholderVisibility(dirs: ArrayList<Directory>) {
directories_empty_text_label.beVisibleIf(dirs.isEmpty() && mLoadedInitialPhotos)
directories_empty_text.beVisibleIf(dirs.isEmpty() && mLoadedInitialPhotos)
directories_grid.beVisibleIf(directories_empty_text_label.isGone())
}
private fun showSortedDirs(dirs: ArrayList<Directory>) {
var sortedDirs = getSortedDirectories(dirs).clone() as ArrayList<Directory>
sortedDirs = sortedDirs.distinctBy { it.path.getDistinctPath() } as ArrayList<Directory>
runOnUiThread {
(directories_grid.adapter as DirectoryAdapter).updateDirs(sortedDirs)
}
}
private fun createDirectoryFromMedia(path: String, curMedia: ArrayList<Medium>, albumCovers: ArrayList<AlbumCover>, hiddenString: String,
includedFolders: MutableSet<String>, isSortingAscending: Boolean): Directory {
var thumbnail = curMedia.firstOrNull { getDoesFilePathExist(it.path) }?.path ?: ""
if (thumbnail.startsWith(OTG_PATH)) {
thumbnail = thumbnail.getOTGPublicPath(applicationContext)
}
albumCovers.forEach {
if (it.path == path && getDoesFilePathExist(it.tmb)) {
thumbnail = it.tmb
}
}
val mediaTypes = curMedia.getDirMediaTypes()
val dirName = checkAppendingHidden(path, hiddenString, includedFolders)
val firstItem = curMedia.first()
val lastItem = curMedia.last()
val lastModified = if (isSortingAscending) Math.min(firstItem.modified, lastItem.modified) else Math.max(firstItem.modified, lastItem.modified)
val dateTaken = if (isSortingAscending) Math.min(firstItem.taken, lastItem.taken) else Math.max(firstItem.taken, lastItem.taken)
val size = curMedia.sumByLong { it.size }
return Directory(null, path, thumbnail, dirName, curMedia.size, lastModified, dateTaken, size, getPathLocation(path), mediaTypes)
}
private fun setupAdapter(dirs: ArrayList<Directory>) {
val currAdapter = directories_grid.adapter
if (currAdapter == null) {
initZoomListener()
val fastscroller = if (config.scrollHorizontally) directories_horizontal_fastscroller else directories_vertical_fastscroller
DirectoryAdapter(this, dirs, this, directories_grid, isPickIntent(intent) || isGetAnyContentIntent(intent), fastscroller) {
val path = (it as Directory).path
if (path != config.tempFolderPath) {
itemClicked(path)
}
}.apply {
setupZoomListener(mZoomListener)
directories_grid.adapter = this
}
} else {
(currAdapter as DirectoryAdapter).updateDirs(dirs)
}
setupScrollDirection()
}
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.allowBubbleDisplay = config.showInfoBubble
directories_horizontal_fastscroller.setViews(directories_grid, directories_refresh_layout) {
directories_horizontal_fastscroller.updateBubbleText(getBubbleTextItem(it))
}
} else {
directories_vertical_fastscroller.allowBubbleDisplay = config.showInfoBubble
directories_vertical_fastscroller.setViews(directories_grid, directories_refresh_layout) {
directories_vertical_fastscroller.updateBubbleText(getBubbleTextItem(it))
}
}
}
private fun checkInvalidDirectories(dirs: ArrayList<Directory>, directoryDao: DirectoryDao) {
val invalidDirs = ArrayList<Directory>()
dirs.forEach {
if (!getDoesFilePathExist(it.path)) {
invalidDirs.add(it)
} else if (it.path != config.tempFolderPath) {
val children = if (it.path.startsWith(OTG_PATH)) getOTGFolderChildrenNames(it.path) else File(it.path).list()?.asList()
val hasMediaFile = children?.any { it.isImageVideoGif() } ?: false
if (!hasMediaFile) {
invalidDirs.add(it)
}
}
}
if (invalidDirs.isNotEmpty()) {
dirs.removeAll(invalidDirs)
showSortedDirs(dirs)
invalidDirs.forEach {
directoryDao.deleteDirPath(it.path)
}
}
}
private fun getCurrentlyDisplayedDirs() = getRecyclerAdapter()?.dirs ?: ArrayList()
private fun getBubbleTextItem(index: Int) = getRecyclerAdapter()?.dirs?.getOrNull(index)?.getBubbleText(config.directorySorting) ?: ""
private fun setupLatestMediaId() {
Thread {
if (hasPermission(PERMISSION_READ_STORAGE)) {
mLatestMediaId = getLatestMediaId()
mLatestMediaDateId = getLatestMediaByDateId()
}
}.start()
}
private fun checkLastMediaChanged() {
if (isActivityDestroyed()) {
return
}
mLastMediaHandler.postDelayed({
Thread {
val mediaId = getLatestMediaId()
val mediaDateId = getLatestMediaByDateId()
if (mLatestMediaId != mediaId || mLatestMediaDateId != mediaDateId) {
mLatestMediaId = mediaId
mLatestMediaDateId = mediaDateId
runOnUiThread {
getDirectories()
}
} else {
mLastMediaHandler.removeCallbacksAndMessages(null)
checkLastMediaChanged()
}
}.start()
}, LAST_MEDIA_CHECK_PERIOD)
}
override fun refreshItems() {
getDirectories()
}
override fun recheckPinnedFolders() {
gotDirectories(movePinnedDirectoriesToFront(getCurrentlyDisplayedDirs()))
}
override fun updateDirectories(directories: ArrayList<Directory>) {
Thread {
storeDirectoryItems(directories)
removeInvalidDBDirectories()
}.start()
}
private fun checkWhatsNewDialog() {
arrayListOf<Release>().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))
add(Release(112, R.string.release_112))
add(Release(114, R.string.release_114))
add(Release(115, R.string.release_115))
add(Release(118, R.string.release_118))
add(Release(119, R.string.release_119))
add(Release(122, R.string.release_122))
add(Release(123, R.string.release_123))
add(Release(125, R.string.release_125))
add(Release(127, R.string.release_127))
add(Release(133, R.string.release_133))
add(Release(136, R.string.release_136))
add(Release(137, R.string.release_137))
add(Release(138, R.string.release_138))
add(Release(143, R.string.release_143))
add(Release(158, R.string.release_158))
add(Release(159, R.string.release_159))
add(Release(163, R.string.release_163))
add(Release(177, R.string.release_177))
add(Release(178, R.string.release_178))
checkWhatsNew(this, BuildConfig.VERSION_CODE)
}
}
}

View file

@ -1,169 +0,0 @@
package com.simplemobiletools.gallery.activities
import android.content.Intent
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.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.*
import com.simplemobiletools.gallery.models.Medium
import kotlinx.android.synthetic.main.fragment_holder.*
import java.io.File
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)
setTranslucentNavigation()
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
checkIntent(savedInstanceState)
} else {
toast(R.string.no_storage_permissions)
finish()
}
}
}
override fun onResume() {
super.onResume()
supportActionBar?.setBackgroundDrawable(resources.getDrawable(R.drawable.actionbar_gradient_background))
if (config.blackBackground) {
updateStatusbarColor(Color.BLACK)
}
}
private fun checkIntent(savedInstanceState: Bundle? = null) {
mUri = intent.data ?: return
if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
val realPath = intent.extras.getString(REAL_FILE_PATH)
sendViewPagerIntent(realPath)
finish()
return
}
mIsFromGallery = intent.getBooleanExtra(IS_FROM_GALLERY, false)
if (mUri!!.scheme == "file") {
scanPathRecursively(mUri!!.path)
sendViewPagerIntent(mUri!!.path)
finish()
return
} else {
val path = applicationContext.getRealPathFromURI(mUri!!) ?: ""
if (path != mUri.toString() && path.isNotEmpty() && mUri!!.authority != "mms") {
scanPathRecursively(mUri!!.path)
sendViewPagerIntent(path)
finish()
return
}
}
showSystemUI()
val bundle = Bundle()
val file = File(mUri.toString())
val type = when {
file.isImageFast() -> TYPE_IMAGES
file.isVideoFast() -> TYPE_VIDEOS
else -> TYPE_GIFS
}
mMedium = Medium(null, getFilenameFromUri(mUri!!), mUri.toString(), mUri!!.path.getParentPath(), 0, 0, file.length(), type)
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_holder, mFragment).commit()
}
if (config.blackBackground) {
fragment_holder.background = ColorDrawable(Color.BLACK)
}
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
val isFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
mFragment?.fullscreenToggled(isFullscreen)
}
}
private fun sendViewPagerIntent(path: String) {
Intent(this, ViewPagerActivity::class.java).apply {
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)
menu.apply {
findItem(R.id.menu_set_as).isVisible = mMedium?.isImage() == true
findItem(R.id.menu_edit).isVisible = mMedium?.isImage() == true && mUri?.scheme == "file"
findItem(R.id.menu_properties).isVisible = mUri?.scheme == "file"
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (mMedium == 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()
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun showProperties() {
PropertiesDialog(this, mUri!!.path)
}
override fun fragmentClicked() {
mIsFullScreen = !mIsFullScreen
if (mIsFullScreen) {
hideSystemUI()
} else {
showSystemUI()
}
}
override fun videoEnded() = false
override fun goToPrevItem() {}
override fun goToNextItem() {}
}

View file

@ -1,412 +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.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.dialogs.SecurityDialog
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.getAdjustedPrimaryColor
import com.simplemobiletools.commons.extensions.handleHiddenFolderPasswordProtection
import com.simplemobiletools.commons.extensions.updateTextColors
import com.simplemobiletools.commons.helpers.PROTECTION_FINGERPRINT
import com.simplemobiletools.commons.helpers.SHOW_ALL_TABS
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.dialogs.ManageExtendedDetailsDialog
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.helpers.ROTATE_BY_ASPECT_RATIO
import com.simplemobiletools.gallery.helpers.ROTATE_BY_DEVICE_ROTATION
import com.simplemobiletools.gallery.helpers.ROTATE_BY_SYSTEM_SETTING
import kotlinx.android.synthetic.main.activity_settings.*
import java.util.*
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()
setupUseEnglish()
setupAvoidWhatsNew()
setupManageIncludedFolders()
setupManageExcludedFolders()
setupManageHiddenFolders()
setupShowHiddenItems()
setupDoExtraCheck()
setupAutoplayVideos()
setupLoopVideos()
setupAnimateGifs()
setupMaxBrightness()
setupCropThumbnails()
setupDarkBackground()
setupScrollHorizontally()
setupScreenRotation()
setupHideSystemUI()
setupReplaceShare()
setupPasswordProtection()
setupAppPasswordProtection()
setupDeleteEmptyFolders()
setupAllowPhotoGestures()
setupAllowVideoGestures()
setupShowMediaCount()
setupKeepLastModified()
setupShowInfoBubble()
setupEnablePullToRefresh()
setupOneFingerZoom()
setupAllowInstantChange()
setupReplaceZoomableImages()
setupShowExtendedDetails()
setupHideExtendedDetails()
setupManageExtendedDetails()
setupSkipDeleteConfirmation()
updateTextColors(settings_holder)
setupSectionColors()
}
private fun setupSectionColors() {
val adjustedPrimaryColor = getAdjustedPrimaryColor()
arrayListOf(visibility_label, videos_label, thumbnails_label, scrolling_label, fullscreen_media_label, security_label,
file_operations_label, extended_details_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 setupAvoidWhatsNew() {
settings_avoid_whats_new.isChecked = config.avoidWhatsNew
settings_avoid_whats_new_holder.setOnClickListener {
settings_avoid_whats_new.toggle()
config.avoidWhatsNew = settings_avoid_whats_new.isChecked
}
}
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.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 setupDoExtraCheck() {
settings_do_extra_check.isChecked = config.doExtraCheck
settings_do_extra_check_holder.setOnClickListener {
settings_do_extra_check.toggle()
config.doExtraCheck = settings_do_extra_check.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_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 setupReplaceShare() {
settings_replace_share.isChecked = config.replaceShare
settings_replace_share_holder.setOnClickListener {
settings_replace_share.toggle()
config.replaceShare = settings_replace_share.isChecked
}
}
private fun setupPasswordProtection() {
settings_password_protection.isChecked = config.isPasswordProtectionOn
settings_password_protection_holder.setOnClickListener {
val tabToShow = if (config.isPasswordProtectionOn) config.protectionType else SHOW_ALL_TABS
SecurityDialog(this, config.passwordHash, tabToShow) { hash, type, success ->
if (success) {
val hasPasswordProtection = config.isPasswordProtectionOn
settings_password_protection.isChecked = !hasPasswordProtection
config.isPasswordProtectionOn = !hasPasswordProtection
config.passwordHash = if (hasPasswordProtection) "" else hash
config.protectionType = type
if (config.isPasswordProtectionOn) {
val confirmationTextId = if (config.protectionType == 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.appPasswordProtectionOn
settings_app_password_protection_holder.setOnClickListener {
val tabToShow = if (config.appPasswordProtectionOn) config.appProtectionType else SHOW_ALL_TABS
SecurityDialog(this, config.appPasswordHash, tabToShow) { hash, type, success ->
if (success) {
val hasPasswordProtection = config.appPasswordProtectionOn
settings_app_password_protection.isChecked = !hasPasswordProtection
config.appPasswordProtectionOn = !hasPasswordProtection
config.appPasswordHash = if (hasPasswordProtection) "" else hash
config.appProtectionType = type
if (config.appPasswordProtectionOn) {
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 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 setupAllowPhotoGestures() {
settings_allow_photo_gestures.isChecked = config.allowPhotoGestures
settings_allow_photo_gestures_holder.setOnClickListener {
settings_allow_photo_gestures.toggle()
config.allowPhotoGestures = settings_allow_photo_gestures.isChecked
}
}
private fun setupAllowVideoGestures() {
settings_allow_video_gestures.isChecked = config.allowVideoGestures
settings_allow_video_gestures_holder.setOnClickListener {
settings_allow_video_gestures.toggle()
config.allowVideoGestures = settings_allow_video_gestures.isChecked
}
}
private fun setupShowMediaCount() {
settings_show_media_count.isChecked = config.showMediaCount
settings_show_media_count_holder.setOnClickListener {
settings_show_media_count.toggle()
config.showMediaCount = settings_show_media_count.isChecked
}
}
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 setupShowInfoBubble() {
settings_show_info_bubble.isChecked = config.showInfoBubble
settings_show_info_bubble_holder.setOnClickListener {
settings_show_info_bubble.toggle()
config.showInfoBubble = settings_show_info_bubble.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 setupOneFingerZoom() {
settings_one_finger_zoom.isChecked = config.oneFingerZoom
settings_one_finger_zoom_holder.setOnClickListener {
settings_one_finger_zoom.toggle()
config.oneFingerZoom = settings_one_finger_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 setupReplaceZoomableImages() {
settings_replace_zoomable_images.isChecked = config.replaceZoomableImages
settings_replace_zoomable_images_holder.setOnClickListener {
settings_replace_zoomable_images.toggle()
config.replaceZoomableImages = settings_replace_zoomable_images.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, 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
})
}

View file

@ -1,30 +0,0 @@
package com.simplemobiletools.gallery.activities
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.gallery.R
open class SimpleActivity : BaseSimpleActivity() {
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)
}

View file

@ -1,11 +0,0 @@
package com.simplemobiletools.gallery.activities
import android.content.Intent
import com.simplemobiletools.commons.activities.BaseSplashActivity
class SplashActivity : BaseSplashActivity() {
override fun initActivity() {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}

View file

@ -1,933 +0,0 @@
package com.simplemobiletools.gallery.activities
import android.animation.Animator
import android.animation.ValueAnimator
import android.annotation.TargetApi
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.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
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.View
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import com.bumptech.glide.Glide
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.R
import com.simplemobiletools.gallery.adapters.MyPagerAdapter
import com.simplemobiletools.gallery.asynctasks.GetMediaAsynctask
import com.simplemobiletools.gallery.dialogs.DeleteWithRememberDialog
import com.simplemobiletools.gallery.dialogs.SaveAsDialog
import com.simplemobiletools.gallery.dialogs.SlideshowDialog
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.*
import com.simplemobiletools.gallery.models.Medium
import kotlinx.android.synthetic.main.activity_medium.*
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.util.*
class ViewPagerActivity : SimpleActivity(), ViewPager.OnPageChangeListener, ViewPagerFragment.FragmentListener {
private var mPath = ""
private var mDirectory = ""
private var mIsFullScreen = false
private var mPos = -1
private var mShowAll = false
private var mIsSlideshowActive = false
private var mRotationDegrees = 0
private var mPrevHashcode = 0
private var mSlideshowHandler = Handler()
private var mSlideshowInterval = SLIDESHOW_DEFAULT_INTERVAL
private var mSlideshowMoveBackwards = false
private var mSlideshowMedia = mutableListOf<Medium>()
private var mAreSlideShowMediaVisible = false
private var mIsOrientationLocked = false
private var mStoredReplaceZoomableImages = false
private var mMediaFiles = ArrayList<Medium>()
companion object {
var screenWidth = 0
var screenHeight = 0
var wasDecodedByGlide = false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_medium)
setTranslucentNavigation()
mMediaFiles = MediaActivity.mMedia.clone() as ArrayList<Medium>
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
initViewPager()
} else {
toast(R.string.no_storage_permissions)
finish()
}
}
storeStateVariables()
}
override fun onResume() {
super.onResume()
if (!hasPermission(PERMISSION_WRITE_STORAGE)) {
finish()
return
}
if (mStoredReplaceZoomableImages != config.replaceZoomableImages) {
mPrevHashcode = 0
refreshViewPager()
}
supportActionBar?.setBackgroundDrawable(resources.getDrawable(R.drawable.actionbar_gradient_background))
if (config.maxBrightness) {
val attributes = window.attributes
attributes.screenBrightness = 1f
window.attributes = attributes
}
setupRotation()
invalidateOptionsMenu()
if (config.blackBackground) {
updateStatusbarColor(Color.BLACK)
}
}
override fun onPause() {
super.onPause()
stopSlideshow()
storeStateVariables()
}
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()
}
}
}
private fun initViewPager() {
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 {
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 (!getDoesFilePathExist(mPath)) {
Thread {
scanPathRecursively(mPath)
}.start()
finish()
return
}
if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) {
if (isShowHiddenFlagNeeded()) {
if (!config.isPasswordProtectionOn) {
config.temporarilyShowHidden = true
}
}
config.isThirdPartyIntent = true
}
showSystemUI()
mDirectory = mPath.getParentPath()
if (mDirectory.startsWith(OTG_PATH.trimEnd('/'))) {
mDirectory += "/"
}
supportActionBar?.title = mPath.getFilenameFromPath()
view_pager.onGlobalLayout {
if (!isActivityDestroyed()) {
if (mMediaFiles.isNotEmpty()) {
gotMedia(mMediaFiles)
}
}
}
refreshViewPager()
if (config.blackBackground) {
view_pager.background = ColorDrawable(Color.BLACK)
}
if (config.hideSystemUI) {
view_pager.onGlobalLayout {
Handler().postDelayed({
fragmentClicked()
}, 500)
}
}
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
mIsFullScreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
view_pager.adapter?.let {
(it as MyPagerAdapter).toggleFullscreen(mIsFullScreen)
checkSystemUI()
}
}
}
private fun setupRotation() {
if (mIsOrientationLocked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED
}
} else 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
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_viewpager, menu)
val currentMedium = getCurrentMedium() ?: return true
menu.apply {
findItem(R.id.menu_share_1).isVisible = !config.replaceShare
findItem(R.id.menu_share_2).isVisible = config.replaceShare
findItem(R.id.menu_rotate).isVisible = currentMedium.isImage()
findItem(R.id.menu_save_as).isVisible = mRotationDegrees != 0
findItem(R.id.menu_hide).isVisible = !currentMedium.name.startsWith('.')
findItem(R.id.menu_unhide).isVisible = currentMedium.name.startsWith('.')
findItem(R.id.menu_lock_orientation).isVisible = mRotationDegrees == 0
findItem(R.id.menu_lock_orientation).title = getString(if (mIsOrientationLocked) R.string.unlock_orientation else R.string.lock_orientation)
findItem(R.id.menu_rotate).setShowAsAction(
if (mRotationDegrees != 0) {
MenuItem.SHOW_AS_ACTION_ALWAYS
} else {
MenuItem.SHOW_AS_ACTION_IF_ROOM
})
}
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 -> copyMoveTo(false)
R.id.menu_open_with -> openPath(getCurrentPath(), true)
R.id.menu_hide -> toggleFileVisibility(true)
R.id.menu_unhide -> toggleFileVisibility(false)
R.id.menu_share_1 -> shareMedium(getCurrentMedium()!!)
R.id.menu_share_2 -> shareMedium(getCurrentMedium()!!)
R.id.menu_delete -> checkDeleteConfirmation()
R.id.menu_rename -> renameFile()
R.id.menu_edit -> openEditor(getCurrentPath())
R.id.menu_properties -> showProperties()
R.id.menu_show_on_map -> showOnMap()
R.id.menu_rotate_right -> rotateImage(90)
R.id.menu_rotate_left -> rotateImage(270)
R.id.menu_rotate_one_eighty -> rotateImage(180)
R.id.menu_lock_orientation -> toggleLockOrientation()
R.id.menu_save_as -> saveImageAs()
R.id.menu_settings -> launchSettings()
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun storeStateVariables() {
config.apply {
mStoredReplaceZoomableImages = replaceZoomableImages
}
}
private fun updatePagerItems(media: MutableList<Medium>) {
val pagerAdapter = MyPagerAdapter(this, supportFragmentManager, media)
if (!isActivityDestroyed()) {
view_pager.apply {
adapter = pagerAdapter
currentItem = mPos
removeOnPageChangeListener(this@ViewPagerActivity)
addOnPageChangeListener(this@ViewPagerActivity)
}
}
}
private fun initSlideshow() {
SlideshowDialog(this) {
startSlideshow()
}
}
private fun startSlideshow() {
if (getMediaForSlideshow()) {
view_pager.onGlobalLayout {
if (!isActivityDestroyed()) {
hideSystemUI()
mSlideshowInterval = config.slideshowInterval
mSlideshowMoveBackwards = config.slideshowMoveBackwards
mIsSlideshowActive = true
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
scheduleSwipe()
}
}
}
}
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?) {
}
})
animator.interpolator = DecelerateInterpolator()
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()
}
}
}
})
animator.duration = SLIDESHOW_SCROLL_DURATION
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) {
mIsSlideshowActive = false
showSystemUI()
mSlideshowHandler.removeCallbacksAndMessages(null)
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
private fun scheduleSwipe() {
mSlideshowHandler.removeCallbacksAndMessages(null)
if (mIsSlideshowActive) {
if (getCurrentMedium()!!.isImage() || getCurrentMedium()!!.isGif()) {
mSlideshowHandler.postDelayed({
if (mIsSlideshowActive && !isActivityDestroyed()) {
swipeToNextMedium()
}
}, mSlideshowInterval * 1000L)
} else {
(getCurrentFragment() as? VideoFragment)!!.playVideo()
}
}
}
private fun swipeToNextMedium() {
animatePagerTransition(!mSlideshowMoveBackwards)
}
private fun getMediaForSlideshow(): Boolean {
mSlideshowMedia = mMediaFiles.toMutableList()
if (!config.slideshowIncludePhotos) {
mSlideshowMedia = mSlideshowMedia.filter { !it.isImage() } as MutableList
}
if (!config.slideshowIncludeVideos) {
mSlideshowMedia = mSlideshowMedia.filter { it.isImage() || it.isGif() } as MutableList
}
if (!config.slideshowIncludeGIFs) {
mSlideshowMedia = mSlideshowMedia.filter { !it.isGif() } as MutableList
}
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 copyMoveTo(isCopyOperation: Boolean) {
val currPath = getCurrentPath()
val fileDirItems = arrayListOf(FileDirItem(currPath, currPath.getFilenameFromPath()))
tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
config.tempFolderPath = ""
if (!isCopyOperation) {
refreshViewPager()
}
}
}
private fun toggleFileVisibility(hide: Boolean) {
toggleFileVisibility(getCurrentPath(), hide) {
val newFileName = it.getFilenameFromPath()
supportActionBar?.title = newFileName
getCurrentMedium()!!.apply {
name = newFileName
path = it
getCurrentMedia()[mPos] = this
}
invalidateOptionsMenu()
}
}
private fun rotateImage(degrees: Int) {
mRotationDegrees = (mRotationDegrees + degrees) % 360
getCurrentFragment()?.let {
(it as? PhotoFragment)?.rotateImageViewBy(mRotationDegrees)
}
supportInvalidateOptionsMenu()
}
private fun toggleLockOrientation() {
mIsOrientationLocked = !mIsOrientationLocked
if (mIsOrientationLocked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED
}
} else {
setupRotation()
}
invalidateOptionsMenu()
}
private fun saveImageAs() {
val currPath = getCurrentPath()
SaveAsDialog(this, currPath, false) {
handleSAFDialog(it) {
Thread {
saveImageToFile(currPath, it)
}.start()
}
}
}
private fun saveImageToFile(oldPath: String, newPath: String) {
toast(R.string.saving)
if (oldPath == newPath && oldPath.isJpg()) {
if (tryRotateByExif(oldPath)) {
return
}
}
val tmpPath = "$filesDir/.tmp_${newPath.getFilenameFromPath()}"
val tmpFileDirItem = FileDirItem(tmpPath, tmpPath.getFilenameFromPath())
try {
getFileOutputStream(tmpFileDirItem) {
if (it == null) {
toast(R.string.unknown_error_occurred)
return@getFileOutputStream
}
val oldLastModified = getCurrentFile().lastModified()
if (oldPath.isJpg()) {
copyFile(getCurrentPath(), tmpPath)
saveExifRotation(ExifInterface(tmpPath), mRotationDegrees)
} else {
val inputstream = getFileInputStreamSync(oldPath)
val bitmap = BitmapFactory.decodeStream(inputstream)
saveFile(tmpPath, bitmap, it as FileOutputStream)
}
if (getDoesFilePathExist(newPath)) {
tryDeleteFileDirItem(FileDirItem(newPath, newPath.getFilenameFromPath()))
}
copyFile(tmpPath, newPath)
scanPathRecursively(newPath)
toast(R.string.file_saved)
if (config.keepLastModified) {
File(newPath).setLastModified(oldLastModified)
updateLastModified(newPath, oldLastModified)
}
it.flush()
it.close()
mRotationDegrees = 0
invalidateOptionsMenu()
// we cannot refresh a specific image in Glide Cache, so just clear it all
val glide = Glide.get(applicationContext)
glide.clearDiskCache()
runOnUiThread {
glide.clearMemory()
}
}
} catch (e: OutOfMemoryError) {
toast(R.string.out_of_memory_error)
} catch (e: Exception) {
showErrorToast(e)
} finally {
tryDeleteFileDirItem(tmpFileDirItem)
}
}
@TargetApi(Build.VERSION_CODES.N)
private fun tryRotateByExif(path: String): Boolean {
return try {
if (saveImageRotation(path, mRotationDegrees)) {
mRotationDegrees = 0
invalidateOptionsMenu()
toast(R.string.file_saved)
true
} else {
false
}
} catch (e: Exception) {
showErrorToast(e)
false
}
}
private fun copyFile(source: String, destination: String) {
var inputStream: InputStream? = null
var out: OutputStream? = null
try {
out = getFileOutputStreamSync(destination, source.getMimeType())
inputStream = getFileInputStreamSync(source)
inputStream?.copyTo(out!!)
} finally {
inputStream?.close()
out?.close()
}
}
private fun saveFile(path: String, bitmap: Bitmap, out: FileOutputStream) {
val matrix = Matrix()
matrix.postRotate(mRotationDegrees.toFloat())
val bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bmp.compress(path.getCompressionFormat(), 90, out)
}
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 showOnMap() {
val exif: ExifInterface
try {
exif = ExifInterface(getCurrentPath())
} catch (e: Exception) {
showErrorToast(e)
return
}
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_app_found)
}
}
}
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
mPrevHashcode = 0
refreshViewPager()
}
} else if (requestCode == REQUEST_SET_AS) {
if (resultCode == Activity.RESULT_OK) {
toast(R.string.wallpaper_set_successfully)
}
}
super.onActivityResult(requestCode, resultCode, resultData)
}
private fun checkDeleteConfirmation() {
if (config.tempSkipDeleteConfirmation || config.skipDeleteConfirmation) {
deleteConfirmed()
} else {
askConfirmDelete()
}
}
private fun askConfirmDelete() {
DeleteWithRememberDialog(this, getString(R.string.proceed_with_deletion)) {
config.tempSkipDeleteConfirmation = it
deleteConfirmed()
}
}
private fun deleteConfirmed() {
val path = getCurrentMedia()[mPos].path
tryDeleteFileDirItem(FileDirItem(path, path.getFilenameFromPath())) {
refreshViewPager()
}
}
private fun isDirEmpty(media: ArrayList<Medium>): 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()
}
Thread {
updateDBMediaPath(oldPath, it)
}.start()
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 refreshViewPager() {
GetMediaAsynctask(applicationContext, mDirectory, false, false, mShowAll) {
gotMedia(it)
}.execute()
}
private fun gotMedia(media: ArrayList<Medium>) {
if (isDirEmpty(media) || media.hashCode() == mPrevHashcode) {
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()
}
private fun getPositionInList(items: MutableList<Medium>): Int {
mPos = 0
for ((i, medium) in items.withIndex()) {
if (medium.path == mPath) {
return i
}
}
return mPos
}
private fun deleteDirectoryIfEmpty() {
val fileDirItem = FileDirItem(mDirectory, mDirectory.getFilenameFromPath(), getIsPathDirectory(mDirectory))
if (config.deleteEmptyFolders && !fileDirItem.isDownloadsFolder() && fileDirItem.isDirectory && fileDirItem.getProperFileCount(applicationContext, true) == 0) {
tryDeleteFileDirItem(fileDirItem, true)
}
scanPathRecursively(mDirectory)
}
private fun checkOrientation() {
if (!mIsOrientationLocked && config.screenRotation == ROTATE_BY_ASPECT_RATIO) {
var flipSides = false
try {
val pathToLoad = getCurrentPath()
val exif = android.media.ExifInterface(pathToLoad)
val orientation = exif.getAttributeInt(android.media.ExifInterface.TAG_ORIENTATION, -1)
flipSides = orientation == ExifInterface.ORIENTATION_ROTATE_90 || orientation == ExifInterface.ORIENTATION_ROTATE_270
} catch (e: Exception) {
}
val res = getCurrentPath().getResolution() ?: return
val width = if (flipSides) res.y else res.x
val height = if (flipSides) res.x else res.y
if (width > height) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else if (width < height) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
}
override fun fragmentClicked() {
mIsFullScreen = !mIsFullScreen
checkSystemUI()
}
override fun videoEnded(): Boolean {
if (mIsSlideshowActive) {
swipeToNextMedium()
}
return 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()
}
private fun checkSystemUI() {
if (mIsFullScreen) {
hideSystemUI()
} else {
stopSlideshow()
showSystemUI()
}
}
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
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
}
if (mPos != position) {
mPos = position
updateActionbarTitle()
mRotationDegrees = 0
supportInvalidateOptionsMenu()
scheduleSwipe()
}
}
override fun onPageScrollStateChanged(state: Int) {
if (state == ViewPager.SCROLL_STATE_IDLE && getCurrentMedium() != null) {
checkOrientation()
}
}
}

View file

@ -1,469 +0,0 @@
package com.simplemobiletools.gallery.adapters
import android.util.SparseArray
import android.view.Menu
import android.view.View
import android.view.ViewGroup
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.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.PropertiesDialog
import com.simplemobiletools.commons.dialogs.RenameItemDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.OTG_PATH
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.FastScroller
import com.simplemobiletools.commons.views.MyRecyclerView
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.dialogs.ExcludeFolderDialog
import com.simplemobiletools.gallery.dialogs.PickMediumDialog
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.*
import com.simplemobiletools.gallery.models.AlbumCover
import com.simplemobiletools.gallery.models.Directory
import kotlinx.android.synthetic.main.directory_item_list.view.*
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
class DirectoryAdapter(activity: BaseSimpleActivity, var dirs: ArrayList<Directory>, val listener: DirOperationsListener?, 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 showMediaCount = config.showMediaCount
private var animateGifs = config.animateGifs
private var cropThumbnails = config.cropThumbnails
private var currentDirectoriesHash = dirs.hashCode()
init {
setupDragListener(true)
}
override fun getActionMenuId() = R.menu.cab_directories
override fun prepareItemSelection(view: View) {
view.dir_check?.background?.applyColorFilter(primaryColor)
}
override fun markItemSelection(select: Boolean, view: View?) {
view?.dir_check?.beVisibleIf(select)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutType = if (isListViewType) R.layout.directory_item_list else R.layout.directory_item_grid
return createViewHolder(layoutType, parent)
}
override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) {
val dir = dirs.getOrNull(position) ?: return
val view = holder.bindView(dir, !isPickIntent) { itemView, adapterPosition ->
setupView(itemView, dir)
}
bindViewHolder(holder, position, view)
}
override fun getItemCount() = dirs.size
override fun prepareActionMode(menu: Menu) {
menu.apply {
findItem(R.id.cab_rename).isVisible = isOneItemSelected()
findItem(R.id.cab_change_cover_image).isVisible = isOneItemSelected()
checkHideBtnVisibility(this)
checkPinBtnVisibility(this)
}
}
override fun actionItemPressed(id: Int) {
if (selectedPositions.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_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)
}
}
override fun getSelectableItemCount() = dirs.size
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
if (!activity.isActivityDestroyed()) {
Glide.with(activity).clear(holder.itemView?.dir_thumbnail!!)
}
}
private fun checkHideBtnVisibility(menu: Menu) {
var hiddenCnt = 0
var unhiddenCnt = 0
selectedPositions.mapNotNull { dirs.getOrNull(it)?.path }.forEach {
if (File(it).doesThisOrParentHaveNoMedia()) {
hiddenCnt++
} else {
unhiddenCnt++
}
}
menu.findItem(R.id.cab_hide).isVisible = unhiddenCnt > 0
menu.findItem(R.id.cab_unhide).isVisible = hiddenCnt > 0
}
private fun checkPinBtnVisibility(menu: Menu) {
val pinnedFolders = config.pinnedFolders
var pinnedCnt = 0
var unpinnedCnt = 0
selectedPositions.mapNotNull { dirs.getOrNull(it)?.path }.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<String>()
selectedPositions.forEach { paths.add(dirs[it].path) }
PropertiesDialog(activity, paths, config.shouldShowHidden)
}
}
private fun renameDir() {
val firstDir = dirs[selectedPositions.first()]
val sourcePath = firstDir.path
val dir = File(sourcePath)
if (activity.isAStorageRootFolder(dir.absolutePath)) {
activity.toast(R.string.rename_folder_root)
return
}
RenameItemDialog(activity, dir.absolutePath) {
activity.runOnUiThread {
firstDir.apply {
path = it
name = it.getFilenameFromPath()
tmb = File(it, tmb.getFilenameFromPath()).absolutePath
}
updateDirs(dirs)
Thread {
activity.galleryDB.DirectoryDao().updateDirectoryAfterRename(firstDir.tmb, firstDir.name, firstDir.path, sourcePath)
listener?.refreshItems()
}.start()
}
}
}
private fun toggleFoldersVisibility(hide: Boolean) {
getSelectedPaths().forEach {
val path = it
if (hide) {
if (config.wasHideFolderTooltipShown) {
hideFolder(path)
} else {
config.wasHideFolderTooltipShown = true
ConfirmationDialog(activity, activity.getString(R.string.hide_folder_description)) {
hideFolder(path)
}
}
} else {
activity.removeNoMedia(path) {
if (activity.config.shouldShowHidden) {
updateFolderNames()
} else {
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}
}
}
}
}
private fun updateFolderNames() {
val includedFolders = activity.config.includedFolders
val hidden = activity.getString(R.string.hidden)
dirs.forEach {
it.name = activity.checkAppendingHidden(it.path, hidden, includedFolders)
}
listener?.updateDirectories(dirs.toList() as ArrayList)
activity.runOnUiThread {
updateDirs(dirs)
}
}
private fun hideFolder(path: String) {
activity.addNoMedia(path) {
if (activity.config.shouldShowHidden) {
updateFolderNames()
} else {
val affectedPositions = ArrayList<Int>()
val includedFolders = activity.config.includedFolders
val newDirs = dirs.filterIndexed { index, directory ->
val removeDir = File(directory.path).doesThisOrParentHaveNoMedia() && !includedFolders.contains(directory.path)
if (removeDir) {
affectedPositions.add(index)
}
!removeDir
} as ArrayList<Directory>
activity.runOnUiThread {
affectedPositions.sortedDescending().forEach {
notifyItemRemoved(it)
itemViews.put(it, null)
}
val newItems = SparseArray<View>()
(0 until itemViews.size())
.filter { itemViews[it] != null }
.forEachIndexed { curIndex, i -> newItems.put(curIndex, itemViews[i]) }
currentDirectoriesHash = newDirs.hashCode()
itemViews = newItems
dirs = newDirs
finishActMode()
fastScroller?.measureRecyclerView()
listener?.updateDirectories(newDirs)
}
}
}
}
private fun tryExcludeFolder() {
val paths = getSelectedPaths()
if (paths.size == 1) {
ExcludeFolderDialog(activity, paths.toList()) {
listener?.refreshItems()
finishActMode()
}
} else {
activity.config.addExcludedFolders(paths)
listener?.refreshItems()
finishActMode()
}
}
private fun pinFolders(pin: Boolean) {
if (pin) {
config.addPinnedFolders(getSelectedPaths())
} else {
config.removePinnedFolders(getSelectedPaths())
}
pinnedFolders = config.pinnedFolders
listener?.recheckPinnedFolders()
notifyDataSetChanged()
finishActMode()
}
private fun copyMoveTo(isCopyOperation: Boolean) {
val paths = ArrayList<String>()
val showHidden = activity.config.shouldShowHidden
selectedPositions.forEach {
val path = dirs[it].path
if (path.startsWith(OTG_PATH)) {
paths.addAll(getOTGFilePaths(path, showHidden))
} else {
File(path).listFiles()?.filter {
!activity.getIsPathDirectory(it.absolutePath) && it.isImageVideoGif() && (showHidden || !it.name.startsWith('.'))
}?.mapTo(paths, { it.absolutePath })
}
}
val fileDirItems = paths.map { FileDirItem(it, it.getFilenameFromPath()) } as ArrayList<FileDirItem>
activity.tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
config.tempFolderPath = ""
listener?.refreshItems()
finishActMode()
}
}
private fun getOTGFilePaths(path: String, showHidden: Boolean): ArrayList<String> {
val paths = ArrayList<String>()
activity.getOTGFolderChildren(path)?.forEach {
if (!it.isDirectory && it.name.isImageVideoGif() && (showHidden || !it.name.startsWith('.'))) {
val relativePath = it.uri.path.substringAfterLast("${activity.config.OTGPartition}:")
paths.add("$OTG_PATH$relativePath")
}
}
return paths
}
private fun askConfirmDelete() {
if (config.skipDeleteConfirmation) {
deleteFiles()
} else {
val items = resources.getQuantityString(R.plurals.delete_items, selectedPositions.size, selectedPositions.size)
val question = String.format(resources.getString(R.string.deletion_confirmation), items)
ConfirmationDialog(activity, question) {
deleteFiles()
}
}
}
private fun deleteFiles() {
if (selectedPositions.isEmpty()) {
return
}
val folders = ArrayList<File>(selectedPositions.size)
val removeFolders = ArrayList<Directory>(selectedPositions.size)
var SAFPath = ""
selectedPositions.forEach {
if (dirs.size > it) {
val path = dirs[it].path
if (activity.needsStupidWritePermissions(path) && config.treeUri.isEmpty()) {
SAFPath = path
}
}
}
activity.handleSAFDialog(SAFPath) {
selectedPositions.sortedDescending().forEach {
val directory = dirs[it]
folders.add(File(directory.path))
removeFolders.add(directory)
}
dirs.removeAll(removeFolders)
listener?.deleteFolders(folders)
removeSelectedItems()
}
}
private fun changeAlbumCover(useDefault: Boolean) {
if (selectedPositions.size != 1)
return
val path = dirs[selectedPositions.first()].path
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<AlbumCover>) {
activity.config.albumCovers = Gson().toJson(albumCovers)
finishActMode()
listener?.refreshItems()
}
private fun getSelectedPaths(): HashSet<String> {
val paths = HashSet<String>(selectedPositions.size)
selectedPositions.forEach { paths.add(dirs[it].path) }
return paths
}
fun updateDirs(newDirs: ArrayList<Directory>) {
if (newDirs.hashCode() != currentDirectoriesHash) {
currentDirectoriesHash = newDirs.hashCode()
dirs = newDirs.clone() as ArrayList<Directory>
notifyDataSetChanged()
finishActMode()
fastScroller?.measureRecyclerView()
}
}
fun updateAnimateGifs(animateGifs: Boolean) {
this.animateGifs = animateGifs
notifyDataSetChanged()
}
fun updateCropThumbnails(cropThumbnails: Boolean) {
this.cropThumbnails = cropThumbnails
notifyDataSetChanged()
}
fun updateShowMediaCount(showMediaCount: Boolean) {
this.showMediaCount = showMediaCount
notifyDataSetChanged()
}
fun updateScrollHorizontally(scrollHorizontally: Boolean) {
this.scrollHorizontally = scrollHorizontally
notifyDataSetChanged()
}
private fun setupView(view: View, directory: Directory) {
view.apply {
dir_name.text = directory.name
dir_path?.text = "${directory.path.substringBeforeLast("/")}/"
photo_cnt.text = directory.mediaCnt.toString()
val thumbnailType = when {
directory.tmb.isImageFast() -> TYPE_IMAGES
directory.tmb.isVideoFast() -> TYPE_VIDEOS
else -> TYPE_GIFS
}
activity.loadImage(thumbnailType, directory.tmb, dir_thumbnail, scrollHorizontally, animateGifs, cropThumbnails)
dir_pin.beVisibleIf(pinnedFolders.contains(directory.path))
dir_location.beVisibleIf(directory.location != LOCAITON_INTERNAL)
if (dir_location.isVisible()) {
dir_location.setImageResource(if (directory.location == LOCATION_SD) R.drawable.ic_sd_card else R.drawable.ic_usb)
}
photo_cnt.beVisibleIf(showMediaCount)
if (isListViewType) {
dir_name.setTextColor(textColor)
dir_path.setTextColor(textColor)
photo_cnt.setTextColor(textColor)
dir_pin.applyColorFilter(textColor)
dir_location.applyColorFilter(textColor)
}
}
}
interface DirOperationsListener {
fun refreshItems()
fun deleteFolders(folders: ArrayList<File>)
fun recheckPinnedFolders()
fun updateDirectories(directories: ArrayList<Directory>)
}
}

View file

@ -1,335 +0,0 @@
package com.simplemobiletools.gallery.adapters
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.View
import android.view.ViewGroup
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.RenameItemDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.OTG_PATH
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.FastScroller
import com.simplemobiletools.commons.views.MyRecyclerView
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.dialogs.DeleteWithRememberDialog
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.VIEW_TYPE_LIST
import com.simplemobiletools.gallery.models.Medium
import kotlinx.android.synthetic.main.photo_video_item_grid.view.*
class MediaAdapter(activity: BaseSimpleActivity, var media: MutableList<Medium>, val listener: MediaOperationsListener?, val isAGetIntent: Boolean,
val allowMultiplePicks: Boolean, 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 config = activity.config
private val isListViewType = config.viewTypeFiles == VIEW_TYPE_LIST
private var visibleItemPaths = ArrayList<String>()
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
init {
setupDragListener(true)
enableInstantLoad()
}
override fun getActionMenuId() = R.menu.cab_media
override fun prepareItemSelection(view: View) {
view.medium_check?.background?.applyColorFilter(primaryColor)
}
override fun markItemSelection(select: Boolean, view: View?) {
view?.medium_check?.beVisibleIf(select)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutType = 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 medium = media.getOrNull(position) ?: return
visibleItemPaths.add(medium.path)
val view = holder.bindView(medium, !allowMultiplePicks) { itemView, adapterPosition ->
setupView(itemView, medium)
}
bindViewHolder(holder, position, view)
}
override fun getItemCount() = media.size
override fun prepareActionMode(menu: Menu) {
menu.apply {
findItem(R.id.cab_rename).isVisible = isOneItemSelected()
findItem(R.id.cab_open_with).isVisible = isOneItemSelected()
findItem(R.id.cab_confirm_selection).isVisible = isAGetIntent && allowMultiplePicks && selectedPositions.size > 0
checkHideBtnVisibility(this)
}
}
override fun actionItemPressed(id: Int) {
if (selectedPositions.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_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_open_with -> activity.openPath(getCurrentPath(), true)
R.id.cab_set_as -> activity.setAs(getCurrentPath())
R.id.cab_delete -> checkDeleteConfirmation()
}
}
override fun getSelectableItemCount() = media.size
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
if (!activity.isActivityDestroyed()) {
val itemView = holder.itemView
visibleItemPaths.remove(itemView?.photo_name?.tag)
Glide.with(activity).clear(itemView?.medium_thumbnail!!)
}
}
private fun checkHideBtnVisibility(menu: Menu) {
var hiddenCnt = 0
var unhiddenCnt = 0
selectedPositions.mapNotNull { media.getOrNull(it) }.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 confirmSelection() {
val paths = getSelectedMedia().map { it.path } as ArrayList<String>
listener?.selectedPaths(paths)
}
private fun showProperties() {
if (selectedPositions.size <= 1) {
PropertiesDialog(activity, media[selectedPositions.first()].path, config.shouldShowHidden)
} else {
val paths = ArrayList<String>()
selectedPositions.forEach { paths.add(media[it].path) }
PropertiesDialog(activity, paths, config.shouldShowHidden)
}
}
private fun renameFile() {
val oldPath = getCurrentPath()
RenameItemDialog(activity, oldPath) {
Thread {
activity.updateDBMediaPath(oldPath, it)
activity.runOnUiThread {
enableInstantLoad()
listener?.refreshItems()
finishActMode()
}
}.start()
}
}
private fun editFile() {
activity.openEditor(getCurrentPath())
}
private fun toggleFileVisibility(hide: Boolean) {
Thread {
getSelectedMedia().forEach {
activity.toggleFileVisibility(it.path, hide)
}
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}.start()
}
private fun shareMedia() {
if (selectedPositions.size == 1 && selectedPositions.first() != -1) {
activity.shareMedium(getSelectedMedia()[0])
} else if (selectedPositions.size > 1) {
activity.shareMedia(getSelectedMedia())
}
}
private fun copyMoveTo(isCopyOperation: Boolean) {
val paths = ArrayList<String>()
selectedPositions.forEach { paths.add(media[it].path) }
val fileDirItems = paths.map { FileDirItem(it, it.getFilenameFromPath()) } as ArrayList
activity.tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
config.tempFolderPath = ""
activity.applicationContext.rescanFolderMedia(it)
activity.applicationContext.rescanFolderMedia(fileDirItems.first().getParentPath())
if (!isCopyOperation) {
listener?.refreshItems()
}
}
}
private fun checkDeleteConfirmation() {
if (config.tempSkipDeleteConfirmation || config.skipDeleteConfirmation) {
deleteFiles()
} else {
askConfirmDelete()
}
}
private fun askConfirmDelete() {
val items = resources.getQuantityString(R.plurals.delete_items, selectedPositions.size, selectedPositions.size)
val question = String.format(resources.getString(R.string.deletion_confirmation), items)
DeleteWithRememberDialog(activity, question) {
config.tempSkipDeleteConfirmation = it
deleteFiles()
}
}
private fun getCurrentPath() = media[selectedPositions.first()].path
private fun deleteFiles() {
if (selectedPositions.isEmpty()) {
return
}
val fileDirItems = ArrayList<FileDirItem>(selectedPositions.size)
val removeMedia = ArrayList<Medium>(selectedPositions.size)
if (media.size <= selectedPositions.first()) {
finishActMode()
return
}
val SAFPath = media[selectedPositions.first()].path
activity.handleSAFDialog(SAFPath) {
selectedPositions.sortedDescending().forEach {
val medium = media[it]
fileDirItems.add(FileDirItem(medium.path, medium.name))
removeMedia.add(medium)
}
media.removeAll(removeMedia)
listener?.tryDeleteFiles(fileDirItems)
removeSelectedItems()
}
}
private fun getSelectedMedia(): List<Medium> {
val selectedMedia = ArrayList<Medium>(selectedPositions.size)
selectedPositions.forEach { selectedMedia.add(media[it]) }
return selectedMedia
}
fun updateMedia(newMedia: ArrayList<Medium>) {
if (newMedia.hashCode() != currentMediaHash) {
currentMediaHash = newMedia.hashCode()
Handler().postDelayed({
media = newMedia.clone() as ArrayList<Medium>
enableInstantLoad()
notifyDataSetChanged()
finishActMode()
fastScroller?.measureRecyclerView()
}, 100L)
}
}
fun updateDisplayFilenames(displayFilenames: Boolean) {
this.displayFilenames = displayFilenames
enableInstantLoad()
notifyDataSetChanged()
}
fun updateAnimateGifs(animateGifs: Boolean) {
this.animateGifs = animateGifs
notifyDataSetChanged()
}
fun updateCropThumbnails(cropThumbnails: Boolean) {
this.cropThumbnails = cropThumbnails
notifyDataSetChanged()
}
fun updateScrollHorizontally(scrollHorizontally: Boolean) {
this.scrollHorizontally = scrollHorizontally
notifyDataSetChanged()
}
private fun enableInstantLoad() {
loadImageInstantly = true
delayHandler.postDelayed({
loadImageInstantly = false
}, INSTANT_LOAD_DURATION)
}
private fun setupView(view: View, medium: Medium) {
view.apply {
play_outline.beVisibleIf(medium.isVideo())
photo_name.beVisibleIf(displayFilenames || isListViewType)
photo_name.text = medium.name
photo_name.tag = medium.path
var thumbnailPath = medium.path
if (hasOTGConnected && thumbnailPath.startsWith(OTG_PATH)) {
thumbnailPath = thumbnailPath.getOTGPublicPath(context)
}
if (loadImageInstantly) {
activity.loadImage(medium.type, thumbnailPath, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails)
} else {
medium_thumbnail.setImageDrawable(null)
medium_thumbnail.isHorizontalScrolling = scrollHorizontally
delayHandler.postDelayed({
val isVisible = visibleItemPaths.contains(medium.path)
if (isVisible) {
activity.loadImage(medium.type, thumbnailPath, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails)
}
}, IMAGE_LOAD_DELAY)
}
if (isListViewType) {
photo_name.setTextColor(textColor)
play_outline.applyColorFilter(textColor)
}
}
}
interface MediaOperationsListener {
fun refreshItems()
fun tryDeleteFiles(fileDirItems: ArrayList<FileDirItem>)
fun selectedPaths(paths: ArrayList<String>)
}
}

View file

@ -1,43 +0,0 @@
package com.simplemobiletools.gallery.asynctasks
import android.content.Context
import android.os.AsyncTask
import com.simplemobiletools.commons.helpers.SORT_BY_DATE_TAKEN
import com.simplemobiletools.commons.models.FileDirItem.Companion.sorting
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.helpers.MediaFetcher
import com.simplemobiletools.gallery.models.Medium
import java.util.*
class GetMediaAsynctask(val context: Context, val mPath: String, val isPickImage: Boolean = false, val isPickVideo: Boolean = false,
val showAll: Boolean, val callback: (media: ArrayList<Medium>) -> Unit) :
AsyncTask<Void, Void, ArrayList<Medium>>() {
private val mediaFetcher = MediaFetcher(context)
override fun doInBackground(vararg params: Void): ArrayList<Medium> {
val getProperDateTaken = sorting and SORT_BY_DATE_TAKEN != 0
return if (showAll) {
val foldersToScan = mediaFetcher.getFoldersToScan()
val media = ArrayList<Medium>()
foldersToScan.forEach {
val newMedia = mediaFetcher.getFilesFrom(it, isPickImage, isPickVideo, getProperDateTaken)
media.addAll(newMedia)
}
MediaFetcher(context).sortMedia(media, context.config.getFileSorting(""))
media
} else {
mediaFetcher.getFilesFrom(mPath, isPickImage, isPickVideo, getProperDateTaken)
}
}
override fun onPostExecute(media: ArrayList<Medium>) {
super.onPostExecute(media)
callback(media)
}
fun stopFetching() {
mediaFetcher.shouldStop = true
cancel(true)
}
}

View file

@ -1,39 +0,0 @@
package com.simplemobiletools.gallery.databases
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.content.Context
import com.simplemobiletools.gallery.interfaces.DirectoryDao
import com.simplemobiletools.gallery.interfaces.MediumDao
import com.simplemobiletools.gallery.models.Directory
import com.simplemobiletools.gallery.models.Medium
@Database(entities = [(Directory::class), (Medium::class)], version = 2)
abstract class GalleryDatabase : RoomDatabase() {
abstract fun DirectoryDao(): DirectoryDao
abstract fun MediumDao(): MediumDao
companion object {
private var db: GalleryDatabase? = null
fun getInstance(context: Context): GalleryDatabase {
if (db == null) {
synchronized(GalleryDatabase::class) {
if (db == null) {
db = Room.databaseBuilder(context.applicationContext, GalleryDatabase::class.java, "gallery.db")
.fallbackToDestructiveMigration()
.build()
}
}
}
return db!!
}
fun destroyInstance() {
db = null
}
}
}

View file

@ -1,98 +0,0 @@
package com.simplemobiletools.gallery.dialogs
import android.support.v7.app.AlertDialog
import android.support.v7.widget.GridLayoutManager
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.beGoneIf
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.views.MyGridLayoutManager
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.adapters.DirectoryAdapter
import com.simplemobiletools.gallery.extensions.addTempFolderIfNeeded
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.extensions.getCachedDirectories
import com.simplemobiletools.gallery.extensions.getSortedDirectories
import com.simplemobiletools.gallery.helpers.VIEW_TYPE_GRID
import com.simplemobiletools.gallery.models.Directory
import kotlinx.android.synthetic.main.dialog_directory_picker.view.*
class PickDirectoryDialog(val activity: BaseSimpleActivity, val sourcePath: String, val callback: (path: String) -> Unit) {
var dialog: AlertDialog
var shownDirectories = ArrayList<Directory>()
var view = activity.layoutInflater.inflate(R.layout.dialog_directory_picker, null)
var isGridViewType = activity.config.viewTypeFolders == VIEW_TYPE_GRID
init {
(view.directories_grid.layoutManager as MyGridLayoutManager).apply {
orientation = if (activity.config.scrollHorizontally && isGridViewType) GridLayoutManager.HORIZONTAL else GridLayoutManager.VERTICAL
spanCount = if (isGridViewType) activity.config.dirColumnCnt else 1
}
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)
}
activity.getCachedDirectories {
if (it.isNotEmpty()) {
activity.runOnUiThread {
gotDirectories(activity.addTempFolderIfNeeded(it))
}
}
}
}
private fun showOtherFolder() {
val showHidden = activity.config.shouldShowHidden
FilePickerDialog(activity, sourcePath, false, showHidden, true) {
callback(it)
}
}
private fun gotDirectories(newDirs: ArrayList<Directory>) {
val dirs = activity.getSortedDirectories(newDirs)
if (dirs.hashCode() == shownDirectories.hashCode())
return
shownDirectories = dirs
val adapter = DirectoryAdapter(activity, dirs, null, view.directories_grid, true) {
if ((it as Directory).path.trimEnd('/') == sourcePath) {
activity.toast(R.string.source_and_destination_same)
return@DirectoryAdapter
} else {
callback(it.path)
dialog.dismiss()
}
}
val scrollHorizontally = activity.config.scrollHorizontally && isGridViewType
val sorting = activity.config.directorySorting
view.apply {
directories_grid.adapter = adapter
directories_vertical_fastscroller.isHorizontal = false
directories_vertical_fastscroller.beGoneIf(scrollHorizontally)
directories_horizontal_fastscroller.isHorizontal = true
directories_horizontal_fastscroller.beVisibleIf(scrollHorizontally)
if (scrollHorizontally) {
directories_horizontal_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble
directories_horizontal_fastscroller.setViews(directories_grid) {
directories_horizontal_fastscroller.updateBubbleText(dirs[it].getBubbleText(sorting))
}
} else {
directories_vertical_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble
directories_vertical_fastscroller.setViews(directories_grid) {
directories_vertical_fastscroller.updateBubbleText(dirs[it].getBubbleText(sorting))
}
}
}
}
}

View file

@ -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.widget.EditText
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.extensions.showKeyboard
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.extensions.value
import com.simplemobiletools.gallery.R
import kotlinx.android.synthetic.main.resize_image.view.*
class ResizeDialog(val activity: BaseSimpleActivity, val size: Point, val callback: (newSize: Point) -> Unit) {
init {
val view = activity.layoutInflater.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 {
activity.setupDialogStuff(view, this, R.string.resize_and_save) {
showKeyboard(view.image_width)
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(newSize)
dismiss()
}
}
}
}
fun getViewValue(view: EditText): Int {
val textValue = view.value
return if (textValue.isEmpty()) 0 else textValue.toInt()
}
}

View file

@ -1,180 +0,0 @@
package com.simplemobiletools.gallery.extensions
import android.app.Activity
import android.content.Intent
import android.provider.MediaStore
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.gallery.BuildConfig
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.activities.SimpleActivity
import com.simplemobiletools.gallery.dialogs.PickDirectoryDialog
import com.simplemobiletools.gallery.helpers.NOMEDIA
import com.simplemobiletools.gallery.models.Medium
import java.io.File
import java.util.*
fun Activity.sharePath(path: String) {
sharePathIntent(path, BuildConfig.APPLICATION_ID)
}
fun Activity.sharePaths(paths: ArrayList<String>) {
sharePathsIntent(paths, BuildConfig.APPLICATION_ID)
}
fun Activity.shareMedium(medium: Medium) {
sharePath(medium.path)
}
fun Activity.shareMedia(media: List<Medium>) {
val paths = media.map { it.path } as ArrayList
sharePaths(paths)
}
fun Activity.setAs(path: String) {
setAsIntent(path, BuildConfig.APPLICATION_ID)
}
fun Activity.openPath(path: String, forceChooser: Boolean) {
openPathIntent(path, forceChooser, BuildConfig.APPLICATION_ID)
}
fun Activity.openEditor(path: String) {
openEditorIntent(path, BuildConfig.APPLICATION_ID)
}
fun Activity.launchCamera() {
val intent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
toast(R.string.no_app_found)
}
}
fun SimpleActivity.launchAbout() {
val faqItems = arrayListOf(
FAQItem(R.string.faq_3_title_commons, R.string.faq_3_text_commons),
FAQItem(R.string.faq_1_title, R.string.faq_1_text),
FAQItem(R.string.faq_2_title, R.string.faq_2_text),
FAQItem(R.string.faq_3_title, R.string.faq_3_text),
FAQItem(R.string.faq_4_title, R.string.faq_4_text),
FAQItem(R.string.faq_5_title, R.string.faq_5_text),
FAQItem(R.string.faq_6_title, R.string.faq_6_text),
FAQItem(R.string.faq_7_title, R.string.faq_7_text),
FAQItem(R.string.faq_8_title, R.string.faq_8_text),
FAQItem(R.string.faq_9_title, R.string.faq_9_text),
FAQItem(R.string.faq_10_title, R.string.faq_10_text),
FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons))
startAboutActivity(R.string.app_name, LICENSE_GLIDE or LICENSE_CROPPER or LICENSE_MULTISELECT or LICENSE_RTL
or LICENSE_SUBSAMPLING or LICENSE_PATTERN or LICENSE_REPRINT or LICENSE_GIF_DRAWABLE or LICENSE_PHOTOVIEW, BuildConfig.VERSION_NAME, faqItems)
}
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 BaseSimpleActivity.addNoMedia(path: String, callback: () -> Unit) {
val file = File(path, NOMEDIA)
if (file.exists()) {
callback()
return
}
if (needsStupidWritePermissions(path)) {
handleSAFDialog(file.absolutePath) {
val fileDocument = getDocumentFile(path)
if (fileDocument?.exists() == true && fileDocument.isDirectory) {
fileDocument.createFile("", NOMEDIA)
applicationContext.scanFileRecursively(file) {
callback()
}
} else {
toast(R.string.unknown_error_occurred)
callback()
}
}
} else {
try {
file.createNewFile()
applicationContext.scanFileRecursively(file) {
callback()
}
} catch (e: Exception) {
showErrorToast(e)
callback()
}
}
}
fun BaseSimpleActivity.removeNoMedia(path: String, callback: (() -> Unit)? = null) {
val file = File(path, NOMEDIA)
if (!file.exists()) {
callback?.invoke()
return
}
tryDeleteFileDirItem(file.toFileDirItem(applicationContext)) {
callback?.invoke()
}
}
fun BaseSimpleActivity.toggleFileVisibility(oldPath: String, hide: Boolean, callback: ((newPath: String) -> Unit)? = null) {
val path = oldPath.getParentPath()
var filename = oldPath.getFilenameFromPath()
filename = if (hide) {
".${filename.trimStart('.')}"
} else {
filename.substring(1, filename.length)
}
val newPath = "$path/$filename"
renameFile(oldPath, newPath) {
callback?.invoke(newPath)
Thread {
updateDBMediaPath(oldPath, newPath)
}.start()
}
}
fun BaseSimpleActivity.tryCopyMoveFilesTo(fileDirItems: ArrayList<FileDirItem>, isCopyOperation: Boolean, callback: (destinationPath: String) -> Unit) {
if (fileDirItems.isEmpty()) {
toast(R.string.unknown_error_occurred)
return
}
val source = fileDirItems[0].getParentPath()
PickDirectoryDialog(this, source) {
copyMoveFilesTo(fileDirItems, source.trimEnd('/'), it, isCopyOperation, true, config.shouldShowHidden, callback)
}
}
fun BaseSimpleActivity.tryDeleteFileDirItem(fileDirItem: FileDirItem, allowDeleteFolder: Boolean = false, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
deleteFile(fileDirItem, allowDeleteFolder) {
callback?.invoke(it)
Thread {
galleryDB.MediumDao().deleteMediumPath(fileDirItem.path)
}.start()
}
}

View file

@ -1,23 +0,0 @@
package com.simplemobiletools.gallery.extensions
import com.simplemobiletools.gallery.helpers.TYPE_GIFS
import com.simplemobiletools.gallery.helpers.TYPE_IMAGES
import com.simplemobiletools.gallery.helpers.TYPE_VIDEOS
import com.simplemobiletools.gallery.models.Medium
fun ArrayList<Medium>.getDirMediaTypes(): Int {
var types = 0
if (any { it.isImage() }) {
types += TYPE_IMAGES
}
if (any { it.isVideo() }) {
types += TYPE_VIDEOS
}
if (any { it.isGif() }) {
types += TYPE_GIFS
}
return types
}

View file

@ -1,366 +0,0 @@
package com.simplemobiletools.gallery.extensions
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.database.Cursor
import android.graphics.Point
import android.media.AudioManager
import android.os.Build
import android.provider.MediaStore
import android.view.WindowManager
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.activities.SettingsActivity
import com.simplemobiletools.gallery.asynctasks.GetMediaAsynctask
import com.simplemobiletools.gallery.databases.GalleryDatabase
import com.simplemobiletools.gallery.helpers.*
import com.simplemobiletools.gallery.interfaces.DirectoryDao
import com.simplemobiletools.gallery.models.Directory
import com.simplemobiletools.gallery.models.Medium
import com.simplemobiletools.gallery.views.MySquareImageView
import pl.droidsonroids.gif.GifDrawable
import java.io.File
val Context.portrait get() = resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
val Context.audioManager get() = getSystemService(Context.AUDIO_SERVICE) as AudioManager
val Context.windowManager: WindowManager get() = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val Context.navigationBarRight: Boolean get() = usableScreenSize.x < realScreenSize.x
val Context.navigationBarBottom: Boolean get() = usableScreenSize.y < realScreenSize.y
val Context.navigationBarHeight: Int get() = if (navigationBarBottom) navigationBarSize.y else 0
val Context.navigationBarWidth: Int get() = if (navigationBarRight) navigationBarSize.x else 0
internal val Context.navigationBarSize: Point
get() = when {
navigationBarRight -> Point(realScreenSize.x - usableScreenSize.x, usableScreenSize.y)
navigationBarBottom -> Point(usableScreenSize.x, realScreenSize.y - usableScreenSize.y)
else -> Point()
}
val Context.usableScreenSize: Point
get() {
val size = Point()
windowManager.defaultDisplay.getSize(size)
return size
}
val Context.realScreenSize: Point
get() {
val size = Point()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
windowManager.defaultDisplay.getRealSize(size)
return size
}
fun Context.getHumanizedFilename(path: String): String {
val humanized = humanizePath(path)
return humanized.substring(humanized.lastIndexOf("/") + 1)
}
fun Context.launchSettings() {
startActivity(Intent(applicationContext, SettingsActivity::class.java))
}
val Context.config: Config get() = Config.newInstance(applicationContext)
val Context.galleryDB: GalleryDatabase get() = GalleryDatabase.getInstance(applicationContext)
fun Context.movePinnedDirectoriesToFront(dirs: ArrayList<Directory>): ArrayList<Directory> {
val foundFolders = ArrayList<Directory>()
val pinnedFolders = config.pinnedFolders
dirs.forEach {
if (pinnedFolders.contains(it.path)) {
foundFolders.add(it)
}
}
dirs.removeAll(foundFolders)
dirs.addAll(0, foundFolders)
if (config.tempFolderPath.isNotEmpty()) {
val newFolder = dirs.firstOrNull { it.path == config.tempFolderPath }
if (newFolder != null) {
dirs.remove(newFolder)
dirs.add(0, newFolder)
}
}
return dirs
}
@Suppress("UNCHECKED_CAST")
fun Context.getSortedDirectories(source: ArrayList<Directory>): ArrayList<Directory> {
val sorting = config.directorySorting
val dirs = source.clone() as ArrayList<Directory>
dirs.sortWith(Comparator { o1, o2 ->
o1 as Directory
o2 as Directory
var result = when {
sorting and SORT_BY_NAME != 0 -> AlphanumericComparator().compare(o1.name.toLowerCase(), o2.name.toLowerCase())
sorting and SORT_BY_PATH != 0 -> AlphanumericComparator().compare(o1.path.toLowerCase(), o2.path.toLowerCase())
sorting and SORT_BY_SIZE != 0 -> o1.size.compareTo(o2.size)
sorting and SORT_BY_DATE_MODIFIED != 0 -> o1.modified.compareTo(o2.modified)
else -> o1.taken.compareTo(o2.taken)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
result
})
return movePinnedDirectoriesToFront(dirs)
}
fun Context.getNoMediaFolders(callback: (folders: ArrayList<String>) -> Unit) {
Thread {
val folders = ArrayList<String>()
val uri = MediaStore.Files.getContentUri("external")
val projection = arrayOf(MediaStore.Files.FileColumns.DATA)
val selection = "${MediaStore.Files.FileColumns.MEDIA_TYPE} = ? AND ${MediaStore.Files.FileColumns.TITLE} LIKE ?"
val selectionArgs = arrayOf(MediaStore.Files.FileColumns.MEDIA_TYPE_NONE.toString(), "%$NOMEDIA%")
val sortOrder = "${MediaStore.Files.FileColumns.DATE_MODIFIED} DESC"
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)
if (cursor?.moveToFirst() == true) {
do {
val path = cursor.getStringValue(MediaStore.Files.FileColumns.DATA) ?: continue
val noMediaFile = File(path)
if (noMediaFile.exists() && noMediaFile.name == NOMEDIA) {
folders.add("${noMediaFile.parent}/")
}
} while (cursor.moveToNext())
}
} finally {
cursor?.close()
}
callback(folders)
}.start()
}
fun Context.rescanFolderMedia(path: String) {
Thread {
rescanFolderMediaSync(path)
}.start()
}
fun Context.rescanFolderMediaSync(path: String) {
getCachedMedia(path) {
val cached = it
GetMediaAsynctask(applicationContext, path, false, false, false) {
Thread {
val newMedia = it
val mediumDao = galleryDB.MediumDao()
mediumDao.insertAll(newMedia)
cached.forEach {
if (!newMedia.contains(it)) {
mediumDao.deleteMediumPath(it.path)
}
}
}.start()
}.execute()
}
}
fun Context.storeDirectoryItems(items: ArrayList<Directory>) {
Thread {
galleryDB.DirectoryDao().insertAll(items)
}.start()
}
fun Context.checkAppendingHidden(path: String, hidden: String, includedFolders: MutableSet<String>): String {
val dirName = when (path) {
internalStoragePath -> getString(R.string.internal)
sdCardPath -> getString(R.string.sd_card)
OTG_PATH -> getString(R.string.otg)
else -> {
if (path.startsWith(OTG_PATH)) {
path.trimEnd('/').substringAfterLast('/')
} else {
path.getFilenameFromPath()
}
}
}
return if (File(path).doesThisOrParentHaveNoMedia() && !path.isThisOrParentIncluded(includedFolders)) {
"$dirName $hidden"
} else {
dirName
}
}
fun Context.loadImage(type: Int, path: String, target: MySquareImageView, horizontalScroll: Boolean, animateGifs: Boolean, cropThumbnails: Boolean) {
target.isHorizontalScrolling = horizontalScroll
if (type == TYPE_IMAGES || type == TYPE_VIDEOS) {
if (type == TYPE_IMAGES && path.isPng()) {
loadPng(path, target, cropThumbnails)
} else {
loadJpg(path, target, cropThumbnails)
}
} else if (type == TYPE_GIFS) {
try {
val gifDrawable = GifDrawable(path)
target.setImageDrawable(gifDrawable)
if (animateGifs) {
gifDrawable.start()
} else {
gifDrawable.stop()
}
target.scaleType = if (cropThumbnails) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.FIT_CENTER
} catch (e: Exception) {
loadJpg(path, target, cropThumbnails)
} catch (e: OutOfMemoryError) {
loadJpg(path, target, cropThumbnails)
}
}
}
fun Context.addTempFolderIfNeeded(dirs: ArrayList<Directory>): ArrayList<Directory> {
val directories = ArrayList<Directory>()
val tempFolderPath = config.tempFolderPath
if (tempFolderPath.isNotEmpty()) {
val newFolder = Directory(null, tempFolderPath, "", tempFolderPath.getFilenameFromPath(), 0, 0, 0, 0L, getPathLocation(tempFolderPath), 0)
directories.add(newFolder)
}
directories.addAll(dirs)
return directories
}
fun Context.getPathLocation(path: String): Int {
return when {
isPathOnSD(path) -> LOCATION_SD
path.startsWith(OTG_PATH) -> LOCATION_OTG
else -> LOCAITON_INTERNAL
}
}
fun Context.loadPng(path: String, target: MySquareImageView, cropThumbnails: Boolean) {
val options = RequestOptions()
.signature(path.getFileSignature())
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.format(DecodeFormat.PREFER_ARGB_8888)
val builder = Glide.with(applicationContext)
.asBitmap()
.load(path)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options).into(target)
}
fun Context.loadJpg(path: String, target: MySquareImageView, cropThumbnails: Boolean) {
val options = RequestOptions()
.signature(path.getFileSignature())
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
val builder = Glide.with(applicationContext)
.load(path)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options).transition(DrawableTransitionOptions.withCrossFade()).into(target)
}
fun Context.getCachedDirectories(getVideosOnly: Boolean = false, getImagesOnly: Boolean = false, callback: (ArrayList<Directory>) -> Unit) {
Thread {
val directoryDao = galleryDB.DirectoryDao()
val directories = directoryDao.getAll() as ArrayList<Directory>
val shouldShowHidden = config.shouldShowHidden
val excludedPaths = config.excludedFolders
val includedPaths = config.includedFolders
var filteredDirectories = directories.filter { it.path.shouldFolderBeVisible(excludedPaths, includedPaths, shouldShowHidden) } as ArrayList<Directory>
val filterMedia = config.filterMedia
filteredDirectories = (when {
getVideosOnly -> filteredDirectories.filter { it.types and TYPE_VIDEOS != 0 }
getImagesOnly -> filteredDirectories.filter { it.types and TYPE_IMAGES != 0 }
else -> filteredDirectories.filter {
(filterMedia and TYPE_IMAGES != 0 && it.types and TYPE_IMAGES != 0) ||
(filterMedia and TYPE_VIDEOS != 0 && it.types and TYPE_VIDEOS != 0) ||
(filterMedia and TYPE_GIFS != 0 && it.types and TYPE_GIFS != 0)
}
}) as ArrayList<Directory>
val hiddenString = resources.getString(R.string.hidden)
filteredDirectories.forEach {
it.name = if (File(it.path).doesThisOrParentHaveNoMedia() && !it.path.isThisOrParentIncluded(includedPaths)) {
"${it.name.removeSuffix(hiddenString).trim()} $hiddenString"
} else {
it.name
}
}
val clone = filteredDirectories.clone() as ArrayList<Directory>
callback(clone.distinctBy { it.path.getDistinctPath() } as ArrayList<Directory>)
removeInvalidDBDirectories(filteredDirectories, directoryDao)
}.start()
}
fun Context.getCachedMedia(path: String, getVideosOnly: Boolean = false, getImagesOnly: Boolean = false, callback: (ArrayList<Medium>) -> Unit) {
Thread {
val mediumDao = galleryDB.MediumDao()
val foldersToScan = if (path == "/") MediaFetcher(this).getFoldersToScan() else arrayListOf(path)
var media = ArrayList<Medium>()
val shouldShowHidden = config.shouldShowHidden
foldersToScan.forEach {
val currMedia = mediumDao.getMediaFromPath(it)
media.addAll(currMedia)
}
if (!shouldShowHidden) {
media = media.filter { !it.path.contains("/.") } as ArrayList<Medium>
}
val filterMedia = config.filterMedia
media = (when {
getVideosOnly -> media.filter { it.type == TYPE_VIDEOS }
getImagesOnly -> media.filter { it.type == TYPE_IMAGES }
else -> media.filter {
(filterMedia and TYPE_IMAGES != 0 && it.type == TYPE_IMAGES) ||
(filterMedia and TYPE_VIDEOS != 0 && it.type == TYPE_VIDEOS) ||
(filterMedia and TYPE_GIFS != 0 && it.type == TYPE_GIFS)
}
}) as ArrayList<Medium>
MediaFetcher(this).sortMedia(media, config.getFileSorting(path))
callback(media.clone() as ArrayList<Medium>)
media.filter { !getDoesFilePathExist(it.path) }.forEach {
mediumDao.deleteMediumPath(it.path)
}
}.start()
}
fun Context.removeInvalidDBDirectories(dirs: ArrayList<Directory>? = null, directoryDao: DirectoryDao = galleryDB.DirectoryDao()) {
val dirsToCheck = dirs ?: directoryDao.getAll()
dirsToCheck.filter { !getDoesFilePathExist(it.path) && it.path != config.tempFolderPath }.forEach {
directoryDao.deleteDirPath(it.path)
}
}
fun Context.updateDBMediaPath(oldPath: String, newPath: String) {
val newFilename = newPath.getFilenameFromPath()
val newParentPath = newPath.getParentPath()
galleryDB.MediumDao().updateMedium(oldPath, newParentPath, newFilename, newPath)
}
fun Context.updateDBDirectory(directory: Directory) {
galleryDB.DirectoryDao().updateDirectory(directory.path, directory.tmb, directory.mediaCnt, directory.modified, directory.taken, directory.size, directory.types)
}
fun Context.getOTGFolderChildren(path: String) = getDocumentFile(path)?.listFiles()
fun Context.getOTGFolderChildrenNames(path: String) = getOTGFolderChildren(path)?.map { it.name }?.toList()

View file

@ -1,20 +0,0 @@
package com.simplemobiletools.gallery.extensions
import com.simplemobiletools.gallery.helpers.NOMEDIA
import java.io.File
fun File.containsNoMedia() = isDirectory && File(this, NOMEDIA).exists()
fun File.doesThisOrParentHaveNoMedia(): Boolean {
var curFile = this
while (true) {
if (curFile.containsNoMedia()) {
return true
}
curFile = curFile.parentFile ?: break
if (curFile.absolutePath == "/") {
break
}
}
return false
}

View file

@ -1,6 +0,0 @@
package com.simplemobiletools.gallery.extensions
import android.os.Environment
import com.simplemobiletools.commons.models.FileDirItem
fun FileDirItem.isDownloadsFolder() = path.equals(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(), true)

View file

@ -1,38 +0,0 @@
package com.simplemobiletools.gallery.extensions
import com.bumptech.glide.signature.ObjectKey
import com.simplemobiletools.commons.helpers.OTG_PATH
import java.io.File
fun String.getFileSignature(): ObjectKey {
val file = File(this)
return ObjectKey("${file.absolutePath}${file.lastModified()}")
}
fun String.isThisOrParentIncluded(includedPaths: MutableSet<String>) = includedPaths.any { startsWith(it, true) }
fun String.isThisOrParentExcluded(excludedPaths: MutableSet<String>) = excludedPaths.any { startsWith(it, true) }
fun String.shouldFolderBeVisible(excludedPaths: MutableSet<String>, includedPaths: MutableSet<String>, showHidden: Boolean): Boolean {
val file = File(this)
return if (isEmpty()) {
false
} else if (!showHidden && file.containsNoMedia()) {
false
} else if (isThisOrParentIncluded(includedPaths)) {
true
} else if (isThisOrParentExcluded(excludedPaths)) {
false
} else if (!showHidden && file.isDirectory && file.canonicalFile == file.absoluteFile) {
var containsNoMediaOrDot = file.containsNoMedia() || contains("/.")
if (!containsNoMediaOrDot) {
containsNoMediaOrDot = file.doesThisOrParentHaveNoMedia()
}
!containsNoMediaOrDot
} else {
true
}
}
// recognize /sdcard/DCIM as the same folder as /storage/emulated/0/DCIM
fun String.getDistinctPath() = if (startsWith(OTG_PATH)) toLowerCase() else File(this).canonicalPath.toLowerCase()

View file

@ -1,433 +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.media.ExifInterface.*
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.OTG_PATH
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.activities.PhotoActivity
import com.simplemobiletools.gallery.activities.ViewPagerActivity
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.GlideRotateTransformation
import com.simplemobiletools.gallery.helpers.MEDIUM
import com.simplemobiletools.gallery.helpers.ROTATE_BY_ASPECT_RATIO
import com.simplemobiletools.gallery.models.Medium
import it.sephiroth.android.library.exif2.ExifInterface
import kotlinx.android.synthetic.main.pager_photo_item.view.*
import pl.droidsonroids.gif.GifDrawable
import java.io.File
import java.io.FileOutputStream
class PhotoFragment : ViewPagerFragment() {
private var DEFAULT_DOUBLE_TAP_ZOOM = 2f
private var isFragmentVisible = false
private var isFullscreen = false
private var wasInit = false
private var useHalfResolution = false
private var imageOrientation = -1
private var gifDrawable: GifDrawable? = null
private var storedShowExtendedDetails = false
private var storedHideExtendedDetails = false
private var storedExtendedDetails = 0
lateinit var view: ViewGroup
lateinit var medium: Medium
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
view = (inflater.inflate(R.layout.pager_photo_item, container, false) as ViewGroup).apply {
subsampling_view.setOnClickListener { photoClicked() }
photo_view.setOnClickListener { photoClicked() }
instant_prev_item.setOnClickListener { listener?.goToPrevItem() }
instant_next_item.setOnClickListener { listener?.goToNextItem() }
instant_prev_item.parentView = container
instant_next_item.parentView = container
photo_brightness_controller.initialize(activity!!, slide_info, true, container) { x, y ->
view.apply {
if (subsampling_view.isVisible()) {
subsampling_view.sendFakeClick(x, y)
} else {
photo_view.sendFakeClick(x, y)
}
}
}
}
storeStateVariables()
if (!isFragmentVisible && activity is PhotoActivity) {
isFragmentVisible = true
}
medium = arguments!!.getSerializable(MEDIUM) as Medium
if (medium.path.startsWith("content://") && !medium.path.startsWith("content://mms/")) {
val originalPath = medium.path
medium.path = context!!.getRealPathFromURI(Uri.parse(originalPath)) ?: 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 {
out?.close()
}
}
}
isFullscreen = activity!!.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == View.SYSTEM_UI_FLAG_FULLSCREEN
loadImage()
checkExtendedDetails()
wasInit = true
return view
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
override fun onResume() {
super.onResume()
if (wasInit && (context!!.config.showExtendedDetails != storedShowExtendedDetails || context!!.config.extendedDetails != storedExtendedDetails)) {
checkExtendedDetails()
}
val allowPhotoGestures = context!!.config.allowPhotoGestures
val allowInstantChange = context!!.config.allowInstantChange
view.apply {
photo_brightness_controller.beVisibleIf(allowPhotoGestures)
instant_prev_item.beVisibleIf(allowInstantChange)
instant_next_item.beVisibleIf(allowInstantChange)
}
storeStateVariables()
}
override fun setMenuVisibility(menuVisible: Boolean) {
super.setMenuVisibility(menuVisible)
isFragmentVisible = menuVisible
if (wasInit) {
if (medium.isGif()) {
gifFragmentVisibilityChanged(menuVisible)
} else {
photoFragmentVisibilityChanged(menuVisible)
}
}
}
private fun storeStateVariables() {
context!!.config.apply {
storedShowExtendedDetails = showExtendedDetails
storedHideExtendedDetails = hideExtendedDetails
storedExtendedDetails = extendedDetails
}
}
private fun gifFragmentVisibilityChanged(isVisible: Boolean) {
if (isVisible) {
gifDrawable?.start()
} else {
gifDrawable?.stop()
}
}
private fun photoFragmentVisibilityChanged(isVisible: Boolean) {
if (isVisible) {
addZoomableView()
}
}
private fun degreesForRotation(orientation: Int) = when (orientation) {
ORIENTATION_ROTATE_270 -> 270
ORIENTATION_ROTATE_180 -> 180
ORIENTATION_ROTATE_90 -> 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() {
imageOrientation = getImageOrientation()
if (medium.isGif()) {
loadGif()
} else {
loadBitmap()
}
}
private fun loadGif() {
try {
val pathToLoad = getPathToLoad(medium)
gifDrawable = if (pathToLoad.startsWith("content://") || pathToLoad.startsWith("file://")) {
GifDrawable(context!!.contentResolver, Uri.parse(pathToLoad))
} else {
GifDrawable(pathToLoad)
}
if (!isFragmentVisible) {
gifDrawable!!.stop()
}
view.photo_view.setImageDrawable(gifDrawable)
} catch (e: Exception) {
gifDrawable = null
loadBitmap()
} catch (e: OutOfMemoryError) {
gifDrawable = null
loadBitmap()
}
}
private fun loadBitmap(degrees: Int = 0) {
if (degrees == 0) {
var targetWidth = if (ViewPagerActivity.screenWidth == 0) Target.SIZE_ORIGINAL else ViewPagerActivity.screenWidth
var targetHeight = if (ViewPagerActivity.screenHeight == 0) Target.SIZE_ORIGINAL else ViewPagerActivity.screenHeight
if (useHalfResolution) {
targetWidth /= 2
targetHeight /= 2
}
if (imageOrientation == ORIENTATION_ROTATE_90) {
targetWidth = targetHeight
targetHeight = Target.SIZE_ORIGINAL
}
val options = RequestOptions()
.signature(medium.path.getFileSignature())
.format(DecodeFormat.PREFER_ARGB_8888)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.override(targetWidth, targetHeight)
Glide.with(this)
.asBitmap()
.load(getPathToLoad(medium))
.apply(options)
.listener(object : RequestListener<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
if (!useHalfResolution && e?.rootCauses?.firstOrNull() is OutOfMemoryError) {
useHalfResolution = true
Handler().post {
if (activity?.isActivityDestroyed() == false) {
loadBitmap(degrees)
}
}
}
return false
}
override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
if (isFragmentVisible)
addZoomableView()
return false
}
}).into(view.photo_view)
} else {
val options = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.transform(GlideRotateTransformation(degrees))
Glide.with(this)
.asBitmap()
.load(getPathToLoad(medium))
.thumbnail(0.2f)
.apply(options)
.into(view.photo_view)
}
}
private fun addZoomableView() {
if (!context!!.config.replaceZoomableImages && medium.isImage() && isFragmentVisible && view.subsampling_view.isGone() && !medium.isDng()) {
ViewPagerActivity.wasDecodedByGlide = false
view.subsampling_view.apply {
maxScale = 10f
beVisible()
isQuickScaleEnabled = context.config.oneFingerZoom
setResetScaleOnSizeChange(context.config.screenRotation != ROTATE_BY_ASPECT_RATIO)
setImage(ImageSource.uri(getPathToLoad(medium)))
orientation = if (imageOrientation == -1) SubsamplingScaleImageView.ORIENTATION_USE_EXIF else degreesForRotation(imageOrientation)
setEagerLoadingEnabled(false)
setExecutor(AsyncTask.SERIAL_EXECUTOR)
setOnImageEventListener(object : SubsamplingScaleImageView.OnImageEventListener {
override fun onImageLoaded() {
}
override fun onReady() {
background = ColorDrawable(if (context.config.blackBackground) Color.BLACK else context.config.backgroundColor)
val useWidth = if (imageOrientation == ORIENTATION_ROTATE_90 || imageOrientation == ORIENTATION_ROTATE_270) sHeight else sWidth
val useHeight = if (imageOrientation == ORIENTATION_ROTATE_90 || imageOrientation == ORIENTATION_ROTATE_270) sWidth else sHeight
setDoubleTapZoomScale(getDoubleTapZoomScale(useWidth, useHeight))
}
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 getImageOrientation(): Int {
val defaultOrientation = -1
var orient = defaultOrientation
try {
val pathToLoad = getPathToLoad(medium)
val exif = android.media.ExifInterface(pathToLoad)
orient = exif.getAttributeInt(android.media.ExifInterface.TAG_ORIENTATION, defaultOrientation)
if (orient == defaultOrientation || medium.path.startsWith(OTG_PATH)) {
val uri = if (pathToLoad.startsWith("content:/")) Uri.parse(pathToLoad) else Uri.fromFile(File(pathToLoad))
val inputStream = context!!.contentResolver.openInputStream(uri)
val exif2 = ExifInterface()
exif2.readExif(inputStream, ExifInterface.Options.OPTION_ALL)
orient = exif2.getTag(ExifInterface.TAG_ORIENTATION)?.getValueAsInt(defaultOrientation) ?: defaultOrientation
}
} catch (ignored: Exception) {
}
return orient
}
private fun getDoubleTapZoomScale(width: Int, height: Int): Float {
val bitmapAspectRatio = height / width.toFloat()
val screenAspectRatio = ViewPagerActivity.screenHeight / ViewPagerActivity.screenWidth.toFloat()
return if (context == null || bitmapAspectRatio == screenAspectRatio) {
DEFAULT_DOUBLE_TAP_ZOOM
} else if (ViewPagerActivity.wasDecodedByGlide) {
1f
} else if (context!!.portrait && bitmapAspectRatio <= screenAspectRatio) {
ViewPagerActivity.screenHeight / height.toFloat()
} else if (context!!.portrait && bitmapAspectRatio > screenAspectRatio) {
ViewPagerActivity.screenWidth / width.toFloat()
} else if (!context!!.portrait && bitmapAspectRatio >= screenAspectRatio) {
ViewPagerActivity.screenWidth / width.toFloat()
} else if (!context!!.portrait && bitmapAspectRatio < screenAspectRatio) {
ViewPagerActivity.screenHeight / height.toFloat()
} else {
DEFAULT_DOUBLE_TAP_ZOOM
}
}
fun rotateImageViewBy(degrees: Int) {
view.subsampling_view.beGone()
loadBitmap(degrees)
}
private fun checkExtendedDetails() {
if (context!!.config.showExtendedDetails) {
view.photo_details.apply {
text = getMediumExtendedDetails(medium)
setTextColor(context.config.textColor)
beVisibleIf(text.isNotEmpty())
alpha = if (!context!!.config.hideExtendedDetails || !isFullscreen) 1f else 0f
onGlobalLayout {
if (height != 0 && isAdded) {
y = getExtendedDetailsY(height)
}
}
}
} else {
view.photo_details.beGone()
}
}
override fun onDestroyView() {
super.onDestroyView()
if (activity?.isActivityDestroyed() == false) {
Glide.with(context!!).clear(view.photo_view)
view.subsampling_view.recycle()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
loadImage()
checkExtendedDetails()
}
private fun photoClicked() {
listener?.fragmentClicked()
}
override fun fullscreenToggled(isFullscreen: Boolean) {
this.isFullscreen = isFullscreen
view.photo_details.apply {
if (storedShowExtendedDetails) {
animate().y(getExtendedDetailsY(height))
if (storedHideExtendedDetails) {
animate().alpha(if (isFullscreen) 0f else 1f).start()
}
}
}
}
private fun getExtendedDetailsY(height: Int): Float {
val smallMargin = resources.getDimension(R.dimen.small_margin)
val fullscreenOffset = context!!.navigationBarHeight.toFloat() - smallMargin
return context!!.usableScreenSize.y - height + if (isFullscreen) fullscreenOffset else -(if (context!!.navigationBarHeight == 0) smallMargin else 0f)
}
}

View file

@ -1,541 +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.support.annotation.RequiresApi
import android.util.DisplayMetrics
import android.view.*
import android.view.animation.AnimationUtils
import android.widget.SeekBar
import android.widget.TextView
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isJellyBean1Plus
import com.simplemobiletools.gallery.BuildConfig
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.activities.VideoActivity
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.MEDIUM
import com.simplemobiletools.gallery.helpers.MediaSideScroll
import com.simplemobiletools.gallery.models.Medium
import kotlinx.android.synthetic.main.pager_video_item.view.*
import java.io.File
import java.io.IOException
class VideoFragment : ViewPagerFragment(), SurfaceHolder.Callback, SeekBar.OnSeekBarChangeListener {
private val PROGRESS = "progress"
private val MIN_SKIP_LENGTH = 2000
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 mView: View? = null
private var mIsPlaying = false
private var mIsDragged = false
private var mIsFullscreen = false
private var mIsFragmentVisible = false
private var mPlayOnPrepare = false
private var wasEncoded = false
private var wasInit = false
private var isPrepared = false
private var mCurrTime = 0
private var mDuration = 0
private var mEncodedPath = ""
private var mStoredShowExtendedDetails = false
private var mStoredHideExtendedDetails = false
private var mStoredExtendedDetails = 0
private lateinit var brightnessSideScroll: MediaSideScroll
private lateinit var volumeSideScroll: MediaSideScroll
lateinit var medium: Medium
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mView = inflater.inflate(R.layout.pager_video_item, container, false).apply {
instant_prev_item.setOnClickListener { listener?.goToPrevItem() }
instant_next_item.setOnClickListener { listener?.goToNextItem() }
mTimeHolder = video_time_holder
}
storeStateVariables()
medium = arguments!!.getSerializable(MEDIUM) as Medium
// setMenuVisibility is not called at VideoActivity (third party intent)
if (!mIsFragmentVisible && activity is VideoActivity) {
mIsFragmentVisible = true
}
mIsFullscreen = activity!!.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == View.SYSTEM_UI_FLAG_FULLSCREEN
setupPlayer()
if (savedInstanceState != null) {
mCurrTime = savedInstanceState.getInt(PROGRESS)
}
checkFullscreen()
wasInit = true
mView!!.apply {
brightnessSideScroll = video_brightness_controller
brightnessSideScroll.initialize(activity!!, slide_info, true, container) { x, y ->
video_holder.performClick()
}
volumeSideScroll = video_volume_controller
volumeSideScroll.initialize(activity!!, slide_info, false, container) { x, y ->
video_holder.performClick()
}
video_curr_time.setOnClickListener { skip(false) }
video_duration.setOnClickListener { skip(true) }
}
return mView
}
override fun onResume() {
super.onResume()
activity!!.updateTextColors(mView!!.video_holder)
val allowVideoGestures = context!!.config.allowVideoGestures
val allowInstantChange = context!!.config.allowInstantChange
mView!!.apply {
video_volume_controller.beVisibleIf(allowVideoGestures)
video_brightness_controller.beVisibleIf(allowVideoGestures)
instant_prev_item.beVisibleIf(allowInstantChange)
instant_next_item.beVisibleIf(allowInstantChange)
}
if (context!!.config.showExtendedDetails != mStoredShowExtendedDetails || context!!.config.extendedDetails != mStoredExtendedDetails) {
checkExtendedDetails()
}
storeStateVariables()
}
override fun onPause() {
super.onPause()
pauseVideo()
storeStateVariables()
}
override fun onDestroy() {
super.onDestroy()
if (activity?.isChangingConfigurations == false) {
cleanup()
}
}
private fun storeStateVariables() {
context!!.config.apply {
mStoredShowExtendedDetails = showExtendedDetails
mStoredHideExtendedDetails = hideExtendedDetails
mStoredExtendedDetails = extendedDetails
}
}
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()
checkExtendedDetails()
initMediaPlayer()
}
override fun setMenuVisibility(menuVisible: Boolean) {
super.setMenuVisibility(menuVisible)
if (mIsFragmentVisible && !menuVisible) {
pauseVideo()
releaseMediaPlayer()
}
mIsFragmentVisible = menuVisible
if (menuVisible && wasInit) {
initMediaPlayer()
if (context?.config?.autoplayVideos == true) {
playVideo()
}
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
setVideoSize()
initTimeHolder()
checkExtendedDetails()
}
private fun toggleFullscreen() {
listener?.fragmentClicked()
}
private fun initTimeHolder() {
val res = resources
val left = 0
val top = 0
var right = 0
var bottom = 0
if (hasNavBar()) {
if (res.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
bottom += context!!.navigationBarHeight
} else {
right += context!!.navigationBarWidth
bottom += context!!.navigationBarHeight
}
mTimeHolder!!.setPadding(left, top, right, bottom)
}
mCurrTimeView = mView!!.video_curr_time
mSeekBar = mView!!.video_seekbar
mSeekBar!!.setOnSeekBarChangeListener(this)
if (mIsFullscreen) {
mTimeHolder!!.beInvisible()
}
}
private fun hasNavBar(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
val display = context!!.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(context).hasPermanentMenuKey()
val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
!hasMenuKey && !hasBackKey
}
}
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
initMediaPlayer()
mIsPlaying = !mIsPlaying
if (mIsPlaying) {
playVideo()
} else {
pauseVideo()
}
}
fun playVideo() {
if (mMediaPlayer != null && isPrepared) {
mIsPlaying = true
mMediaPlayer?.start()
} else {
mPlayOnPrepare = true
}
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 || !mIsFragmentVisible) {
return
}
val mediumPath = if (wasEncoded) mEncodedPath else getPathToLoad(medium)
// this workaround is needed for example if the filename contains a colon
val fileUri = if (mediumPath.startsWith("/")) context!!.getFilePublicUri(File(mediumPath), BuildConfig.APPLICATION_ID) else Uri.parse(mediumPath)
try {
mMediaPlayer = MediaPlayer().apply {
setDataSource(context, fileUri)
setDisplay(mSurfaceHolder)
setOnCompletionListener { videoCompleted() }
setOnVideoSizeChangedListener { mediaPlayer, width, height -> setVideoSize() }
setOnPreparedListener { videoPrepared(it) }
setAudioStreamType(AudioManager.STREAM_MUSIC)
prepare()
}
} catch (e: IOException) {
mEncodedPath = Uri.encode(getPathToLoad(medium))
if (wasEncoded) {
releaseMediaPlayer()
} else {
wasEncoded = true
mMediaPlayer = null
initMediaPlayer()
}
} catch (e: Exception) {
releaseMediaPlayer()
}
}
private fun setProgress(seconds: Int) {
mMediaPlayer!!.seekTo(seconds * 1000)
mSeekBar!!.progress = seconds
mCurrTimeView!!.text = seconds.getFormattedDuration()
}
private fun addPreviewImage() {
mMediaPlayer!!.start()
mMediaPlayer!!.pause()
}
private fun cleanup() {
pauseVideo()
mCurrTimeView?.text = 0.getFormattedDuration()
releaseMediaPlayer()
mSeekBar?.progress = 0
mTimerHandler?.removeCallbacksAndMessages(null)
mSurfaceView = null
mSurfaceHolder?.removeCallback(this)
mSurfaceHolder = null
}
private fun releaseMediaPlayer() {
mMediaPlayer?.setSurface(null)
mMediaPlayer?.release()
mMediaPlayer = null
}
private fun videoPrepared(mediaPlayer: MediaPlayer) {
isPrepared = true
mDuration = mediaPlayer.duration / 1000
addPreviewImage()
setupTimeHolder()
setProgress(mCurrTime)
if (mIsFragmentVisible && (context!!.config.autoplayVideos || mPlayOnPrepare)) {
playVideo()
}
}
private fun videoCompleted() {
if (!isAdded) {
return
}
if (listener?.videoEnded() == false && context!!.config.loopVideos) {
playVideo()
} else {
mSeekBar!!.progress = mSeekBar!!.max
mCurrTimeView!!.text = mDuration.getFormattedDuration()
pauseVideo()
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
mSurfaceHolder = holder
if (mIsFragmentVisible) {
initMediaPlayer()
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
if (width != 0 && height != 0 && mSurfaceView != null) {
setVideoSize()
}
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
releaseMediaPlayer()
}
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private fun setVideoSize() {
if (mSurfaceHolder == null)
mSurfaceHolder = mSurfaceView!!.holder
if (activity == null || mSurfaceHolder == null || !mSurfaceHolder!!.surface.isValid)
return
initMediaPlayer()
if (mMediaPlayer == null) {
return
}
val videoProportion = mMediaPlayer!!.videoWidth.toFloat() / mMediaPlayer!!.videoHeight.toFloat()
val display = activity!!.windowManager.defaultDisplay
val screenWidth: Int
val screenHeight: Int
if (isJellyBean1Plus()) {
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
}
}
private fun checkExtendedDetails() {
if (context!!.config.showExtendedDetails) {
mView!!.video_details.apply {
text = getMediumExtendedDetails(medium)
setTextColor(context.config.textColor)
beVisibleIf(text.isNotEmpty())
alpha = if (!context!!.config.hideExtendedDetails || !mIsFullscreen) 1f else 0f
onGlobalLayout {
if (height != 0 && isAdded) {
y = getExtendedDetailsY(height)
}
}
}
} else {
mView!!.video_details.beGone()
}
}
private fun skip(forward: Boolean) {
if (mMediaPlayer == null) {
return
}
val curr = mMediaPlayer!!.currentPosition
val twoPercents = Math.max(mMediaPlayer!!.duration / 50, MIN_SKIP_LENGTH)
val newProgress = if (forward) curr + twoPercents else curr - twoPercents
val roundProgress = Math.round(newProgress / 1000f)
val limitedProgress = Math.max(Math.min(mMediaPlayer!!.duration / 1000, roundProgress), 0)
setProgress(limitedProgress)
if (!mIsPlaying) {
togglePlayPause()
}
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (mMediaPlayer != null && fromUser) {
setProgress(progress)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
initMediaPlayer()
if (mMediaPlayer == null)
return
mMediaPlayer!!.pause()
mIsDragged = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
if (!mIsPlaying) {
togglePlayPause()
} else {
mMediaPlayer?.start()
}
mIsDragged = false
}
override fun fullscreenToggled(isFullscreen: Boolean) {
mIsFullscreen = isFullscreen
checkFullscreen()
mView!!.video_details.apply {
if (mStoredShowExtendedDetails) {
animate().y(getExtendedDetailsY(height))
if (mStoredHideExtendedDetails) {
animate().alpha(if (isFullscreen) 0f else 1f).start()
}
}
}
}
private fun getExtendedDetailsY(height: Int): Float {
val smallMargin = resources.getDimension(R.dimen.small_margin)
val timeHolderHeight = mTimeHolder!!.height - context!!.navigationBarHeight.toFloat()
val fullscreenOffset = context!!.navigationBarHeight.toFloat() - smallMargin
return context!!.usableScreenSize.y - height + if (mIsFullscreen) fullscreenOffset else -(timeHolderHeight + if (context!!.navigationBarHeight == 0) smallMargin else 0f)
}
}

View file

@ -1,71 +0,0 @@
package com.simplemobiletools.gallery.fragments
import android.support.v4.app.Fragment
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.OTG_PATH
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.helpers.*
import com.simplemobiletools.gallery.models.Medium
import java.io.File
abstract class ViewPagerFragment : Fragment() {
var listener: FragmentListener? = null
abstract fun fullscreenToggled(isFullscreen: Boolean)
interface FragmentListener {
fun fragmentClicked()
fun videoEnded(): Boolean
fun goToPrevItem()
fun goToNextItem()
}
fun getMediumExtendedDetails(medium: Medium): String {
val file = File(medium.path)
if (!file.exists()) {
return ""
}
val path = "${file.parent.trimEnd('/')}/"
val exif = android.media.ExifInterface(medium.path)
val details = StringBuilder()
val detailsFlag = context!!.config.extendedDetails
if (detailsFlag and EXT_NAME != 0) {
medium.name.let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_PATH != 0) {
path.let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_SIZE != 0) {
file.length().formatSize().let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_RESOLUTION != 0) {
file.absolutePath.getResolution()?.formatAsResolution().let { if (it?.isNotEmpty() == true) details.appendln(it) }
}
if (detailsFlag and EXT_LAST_MODIFIED != 0) {
file.lastModified().formatDate().let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_DATE_TAKEN != 0) {
path.getExifDateTaken(exif).let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_CAMERA_MODEL != 0) {
path.getExifCameraModel(exif).let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_EXIF_PROPERTIES != 0) {
path.getExifProperties(exif).let { if (it.isNotEmpty()) details.appendln(it) }
}
return details.toString().trim()
}
fun getPathToLoad(medium: Medium) = if (medium.path.startsWith(OTG_PATH)) medium.path.getOTGPublicPath(context!!) else medium.path
}

View file

@ -1,325 +0,0 @@
package com.simplemobiletools.gallery.helpers
import android.content.Context
import android.content.res.Configuration
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 directorySorting: Int
get(): Int = 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()) {
sorting = value
} else {
prefs.edit().putInt(SORT_FOLDER_PREFIX + path.toLowerCase(), value).apply()
}
}
fun getFileSorting(path: String) = prefs.getInt(SORT_FOLDER_PREFIX + path.toLowerCase(), sorting)
fun removeFileSorting(path: String) {
prefs.edit().remove(SORT_FOLDER_PREFIX + path.toLowerCase()).apply()
}
fun hasCustomSorting(path: String) = prefs.contains(SORT_FOLDER_PREFIX + path.toLowerCase())
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 isThirdPartyIntent: Boolean
get() = prefs.getBoolean(IS_THIRD_PARTY_INTENT, false)
set(isThirdPartyIntent) = prefs.edit().putBoolean(IS_THIRD_PARTY_INTENT, isThirdPartyIntent).apply()
var pinnedFolders: Set<String>
get() = prefs.getStringSet(PINNED_FOLDERS, HashSet<String>())
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<String>) {
val currPinnedFolders = HashSet<String>(pinnedFolders)
currPinnedFolders.addAll(paths)
pinnedFolders = currPinnedFolders
}
fun removePinnedFolders(paths: Set<String>) {
val currPinnedFolders = HashSet<String>(pinnedFolders)
currPinnedFolders.removeAll(paths)
pinnedFolders = currPinnedFolders
}
fun addExcludedFolder(path: String) {
addExcludedFolders(HashSet<String>(Arrays.asList(path)))
}
fun addExcludedFolders(paths: Set<String>) {
val currExcludedFolders = HashSet<String>(excludedFolders)
currExcludedFolders.addAll(paths)
excludedFolders = currExcludedFolders
}
fun removeExcludedFolder(path: String) {
val currExcludedFolders = HashSet<String>(excludedFolders)
currExcludedFolders.remove(path)
excludedFolders = currExcludedFolders
}
var excludedFolders: MutableSet<String>
get() = prefs.getStringSet(EXCLUDED_FOLDERS, getDataFolder())
set(excludedFolders) = prefs.edit().remove(EXCLUDED_FOLDERS).putStringSet(EXCLUDED_FOLDERS, excludedFolders).apply()
private fun getDataFolder(): Set<String> {
val folders = HashSet<String>()
val dataFolder = context.externalCacheDir?.parentFile?.parent?.trimEnd('/') ?: ""
if (dataFolder.endsWith("data"))
folders.add(dataFolder)
return folders
}
fun addIncludedFolder(path: String) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.add(path)
includedFolders = currIncludedFolders
}
fun removeIncludedFolder(path: String) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.remove(path)
includedFolders = currIncludedFolders
}
var includedFolders: MutableSet<String>
get() = prefs.getStringSet(INCLUDED_FOLDERS, HashSet<String>())
set(includedFolders) = prefs.edit().remove(INCLUDED_FOLDERS).putStringSet(INCLUDED_FOLDERS, includedFolders).apply()
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 blackBackground: Boolean
get() = prefs.getBoolean(DARK_BACKGROUND, false)
set(darkBackground) = prefs.edit().putBoolean(DARK_BACKGROUND, darkBackground).apply()
var filterMedia: Int
get() = prefs.getInt(FILTER_MEDIA, TYPE_IMAGES or TYPE_VIDEOS or TYPE_GIFS)
set(filterMedia) = prefs.edit().putInt(FILTER_MEDIA, filterMedia).apply()
var dirColumnCnt: Int
get() = prefs.getInt(getDirectoryColumnsField(), getDefaultDirectoryColumnCount())
set(dirColumnCnt) = prefs.edit().putInt(getDirectoryColumnsField(), dirColumnCnt).apply()
var oneFingerZoom: Boolean
get() = prefs.getBoolean(ONE_FINGER_ZOOM, false)
set(oneFingerZoom) = prefs.edit().putBoolean(ONE_FINGER_ZOOM, oneFingerZoom).apply()
var allowInstantChange: Boolean
get() = prefs.getBoolean(ALLOW_INSTANT_CHANGE, false)
set(allowInstantChange) = prefs.edit().putBoolean(ALLOW_INSTANT_CHANGE, allowInstantChange).apply()
var replaceZoomableImages: Boolean
get() = prefs.getBoolean(REPLACE_ZOOMABLE_IMAGES, false)
set(replaceZoomableImages) = prefs.edit().putBoolean(REPLACE_ZOOMABLE_IMAGES, replaceZoomableImages).apply()
private fun getDirectoryColumnsField(): String {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
if (scrollHorizontally) {
DIR_HORIZONTAL_COLUMN_CNT
} else {
DIR_COLUMN_CNT
}
} else {
if (scrollHorizontally) {
DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT
} else {
DIR_LANDSCAPE_COLUMN_CNT
}
}
}
private fun getDefaultDirectoryColumnCount() = context.resources.getInteger(if (scrollHorizontally) R.integer.directory_columns_horizontal_scroll
else R.integer.directory_columns_vertical_scroll)
var mediaColumnCnt: Int
get() = prefs.getInt(getMediaColumnsField(), getDefaultMediaColumnCount())
set(mediaColumnCnt) = prefs.edit().putInt(getMediaColumnsField(), mediaColumnCnt).apply()
private fun getMediaColumnsField(): String {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
if (scrollHorizontally) {
MEDIA_HORIZONTAL_COLUMN_CNT
} else {
MEDIA_COLUMN_CNT
}
} else {
if (scrollHorizontally) {
MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT
} else {
MEDIA_LANDSCAPE_COLUMN_CNT
}
}
}
private fun getDefaultMediaColumnCount() = context.resources.getInteger(if (scrollHorizontally) R.integer.media_columns_horizontal_scroll
else R.integer.media_columns_vertical_scroll)
var albumCovers: String
get() = prefs.getString(ALBUM_COVERS, "")
set(albumCovers) = prefs.edit().putString(ALBUM_COVERS, albumCovers).apply()
fun parseAlbumCovers(): ArrayList<AlbumCover> {
val listType = object : TypeToken<List<AlbumCover>>() {}.type
return Gson().fromJson<ArrayList<AlbumCover>>(albumCovers, listType) ?: ArrayList(1)
}
var hideSystemUI: Boolean
get() = prefs.getBoolean(HIDE_SYSTEM_UI, false)
set(hideSystemUI) = prefs.edit().putBoolean(HIDE_SYSTEM_UI, hideSystemUI).apply()
var replaceShare: Boolean
get() = prefs.getBoolean(REPLACE_SHARE_WITH_ROTATE, false)
set(replaceShare) = prefs.edit().putBoolean(REPLACE_SHARE_WITH_ROTATE, replaceShare).apply()
var deleteEmptyFolders: Boolean
get() = prefs.getBoolean(DELETE_EMPTY_FOLDERS, false)
set(deleteEmptyFolders) = prefs.edit().putBoolean(DELETE_EMPTY_FOLDERS, deleteEmptyFolders).apply()
var allowPhotoGestures: Boolean
get() = prefs.getBoolean(ALLOW_PHOTO_GESTURES, false)
set(allowPhotoGestures) = prefs.edit().putBoolean(ALLOW_PHOTO_GESTURES, allowPhotoGestures).apply()
var allowVideoGestures: Boolean
get() = prefs.getBoolean(ALLOW_VIDEO_GESTURES, true)
set(allowVideoGestures) = prefs.edit().putBoolean(ALLOW_VIDEO_GESTURES, allowVideoGestures).apply()
var showMediaCount: Boolean
get() = prefs.getBoolean(SHOW_MEDIA_COUNT, true)
set(showMediaCount) = prefs.edit().putBoolean(SHOW_MEDIA_COUNT, showMediaCount).apply()
var slideshowInterval: Int
get() = prefs.getInt(SLIDESHOW_INTERVAL, SLIDESHOW_DEFAULT_INTERVAL)
set(slideshowInterval) = prefs.edit().putInt(SLIDESHOW_INTERVAL, slideshowInterval).apply()
var slideshowIncludePhotos: Boolean
get() = prefs.getBoolean(SLIDESHOW_INCLUDE_PHOTOS, true)
set(slideshowIncludePhotos) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_PHOTOS, slideshowIncludePhotos).apply()
var slideshowIncludeVideos: Boolean
get() = prefs.getBoolean(SLIDESHOW_INCLUDE_VIDEOS, false)
set(slideshowIncludeVideos) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_VIDEOS, slideshowIncludeVideos).apply()
var slideshowIncludeGIFs: Boolean
get() = prefs.getBoolean(SLIDESHOW_INCLUDE_GIFS, false)
set(slideshowIncludeGIFs) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_GIFS, slideshowIncludeGIFs).apply()
var slideshowRandomOrder: Boolean
get() = prefs.getBoolean(SLIDESHOW_RANDOM_ORDER, false)
set(slideshowRandomOrder) = prefs.edit().putBoolean(SLIDESHOW_RANDOM_ORDER, slideshowRandomOrder).apply()
var slideshowUseFade: Boolean
get() = prefs.getBoolean(SLIDESHOW_USE_FADE, false)
set(slideshowUseFade) = prefs.edit().putBoolean(SLIDESHOW_USE_FADE, slideshowUseFade).apply()
var slideshowMoveBackwards: Boolean
get() = prefs.getBoolean(SLIDESHOW_MOVE_BACKWARDS, false)
set(slideshowMoveBackwards) = prefs.edit().putBoolean(SLIDESHOW_MOVE_BACKWARDS, slideshowMoveBackwards).apply()
var loopSlideshow: Boolean
get() = prefs.getBoolean(SLIDESHOW_LOOP, false)
set(loopSlideshow) = prefs.edit().putBoolean(SLIDESHOW_LOOP, loopSlideshow).apply()
var tempFolderPath: String
get() = prefs.getString(TEMP_FOLDER_PATH, "")
set(tempFolderPath) = prefs.edit().putString(TEMP_FOLDER_PATH, tempFolderPath).apply()
var viewTypeFolders: Int
get() = prefs.getInt(VIEW_TYPE_FOLDERS, VIEW_TYPE_GRID)
set(viewTypeFolders) = prefs.edit().putInt(VIEW_TYPE_FOLDERS, viewTypeFolders).apply()
var viewTypeFiles: Int
get() = prefs.getInt(VIEW_TYPE_FILES, VIEW_TYPE_GRID)
set(viewTypeFiles) = prefs.edit().putInt(VIEW_TYPE_FILES, viewTypeFiles).apply()
var showExtendedDetails: Boolean
get() = prefs.getBoolean(SHOW_EXTENDED_DETAILS, false)
set(showExtendedDetails) = prefs.edit().putBoolean(SHOW_EXTENDED_DETAILS, showExtendedDetails).apply()
var hideExtendedDetails: Boolean
get() = prefs.getBoolean(HIDE_EXTENDED_DETAILS, false)
set(hideExtendedDetails) = prefs.edit().putBoolean(HIDE_EXTENDED_DETAILS, hideExtendedDetails).apply()
var extendedDetails: Int
get() = prefs.getInt(EXTENDED_DETAILS, EXT_RESOLUTION or EXT_LAST_MODIFIED or EXT_EXIF_PROPERTIES)
set(extendedDetails) = prefs.edit().putInt(EXTENDED_DETAILS, extendedDetails).apply()
var doExtraCheck: Boolean
get() = prefs.getBoolean(DO_EXTRA_CHECK, false)
set(doExtraCheck) = prefs.edit().putBoolean(DO_EXTRA_CHECK, doExtraCheck).apply()
var wasNewAppShown: Boolean
get() = prefs.getBoolean(WAS_NEW_APP_SHOWN, false)
set(wasNewAppShown) = prefs.edit().putBoolean(WAS_NEW_APP_SHOWN, wasNewAppShown).apply()
var lastFilepickerPath: String
get() = prefs.getString(LAST_FILEPICKER_PATH, "")
set(lastFilepickerPath) = prefs.edit().putString(LAST_FILEPICKER_PATH, lastFilepickerPath).apply()
var wasOTGHandled: Boolean
get() = prefs.getBoolean(WAS_OTG_HANDLED, false)
set(wasOTGHandled) = prefs.edit().putBoolean(WAS_OTG_HANDLED, wasOTGHandled).apply()
var tempSkipDeleteConfirmation: Boolean
get() = prefs.getBoolean(TEMP_SKIP_DELETE_CONFIRMATION, false)
set(tempSkipDeleteConfirmation) = prefs.edit().putBoolean(TEMP_SKIP_DELETE_CONFIRMATION, tempSkipDeleteConfirmation).apply()
}

View file

@ -1,110 +0,0 @@
package com.simplemobiletools.gallery.helpers
// shared preferences
const val DIRECTORY_SORT_ORDER = "directory_sort_order"
const val SORT_FOLDER_PREFIX = "sort_folder_"
const val SHOW_HIDDEN_MEDIA = "show_hidden_media"
const val TEMPORARILY_SHOW_HIDDEN = "temporarily_show_hidden"
const val IS_THIRD_PARTY_INTENT = "is_third_party_intent"
const val AUTOPLAY_VIDEOS = "autoplay_videos"
const val LOOP_VIDEOS = "loop_videos"
const val ANIMATE_GIFS = "animate_gifs"
const val MAX_BRIGHTNESS = "max_brightness"
const val CROP_THUMBNAILS = "crop_thumbnails"
const val SCREEN_ROTATION = "screen_rotation"
const val DISPLAY_FILE_NAMES = "display_file_names"
const val DARK_BACKGROUND = "dark_background"
const val PINNED_FOLDERS = "pinned_folders"
const val FILTER_MEDIA = "filter_media"
const val DIR_COLUMN_CNT = "dir_column_cnt"
const val DIR_LANDSCAPE_COLUMN_CNT = "dir_landscape_column_cnt"
const val DIR_HORIZONTAL_COLUMN_CNT = "dir_horizontal_column_cnt"
const val DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "dir_landscape_horizontal_column_cnt"
const val MEDIA_COLUMN_CNT = "media_column_cnt"
const val MEDIA_LANDSCAPE_COLUMN_CNT = "media_landscape_column_cnt"
const val MEDIA_HORIZONTAL_COLUMN_CNT = "media_horizontal_column_cnt"
const val MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "media_landscape_horizontal_column_cnt"
const val SHOW_ALL = "show_all" // display images and videos from all folders together
const val HIDE_FOLDER_TOOLTIP_SHOWN = "hide_folder_tooltip_shown"
const val EXCLUDED_FOLDERS = "excluded_folders"
const val INCLUDED_FOLDERS = "included_folders"
const val ALBUM_COVERS = "album_covers"
const val HIDE_SYSTEM_UI = "hide_system_ui"
const val REPLACE_SHARE_WITH_ROTATE = "replace_share_with_rotate"
const val DELETE_EMPTY_FOLDERS = "delete_empty_folders"
const val ALLOW_PHOTO_GESTURES = "allow_photo_gestures"
const val ALLOW_VIDEO_GESTURES = "allow_video_gestures"
const val SHOW_MEDIA_COUNT = "show_media_count"
const val TEMP_FOLDER_PATH = "temp_folder_path"
const val VIEW_TYPE_FOLDERS = "view_type_folders"
const val VIEW_TYPE_FILES = "view_type_files"
const val SHOW_EXTENDED_DETAILS = "show_extended_details"
const val EXTENDED_DETAILS = "extended_details"
const val HIDE_EXTENDED_DETAILS = "hide_extended_details"
const val ONE_FINGER_ZOOM = "one_finger_zoom"
const val ALLOW_INSTANT_CHANGE = "allow_instant_change"
const val REPLACE_ZOOMABLE_IMAGES = "replace_zoomable_images"
const val DO_EXTRA_CHECK = "do_extra_check"
const val WAS_NEW_APP_SHOWN = "was_new_app_shown_clock"
const val LAST_FILEPICKER_PATH = "last_filepicker_path"
const val WAS_OTG_HANDLED = "was_otg_handled"
const val TEMP_SKIP_DELETE_CONFIRMATION = "temp_skip_delete_confirmation"
// slideshow
const val SLIDESHOW_INTERVAL = "slideshow_interval"
const val SLIDESHOW_INCLUDE_PHOTOS = "slideshow_include_photos"
const val SLIDESHOW_INCLUDE_VIDEOS = "slideshow_include_videos"
const val SLIDESHOW_INCLUDE_GIFS = "slideshow_include_gifs"
const val SLIDESHOW_RANDOM_ORDER = "slideshow_random_order"
const val SLIDESHOW_USE_FADE = "slideshow_use_fade"
const val SLIDESHOW_MOVE_BACKWARDS = "slideshow_move_backwards"
const val SLIDESHOW_LOOP = "loop_slideshow"
const val SLIDESHOW_DEFAULT_INTERVAL = 5
const val SLIDESHOW_SCROLL_DURATION = 500L
const val NOMEDIA = ".nomedia"
const val MAX_COLUMN_COUNT = 20
const val SHOW_TEMP_HIDDEN_DURATION = 600000L
const val CLICK_MAX_DURATION = 150
const val DRAG_THRESHOLD = 8
const val DIRECTORY = "directory"
const val MEDIUM = "medium"
const val PATH = "path"
const val GET_IMAGE_INTENT = "get_image_intent"
const val GET_VIDEO_INTENT = "get_video_intent"
const val GET_ANY_INTENT = "get_any_intent"
const val SET_WALLPAPER_INTENT = "set_wallpaper_intent"
const val IS_VIEW_INTENT = "is_view_intent"
const val PICKED_PATHS = "picked_paths"
// rotations
const val ROTATE_BY_SYSTEM_SETTING = 0
const val ROTATE_BY_DEVICE_ROTATION = 1
const val ROTATE_BY_ASPECT_RATIO = 2
// view types
const val VIEW_TYPE_GRID = 1
const val VIEW_TYPE_LIST = 2
// extended details values
const val EXT_NAME = 1
const val EXT_PATH = 2
const val EXT_SIZE = 4
const val EXT_RESOLUTION = 8
const val EXT_LAST_MODIFIED = 16
const val EXT_DATE_TAKEN = 32
const val EXT_CAMERA_MODEL = 64
const val EXT_EXIF_PROPERTIES = 128
const val EXT_DURATION = 256
const val EXT_ARTIST = 512
const val EXT_ALBUM = 1024
// media types
const val TYPE_IMAGES = 1
const val TYPE_VIDEOS = 2
const val TYPE_GIFS = 4
const val LOCAITON_INTERNAL = 1
const val LOCATION_SD = 2
const val LOCATION_OTG = 3

View file

@ -1,21 +0,0 @@
package com.simplemobiletools.gallery.helpers
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
import java.security.MessageDigest
class GlideRotateTransformation(val rotateRotationAngle: Int) : BitmapTransformation() {
override fun transform(pool: BitmapPool, bitmap: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
if (rotateRotationAngle % 360 == 0)
return bitmap
val matrix = Matrix()
matrix.postRotate(rotateRotationAngle.toFloat())
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
override fun updateDiskCacheKey(messageDigest: MessageDigest) {
}
}

View file

@ -1,299 +0,0 @@
package com.simplemobiletools.gallery.helpers
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.extensions.getDistinctPath
import com.simplemobiletools.gallery.extensions.getOTGFolderChildren
import com.simplemobiletools.gallery.extensions.shouldFolderBeVisible
import com.simplemobiletools.gallery.models.Medium
import java.io.File
class MediaFetcher(val context: Context) {
var shouldStop = false
fun getFilesFrom(curPath: String, isPickImage: Boolean, isPickVideo: Boolean, getProperDateTaken: Boolean): ArrayList<Medium> {
val filterMedia = context.config.filterMedia
if (filterMedia == 0) {
return ArrayList()
}
val curMedia = ArrayList<Medium>()
if (curPath.startsWith(OTG_PATH)) {
val newMedia = getMediaOnOTG(curPath, isPickImage, isPickVideo, filterMedia)
curMedia.addAll(newMedia)
} else {
val newMedia = getMediaInFolder(curPath, isPickImage, isPickVideo, filterMedia, getProperDateTaken)
curMedia.addAll(newMedia)
}
sortMedia(curMedia, context.config.getFileSorting(curPath))
return curMedia
}
fun getFoldersToScan(): ArrayList<String> {
val filterMedia = context.config.filterMedia
val projection = arrayOf(MediaStore.Images.Media.DATA)
val uri = MediaStore.Files.getContentUri("external")
val selection = "${getSelectionQuery(filterMedia)} ${MediaStore.Images.ImageColumns.BUCKET_ID} IS NOT NULL) GROUP BY (${MediaStore.Images.ImageColumns.BUCKET_ID}"
val selectionArgs = getSelectionArgsQuery(filterMedia).toTypedArray()
return try {
val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
parseCursor(cursor)
} catch (e: Exception) {
ArrayList()
}
}
private fun getSelectionQuery(filterMedia: Int): String {
val query = StringBuilder()
query.append("(")
if (filterMedia and TYPE_IMAGES != 0) {
photoExtensions.forEach {
query.append("${MediaStore.Images.Media.DATA} LIKE ? OR ")
}
}
if (filterMedia and TYPE_VIDEOS != 0) {
videoExtensions.forEach {
query.append("${MediaStore.Images.Media.DATA} LIKE ? OR ")
}
}
if (filterMedia and TYPE_GIFS != 0) {
query.append("${MediaStore.Images.Media.DATA} LIKE ?")
}
var selectionQuery = query.toString().trim().removeSuffix("OR")
selectionQuery += ") AND "
return selectionQuery
}
private fun getSelectionArgsQuery(filterMedia: Int): ArrayList<String> {
val args = ArrayList<String>()
if (filterMedia and TYPE_IMAGES != 0) {
photoExtensions.forEach {
args.add("%$it")
}
}
if (filterMedia and TYPE_VIDEOS != 0) {
videoExtensions.forEach {
args.add("%$it")
}
}
if (filterMedia and TYPE_GIFS != 0) {
args.add("%.gif")
}
return args
}
private fun parseCursor(cursor: Cursor): ArrayList<String> {
val config = context.config
val includedFolders = config.includedFolders
var foldersToScan = ArrayList<String>()
cursor.use {
if (cursor.moveToFirst()) {
do {
val path = cursor.getStringValue(MediaStore.Images.Media.DATA).trim()
val parentPath = File(path).parent?.trimEnd('/') ?: continue
if (!includedFolders.contains(parentPath)) {
foldersToScan.add(parentPath)
}
} while (cursor.moveToNext())
}
}
includedFolders.forEach {
addFolder(foldersToScan, it)
}
val showHidden = config.shouldShowHidden
val excludedFolders = config.excludedFolders
foldersToScan = foldersToScan.filter { it.shouldFolderBeVisible(excludedFolders, includedFolders, showHidden) } as ArrayList<String>
return foldersToScan.distinctBy { it.getDistinctPath() } as ArrayList<String>
}
private fun addFolder(curFolders: ArrayList<String>, folder: String) {
curFolders.add(folder)
if (folder.startsWith(OTG_PATH)) {
val files = context.getOTGFolderChildren(folder) ?: return
for (file in files) {
if (file.isDirectory) {
val relativePath = file.uri.path.substringAfterLast("${context.config.OTGPartition}:")
addFolder(curFolders, "$OTG_PATH$relativePath")
}
}
} else {
val files = File(folder).listFiles() ?: return
for (file in files) {
if (file.isDirectory) {
addFolder(curFolders, file.absolutePath)
}
}
}
}
private fun getMediaInFolder(folder: String, isPickImage: Boolean, isPickVideo: Boolean, filterMedia: Int, getProperDateTaken: Boolean): ArrayList<Medium> {
val media = ArrayList<Medium>()
val files = File(folder).listFiles() ?: return media
val doExtraCheck = context.config.doExtraCheck
val showHidden = context.config.shouldShowHidden
val dateTakens = if (getProperDateTaken) getFolderDateTakens(folder) else HashMap()
for (file in files) {
if (shouldStop) {
break
}
val filename = file.name
val isImage = filename.isImageFast()
val isVideo = if (isImage) false else filename.isVideoFast()
val isGif = if (isImage || isVideo) false else filename.isGif()
if (!isImage && !isVideo && !isGif)
continue
if (isVideo && (isPickImage || filterMedia and TYPE_VIDEOS == 0))
continue
if (isImage && (isPickVideo || filterMedia and TYPE_IMAGES == 0))
continue
if (isGif && filterMedia and TYPE_GIFS == 0)
continue
if (!showHidden && filename.startsWith('.'))
continue
val size = file.length()
if (size <= 0L || (doExtraCheck && !file.exists()))
continue
val lastModified = file.lastModified()
var dateTaken = lastModified
if (getProperDateTaken) {
dateTaken = dateTakens.remove(filename) ?: lastModified
}
val type = when {
isImage -> TYPE_IMAGES
isVideo -> TYPE_VIDEOS
else -> TYPE_GIFS
}
val medium = Medium(null, filename, file.absolutePath, folder, lastModified, dateTaken, size, type)
media.add(medium)
}
return media
}
private fun getMediaOnOTG(folder: String, isPickImage: Boolean, isPickVideo: Boolean, filterMedia: Int): ArrayList<Medium> {
val media = ArrayList<Medium>()
val files = context.getDocumentFile(folder)?.listFiles() ?: return media
val doExtraCheck = context.config.doExtraCheck
val showHidden = context.config.shouldShowHidden
for (file in files) {
if (shouldStop) {
break
}
val filename = file.name ?: continue
val isImage = filename.isImageFast()
val isVideo = if (isImage) false else filename.isVideoFast()
val isGif = if (isImage || isVideo) false else filename.isGif()
if (!isImage && !isVideo && !isGif)
continue
if (isVideo && (isPickImage || filterMedia and TYPE_VIDEOS == 0))
continue
if (isImage && (isPickVideo || filterMedia and TYPE_IMAGES == 0))
continue
if (isGif && filterMedia and TYPE_GIFS == 0)
continue
if (!showHidden && filename.startsWith('.'))
continue
val size = file.length()
if (size <= 0L || (doExtraCheck && !file.exists()))
continue
val dateTaken = file.lastModified()
val dateModified = file.lastModified()
val type = when {
isImage -> TYPE_IMAGES
isVideo -> TYPE_VIDEOS
else -> TYPE_GIFS
}
val path = Uri.decode(file.uri.toString().replaceFirst("${context.config.OTGTreeUri}/document/${context.config.OTGPartition}%3A", OTG_PATH))
val medium = Medium(null, filename, path, folder, dateModified, dateTaken, size, type)
media.add(medium)
}
return media
}
private fun getFolderDateTakens(folder: String): HashMap<String, Long> {
val projection = arrayOf(
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN
)
val uri = MediaStore.Files.getContentUri("external")
val selection = "${MediaStore.Images.Media.DATA} LIKE ? AND ${MediaStore.Images.Media.DATA} NOT LIKE ?"
val selectionArgs = arrayOf("$folder/%", "$folder/%/%")
val dateTakens = HashMap<String, Long>()
val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor.use {
if (cursor.moveToFirst()) {
do {
try {
val path = cursor.getStringValue(MediaStore.Images.Media.DISPLAY_NAME)
val dateTaken = cursor.getLongValue(MediaStore.Images.Media.DATE_TAKEN)
dateTakens[path] = dateTaken
} catch (e: Exception) {
}
} while (cursor.moveToNext())
}
}
return dateTakens
}
fun sortMedia(media: ArrayList<Medium>, sorting: Int) {
media.sortWith(Comparator { o1, o2 ->
o1 as Medium
o2 as Medium
var result = when {
sorting and SORT_BY_NAME != 0 -> AlphanumericComparator().compare(o1.name.toLowerCase(), o2.name.toLowerCase())
sorting and SORT_BY_PATH != 0 -> AlphanumericComparator().compare(o1.path.toLowerCase(), o2.path.toLowerCase())
sorting and SORT_BY_SIZE != 0 -> o1.size.compareTo(o2.size)
sorting and SORT_BY_DATE_MODIFIED != 0 -> o1.modified.compareTo(o2.modified)
else -> o1.taken.compareTo(o2.taken)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
result
})
}
}

View file

@ -1,28 +0,0 @@
package com.simplemobiletools.gallery.interfaces
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.OnConflictStrategy.REPLACE
import android.arch.persistence.room.Query
import com.simplemobiletools.gallery.models.Directory
@Dao
interface DirectoryDao {
@Query("SELECT path, thumbnail, filename, media_count, last_modified, date_taken, size, location, media_types FROM directories")
fun getAll(): List<Directory>
@Insert(onConflict = REPLACE)
fun insert(directory: Directory)
@Insert(onConflict = REPLACE)
fun insertAll(directories: List<Directory>)
@Query("DELETE FROM directories WHERE path = :path")
fun deleteDirPath(path: String)
@Query("UPDATE OR REPLACE directories SET thumbnail = :thumbnail, media_count = :mediaCnt, last_modified = :lastModified, date_taken = :dateTaken, size = :size, media_types = :mediaTypes WHERE path = :path")
fun updateDirectory(path: String, thumbnail: String, mediaCnt: Int, lastModified: Long, dateTaken: Long, size: Long, mediaTypes: Int)
@Query("UPDATE directories SET thumbnail = :thumbnail, filename = :name, path = :newPath WHERE path = :oldPath")
fun updateDirectoryAfterRename(thumbnail: String, name: String, newPath: String, oldPath: String)
}

View file

@ -1,25 +0,0 @@
package com.simplemobiletools.gallery.interfaces
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.OnConflictStrategy.REPLACE
import android.arch.persistence.room.Query
import com.simplemobiletools.gallery.models.Medium
@Dao
interface MediumDao {
@Query("SELECT filename, full_path, parent_path, last_modified, date_taken, size, type FROM media WHERE parent_path = :path")
fun getMediaFromPath(path: String): List<Medium>
@Insert(onConflict = REPLACE)
fun insert(medium: Medium)
@Insert(onConflict = REPLACE)
fun insertAll(media: List<Medium>)
@Query("DELETE FROM media WHERE full_path = :path")
fun deleteMediumPath(path: String)
@Query("UPDATE OR REPLACE media SET filename = :newFilename, full_path = :newFullPath, parent_path = :newParentPath WHERE full_path = :oldPath")
fun updateMedium(oldPath: String, newParentPath: String, newFilename: String, newFullPath: String)
}

View file

@ -1,39 +0,0 @@
package com.simplemobiletools.gallery.models
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Index
import android.arch.persistence.room.PrimaryKey
import com.simplemobiletools.commons.extensions.formatDate
import com.simplemobiletools.commons.extensions.formatSize
import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
import com.simplemobiletools.commons.helpers.SORT_BY_NAME
import com.simplemobiletools.commons.helpers.SORT_BY_PATH
import com.simplemobiletools.commons.helpers.SORT_BY_SIZE
import java.io.Serializable
@Entity(tableName = "directories", indices = [Index(value = "path", unique = true)])
data class Directory(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "path") var path: String,
@ColumnInfo(name = "thumbnail") var tmb: String,
@ColumnInfo(name = "filename") var name: String,
@ColumnInfo(name = "media_count") var mediaCnt: Int,
@ColumnInfo(name = "last_modified") var modified: Long,
@ColumnInfo(name = "date_taken") var taken: Long,
@ColumnInfo(name = "size") var size: Long,
@ColumnInfo(name = "location") val location: Int,
@ColumnInfo(name = "media_types") var types: Int) : Serializable {
companion object {
private const val serialVersionUID = -6553345863555455L
}
fun getBubbleText(sorting: Int) = when {
sorting and SORT_BY_NAME != 0 -> name
sorting and SORT_BY_PATH != 0 -> path
sorting and SORT_BY_SIZE != 0 -> size.formatSize()
sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate()
else -> taken.formatDate()
}
}

View file

@ -1,49 +0,0 @@
package com.simplemobiletools.gallery.models
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Index
import android.arch.persistence.room.PrimaryKey
import com.simplemobiletools.commons.extensions.formatDate
import com.simplemobiletools.commons.extensions.formatSize
import com.simplemobiletools.commons.extensions.isDng
import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
import com.simplemobiletools.commons.helpers.SORT_BY_NAME
import com.simplemobiletools.commons.helpers.SORT_BY_PATH
import com.simplemobiletools.commons.helpers.SORT_BY_SIZE
import com.simplemobiletools.gallery.helpers.TYPE_GIFS
import com.simplemobiletools.gallery.helpers.TYPE_IMAGES
import com.simplemobiletools.gallery.helpers.TYPE_VIDEOS
import java.io.Serializable
@Entity(tableName = "media", indices = [(Index(value = "full_path", unique = true))])
data class Medium(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "filename") var name: String,
@ColumnInfo(name = "full_path") var path: String,
@ColumnInfo(name = "parent_path") var parentPath: String,
@ColumnInfo(name = "last_modified") val modified: Long,
@ColumnInfo(name = "date_taken") var taken: Long,
@ColumnInfo(name = "size") val size: Long,
@ColumnInfo(name = "type") val type: Int) : Serializable {
companion object {
private const val serialVersionUID = -6553149366975455L
}
fun isGif() = type == TYPE_GIFS
fun isImage() = type == TYPE_IMAGES
fun isVideo() = type == TYPE_VIDEOS
fun isDng() = path.isDng()
fun getBubbleText(sorting: Int) = when {
sorting and SORT_BY_NAME != 0 -> name
sorting and SORT_BY_PATH != 0 -> path
sorting and SORT_BY_SIZE != 0 -> size.formatSize()
sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate()
else -> taken.formatDate()
}
}

View file

@ -0,0 +1,13 @@
package com.simplemobiletools.gallery.pro
import androidx.multidex.MultiDexApplication
import com.github.ajalt.reprint.core.Reprint
import com.simplemobiletools.commons.extensions.checkUseEnglish
class App : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
checkUseEnglish()
Reprint.initialize(this)
}
}

View file

@ -0,0 +1,889 @@
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.media.ExifInterface
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.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.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<Float, Float>? = 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<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
if (uri != originalUri) {
uri = originalUri
Handler().post {
loadDefaultImageView()
}
}
return false
}
override fun onResourceReady(bitmap: Bitmap?, model: Any?, target: Target<Bitmap>?, 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() {
var inputStream: InputStream? = null
try {
if (isNougatPlus()) {
inputStream = contentResolver.openInputStream(uri!!)
oldExif = ExifInterface(inputStream!!)
}
} catch (e: Exception) {
} finally {
inputStream?.close()
}
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)
}
}
}
}
}
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<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
showErrorToast(e.toString())
return false
}
override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, 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) {
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<String, Boolean> {
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?.copyTo(newExif, false)
}
} 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()
}
}
}

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.activities
package com.simplemobiletools.gallery.pro.activities
import android.os.Bundle
import android.view.Menu
@ -6,9 +6,9 @@ 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.R
import com.simplemobiletools.gallery.adapters.ManageFoldersAdapter
import com.simplemobiletools.gallery.extensions.config
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 {
@ -20,7 +20,7 @@ class ExcludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
private fun updateFolders() {
val folders = ArrayList<String>()
config.excludedFolders.mapTo(folders, { it })
config.excludedFolders.mapTo(folders) { it }
manage_folders_placeholder.apply {
text = getString(R.string.excluded_activity_placeholder)
beVisibleIf(folders.isEmpty())
@ -31,8 +31,9 @@ class ExcludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
manage_folders_list.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_add_folder, menu)
updateMenuItemColors(menu)
return true
}
@ -49,7 +50,7 @@ class ExcludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
}
private fun addFolder() {
FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden) {
FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden, false, true, true) {
config.lastFilepickerPath = it
config.addExcludedFolder(it)
updateFolders()

View file

@ -1,16 +1,17 @@
package com.simplemobiletools.gallery.activities
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.R
import com.simplemobiletools.gallery.adapters.ManageHiddenFoldersAdapter
import com.simplemobiletools.gallery.extensions.addNoMedia
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.extensions.getNoMediaFolders
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 {
@ -35,8 +36,9 @@ class HiddenFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_add_folder, menu)
updateMenuItemColors(menu)
return true
}
@ -53,13 +55,13 @@ class HiddenFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
}
private fun addFolder() {
FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden) {
FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden, false, true) {
config.lastFilepickerPath = it
Thread {
ensureBackgroundThread {
addNoMedia(it) {
updateFolders()
}
}.start()
}
}
}
}

View file

@ -1,15 +1,13 @@
package com.simplemobiletools.gallery.activities
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.extensions.scanPathRecursively
import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.adapters.ManageFoldersAdapter
import com.simplemobiletools.gallery.extensions.config
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 {
@ -21,7 +19,7 @@ class IncludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
private fun updateFolders() {
val folders = ArrayList<String>()
config.includedFolders.mapTo(folders, { it })
config.includedFolders.mapTo(folders) { it }
manage_folders_placeholder.apply {
text = getString(R.string.included_activity_placeholder)
beVisibleIf(folders.isEmpty())
@ -32,8 +30,9 @@ class IncludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
manage_folders_list.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_add_folder, menu)
updateMenuItemColors(menu)
return true
}
@ -50,13 +49,8 @@ class IncludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
}
private fun addFolder() {
FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden) {
config.lastFilepickerPath = it
config.addIncludedFolder(it)
showAddIncludedFolderDialog {
updateFolders()
Thread {
scanPathRecursively(it)
}.start()
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.activities
package com.simplemobiletools.gallery.pro.activities
import android.app.Activity
import android.app.SearchManager
@ -9,42 +9,48 @@ import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v4.view.MenuItemCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.SearchView
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.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.dialogs.CreateNewFolderDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.OTG_PATH
import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_STORAGE
import com.simplemobiletools.commons.helpers.REQUEST_EDIT_IMAGE
import com.simplemobiletools.commons.helpers.SORT_BY_RANDOM
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.views.MyGridLayoutManager
import com.simplemobiletools.commons.views.MyRecyclerView
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.dialogs.FilterMediaDialog
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.*
import com.simplemobiletools.gallery.models.Medium
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.*
class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
class MediaActivity : SimpleActivity(), MediaOperationsListener {
private val LAST_MEDIA_CHECK_PERIOD = 3000L
private var mPath = ""
@ -56,6 +62,9 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
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()
@ -68,16 +77,18 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
private var mStoredCropThumbnails = true
private var mStoredScrollHorizontally = true
private var mStoredShowInfoBubble = true
private var mStoredShowFileTypes = true
private var mStoredTextColor = 0
private var mStoredPrimaryColor = 0
companion object {
var mMedia = ArrayList<Medium>()
var mMedia = ArrayList<ThumbnailItem>()
}
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)
@ -98,11 +109,14 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
if (mShowAll) {
supportActionBar?.setDisplayHomeAsUpEnabled(false)
registerFileUpdateListener()
}
media_empty_text.setOnClickListener {
media_empty_text_placeholder_2.setOnClickListener {
showFilterMediaDialog()
}
updateWidgets()
}
override fun onStart() {
@ -112,6 +126,9 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
override fun onResume() {
super.onResume()
mDateFormat = config.dateFormat
mTimeFormat = getTimeFormat()
if (mStoredAnimateGifs != config.animateGifs) {
getMediaAdapter()?.updateAnimateGifs(config.animateGifs)
}
@ -121,8 +138,13 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
}
if (mStoredScrollHorizontally != config.scrollHorizontally) {
getMediaAdapter()?.updateScrollHorizontally(config.viewTypeFiles != VIEW_TYPE_LIST || !config.scrollHorizontally)
setupScrollDirection()
mLoadedInitialPhotos = false
media_grid.adapter = null
getMedia()
}
if (mStoredShowFileTypes != config.showThumbnailFileTypes) {
getMediaAdapter()?.updateShowFileTypes(config.showThumbnailFileTypes)
}
if (mStoredTextColor != config.textColor) {
@ -140,10 +162,26 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
media_horizontal_fastscroller.allowBubbleDisplay = config.showInfoBubble
media_vertical_fastscroller.allowBubbleDisplay = config.showInfoBubble
media_refresh_layout.isEnabled = config.enablePullToRefresh
tryloadGallery()
invalidateOptionsMenu()
media_empty_text_label.setTextColor(config.textColor)
media_empty_text.setTextColor(getAdjustedPrimaryColor())
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() {
@ -160,11 +198,11 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
override fun onStop() {
super.onStop()
mSearchMenuItem?.collapseActionView()
if (config.temporarilyShowHidden) {
if (config.temporarilyShowHidden || config.tempSkipDeleteConfirmation) {
mTempShowHiddenHandler.postDelayed({
config.temporarilyShowHidden = false
config.tempSkipDeleteConfirmation = false
}, SHOW_TEMP_HIDDEN_DURATION)
} else {
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
@ -173,9 +211,11 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
override fun onDestroy() {
super.onDestroy()
if (config.showAll) {
if (config.showAll && !isChangingConfigurations) {
config.temporarilyShowHidden = false
config.tempSkipDeleteConfirmation = false
unregisterFileUpdateListener()
GalleryDatabase.destroyInstance()
}
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
@ -185,26 +225,29 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
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.exclude_folder).isVisible = !mShowAll
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.increase_column_count).isVisible = config.viewTypeFiles == VIEW_TYPE_GRID && config.mediaColumnCnt < MAX_COLUMN_COUNT
findItem(R.id.reduce_column_count).isVisible = config.viewTypeFiles == VIEW_TYPE_GRID && config.mediaColumnCnt > 1
findItem(R.id.toggle_filename).isVisible = config.viewTypeFiles == VIEW_TYPE_GRID
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
}
@ -212,17 +255,20 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
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.hide_folder -> tryHideFolder()
R.id.unhide_folder -> unhideFolder()
R.id.exclude_folder -> tryExcludeFolder()
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.slideshow -> startSlideshow()
R.id.settings -> launchSettings()
R.id.about -> launchAbout()
else -> return super.onOptionsItemSelected(item)
@ -230,12 +276,26 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
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
mStoredShowInfoBubble = showInfoBubble
mStoredShowFileTypes = showThumbnailFileTypes
mStoredTextColor = textColor
mStoredPrimaryColor = primaryColor
mShowAll = showAll
@ -245,7 +305,7 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
private fun setupSearch(menu: Menu) {
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
mSearchMenuItem = menu.findItem(R.id.search)
(mSearchMenuItem!!.actionView as SearchView).apply {
(mSearchMenuItem?.actionView as? SearchView)?.apply {
setSearchableInfo(searchManager.getSearchableInfo(componentName))
isSubmitButtonEnabled = false
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
@ -253,6 +313,7 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
override fun onQueryTextChange(newText: String): Boolean {
if (mIsSearchOpen) {
mLastSearchedText = newText
searchQueryChanged(newText)
}
return true
@ -267,33 +328,52 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
return true
}
// this triggers on device rotation too, avoid doing anything
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
mIsSearchOpen = false
media_refresh_layout.isEnabled = config.enablePullToRefresh
if (mIsSearchOpen) {
mIsSearchOpen = false
mLastSearchedText = ""
media_refresh_layout.isEnabled = config.enablePullToRefresh
searchQueryChanged("")
}
return true
}
})
}
private fun searchQueryChanged(text: String) {
Thread {
val filtered = mMedia.filter { it.name.contains(text, true) } as ArrayList
filtered.sortBy { !it.name.startsWith(text, true) }
runOnUiThread {
getMediaAdapter()?.updateMedia(filtered)
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<Medium>, 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()
}
getMediaAdapter()?.updateMedia(grouped)
measureRecyclerViewContent(grouped)
}
} catch (ignored: Exception) {
}
}.start()
}
}
private fun tryloadGallery() {
private fun tryLoadGallery() {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
val dirName = when {
mPath == OTG_PATH -> getString(R.string.otg)
mPath.startsWith(OTG_PATH) -> mPath.trimEnd('/').substringAfterLast('/')
mPath == FAVORITES -> getString(R.string.favorites)
mPath == RECYCLE_BIN -> getString(R.string.recycle_bin)
mPath == config.OTGPath -> getString(R.string.usb)
else -> getHumanizedFilename(mPath)
}
supportActionBar?.title = if (mShowAll) resources.getString(R.string.all_folders) else dirName
updateActionBarTitle(if (mShowAll) resources.getString(R.string.all_folders) else dirName)
getMedia()
setupLayoutManager()
} else {
@ -314,28 +394,37 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
if (currAdapter == null) {
initZoomListener()
val fastscroller = if (config.scrollHorizontally) media_horizontal_fastscroller else media_vertical_fastscroller
MediaAdapter(this, mMedia, this, mIsGetImageIntent || mIsGetVideoIntent || mIsGetAnyIntent, mAllowPickingMultiple, media_grid, fastscroller) {
itemClicked((it as Medium).path)
MediaAdapter(this, mMedia.clone() as ArrayList<ThumbnailItem>, this, mIsGetImageIntent || mIsGetVideoIntent || mIsGetAnyIntent,
mAllowPickingMultiple, mPath, media_grid, fastscroller) {
if (it is Medium && !isFinishing) {
itemClicked(it.path)
}
}.apply {
setupZoomListener(mZoomListener)
media_grid.adapter = this
}
} else {
setupLayoutManager()
measureRecyclerViewContent(mMedia)
} else if (mLastSearchedText.isEmpty()) {
(currAdapter as MediaAdapter).updateMedia(mMedia)
measureRecyclerViewContent(mMedia)
} else {
searchQueryChanged(mLastSearchedText)
}
setupScrollDirection()
}
private fun setupScrollDirection() {
val allowHorizontalScroll = config.scrollHorizontally && config.viewTypeFiles == VIEW_TYPE_GRID
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.getFileSorting(mPath)
val sorting = config.getFolderSorting(if (mShowAll) SHOW_ALL else mPath)
if (allowHorizontalScroll) {
media_horizontal_fastscroller.allowBubbleDisplay = config.showInfoBubble
media_horizontal_fastscroller.setViews(media_grid, media_refresh_layout) {
@ -349,15 +438,23 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
}
}
private fun getBubbleTextItem(index: Int, sorting: Int) = getMediaAdapter()?.media?.getOrNull(index)?.getBubbleText(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 (isActivityDestroyed())
if (isDestroyed || config.getFolderSorting(mPath) and SORT_BY_RANDOM != 0) {
return
}
mLastMediaHandler.removeCallbacksAndMessages(null)
mLastMediaHandler.postDelayed({
Thread {
ensureBackgroundThread {
val mediaId = getLatestMediaId()
val mediaDateId = getLatestMediaByDateId()
if (mLatestMediaId != mediaId || mLatestMediaDateId != mediaDateId) {
@ -369,13 +466,14 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
} else {
checkLastMediaChanged()
}
}.start()
}
}, LAST_MEDIA_CHECK_PERIOD)
}
private fun showSortingDialog() {
ChangeSortingDialog(this, false, !config.showAll, mPath) {
ChangeSortingDialog(this, false, true, mPath) {
mLoadedInitialPhotos = false
media_grid.adapter = null
getMedia()
}
}
@ -384,10 +482,37 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
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<String>
restoreRecycleBinPaths(paths) {
ensureBackgroundThread {
directoryDao.deleteDirPath(RECYCLE_BIN)
}
finish()
}
}
private fun toggleFilenameVisibility() {
config.displayFileNames = !config.displayFileNames
getMediaAdapter()?.updateDisplayFilenames(config.displayFileNames)
@ -400,12 +525,7 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
}
private fun changeViewType() {
val items = arrayListOf(
RadioItem(VIEW_TYPE_GRID, getString(R.string.grid)),
RadioItem(VIEW_TYPE_LIST, getString(R.string.list)))
RadioGroupDialog(this, items, config.viewTypeFiles) {
config.viewTypeFiles = it as Int
ChangeViewTypeDialog(this, false, mPath) {
invalidateOptionsMenu()
setupLayoutManager()
media_grid.adapter = null
@ -413,47 +533,18 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
}
}
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 showGroupByDialog() {
ChangeGroupingDialog(this, mPath) {
mLoadedInitialPhotos = false
media_grid.adapter = null
getMedia()
}
}
private fun deleteDirectoryIfEmpty() {
val fileDirItem = FileDirItem(mPath, mPath.getFilenameFromPath())
if (config.deleteEmptyFolders && !fileDirItem.isDownloadsFolder() && fileDirItem.isDirectory && fileDirItem.getProperFileCount(applicationContext, true) == 0) {
tryDeleteFileDirItem(fileDirItem, true)
val fileDirItem = FileDirItem(mPath, mPath.getFilenameFromPath(), true)
if (config.deleteEmptyFolders && !fileDirItem.isDownloadsFolder() && fileDirItem.isDirectory && fileDirItem.getProperFileCount(this, true) == 0) {
tryDeleteFileDirItem(fileDirItem, true, true)
}
}
@ -463,7 +554,9 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
}
mIsGettingMedia = true
if (!mLoadedInitialPhotos) {
if (mLoadedInitialPhotos) {
startAsyncTask()
} else {
getCachedMedia(mPath, mIsGetVideoIntent, mIsGetImageIntent) {
if (it.isEmpty()) {
runOnUiThread {
@ -472,15 +565,27 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
} else {
gotMedia(it, true)
}
startAsyncTask()
}
} else {
media_refresh_layout.isRefreshing = true
}
mLoadedInitialPhotos = true
}
private fun startAsyncTask() {
mCurrAsyncTask?.stopFetching()
mCurrAsyncTask = GetMediaAsynctask(applicationContext, mPath, mIsGetImageIntent, mIsGetVideoIntent, mShowAll) {
gotMedia(it)
ensureBackgroundThread {
val oldMedia = mMedia.clone() as ArrayList<ThumbnailItem>
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()
@ -488,8 +593,17 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
private fun isDirEmpty(): Boolean {
return if (mMedia.size <= 0 && config.filterMedia > 0) {
deleteDirectoryIfEmpty()
deleteDBDirectory()
if (mPath != FAVORITES && mPath != RECYCLE_BIN) {
deleteDirectoryIfEmpty()
deleteDBDirectory()
}
if (mPath == FAVORITES) {
ensureBackgroundThread {
directoryDao.deleteDirPath(FAVORITES)
}
}
finish()
true
} else {
@ -498,9 +612,18 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
}
private fun deleteDBDirectory() {
Thread {
galleryDB.DirectoryDao().deleteDirPath(mPath)
}.start()
ensureBackgroundThread {
try {
directoryDao.deleteDirPath(mPath)
} catch (ignored: Exception) {
}
}
}
private fun createNewFolder() {
CreateNewFolderDialog(this, mPath) {
config.tempFolderPath = it
}
}
private fun tryToggleTemporarilyShowHidden() {
@ -521,7 +644,8 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
}
private fun setupLayoutManager() {
if (config.viewTypeFiles == VIEW_TYPE_GRID) {
val viewType = config.getFolderViewType(if (mShowAll) SHOW_ALL else mPath)
if (viewType == VIEW_TYPE_GRID) {
setupGridLayoutManager()
} else {
setupListLayoutManager()
@ -530,19 +654,80 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
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 = GridLayoutManager.HORIZONTAL
layoutManager.orientation = RecyclerView.HORIZONTAL
media_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
} else {
layoutManager.orientation = GridLayoutManager.VERTICAL
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<ThumbnailItem>) {
media_grid.onGlobalLayout {
if (config.scrollHorizontally) {
calculateContentWidth(media)
} else {
calculateContentHeight(media)
}
}
}
private fun calculateContentWidth(media: ArrayList<ThumbnailItem>) {
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<ThumbnailItem>) {
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++
}
}
fullHeight += ((curSectionItems - 1) / layoutManager.spanCount + 1) * thumbnailHeight
media_vertical_fastscroller.setContentHeight(fullHeight)
media_vertical_fastscroller.setScrollToY(media_grid.computeVerticalScrollOffset())
}
private fun initZoomListener() {
if (config.viewTypeFiles == VIEW_TYPE_GRID) {
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() {
@ -567,25 +752,32 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
private fun setupListLayoutManager() {
val layoutManager = media_grid.layoutManager as MyGridLayoutManager
layoutManager.spanCount = 1
layoutManager.orientation = GridLayoutManager.VERTICAL
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() {
media_vertical_fastscroller.measureRecyclerViewOnRedraw()
media_horizontal_fastscroller.measureRecyclerViewOnRedraw()
config.mediaColumnCnt = ++(media_grid.layoutManager as MyGridLayoutManager).spanCount
invalidateOptionsMenu()
media_grid.adapter?.notifyDataSetChanged()
columnCountChanged()
}
private fun reduceColumnCount() {
media_vertical_fastscroller.measureRecyclerViewOnRedraw()
media_horizontal_fastscroller.measureRecyclerViewOnRedraw()
config.mediaColumnCnt = --(media_grid.layoutManager as MyGridLayoutManager).spanCount
columnCountChanged()
}
private fun columnCountChanged() {
invalidateOptionsMenu()
media_grid.adapter?.notifyDataSetChanged()
measureRecyclerViewContent(mMedia)
}
private fun isSetWallpaperIntent() = intent.getBooleanExtra(SET_WALLPAPER_INTENT, false)
@ -609,24 +801,24 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
val ratio = wantedWidth.toFloat() / wantedHeight
val options = RequestOptions()
.override((wantedWidth * ratio).toInt(), wantedHeight)
.fitCenter()
.override((wantedWidth * ratio).toInt(), wantedHeight)
.fitCenter()
Glide.with(this)
.asBitmap()
.load(File(path))
.apply(options)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
try {
WallpaperManager.getInstance(applicationContext).setBitmap(resource)
setResult(Activity.RESULT_OK)
} catch (ignored: IOException) {
}
finish()
.asBitmap()
.load(File(path))
.apply(options)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
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)
@ -636,61 +828,104 @@ class MediaActivity : SimpleActivity(), MediaAdapter.MediaOperationsListener {
} else {
val isVideo = path.isVideoFast()
if (isVideo) {
openPath(path, false)
val extras = HashMap<String, Boolean>()
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<Medium>, isFromCache: Boolean = false) {
val mediaToInsert = media.clone() as ArrayList<Medium>
Thread {
mLatestMediaId = getLatestMediaId()
mLatestMediaDateId = getLatestMediaByDateId()
if (!isFromCache) {
galleryDB.MediumDao().insertAll(mediaToInsert)
}
}.start()
private fun gotMedia(media: ArrayList<ThumbnailItem>, isFromCache: Boolean) {
mIsGettingMedia = false
checkLastMediaChanged()
mMedia = media
runOnUiThread {
media_refresh_layout.isRefreshing = false
media_empty_text_label.beVisibleIf(media.isEmpty() && !isFromCache)
media_empty_text.beVisibleIf(media.isEmpty() && !isFromCache)
media_grid.beVisibleIf(media_empty_text_label.isGone())
media_empty_text_placeholder.beVisibleIf(media.isEmpty() && !isFromCache)
media_empty_text_placeholder_2.beVisibleIf(media.isEmpty() && !isFromCache)
val allowHorizontalScroll = config.scrollHorizontally && config.viewTypeFiles == VIEW_TYPE_GRID
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<FileDirItem>) {
val filtered = fileDirItems.filter { it.path.isImageVideoGif() } as 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<String>) {
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<FileDirItem>) {
deleteFiles(filtered) {
if (!it) {
toast(R.string.unknown_error_occurred)
return@deleteFiles
}
mMedia.removeAll { filtered.map { it.path }.contains(it.path) }
mMedia.removeAll { filtered.map { it.path }.contains((it as? Medium)?.path) }
Thread {
val mediumDao = galleryDB.MediumDao()
ensureBackgroundThread {
val useRecycleBin = config.useRecycleBin
filtered.forEach {
mediumDao.deleteMediumPath(it.path)
if (it.path.startsWith(recycleBinPath) || !useRecycleBin) {
deleteDBPath(it.path)
}
}
}.start()
}
if (mMedia.isEmpty()) {
deleteDirectoryIfEmpty()

View file

@ -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)
}
}
}

View file

@ -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
}
}

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.activities
package com.simplemobiletools.gallery.pro.activities
import android.os.Bundle

View file

@ -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
}

View file

@ -0,0 +1,361 @@
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.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_search.*
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<ThumbnailItem>()
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<Medium>, "")
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()
}
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()
measureRecyclerViewContent(mAllMedia)
} else if (mLastSearchedText.isEmpty()) {
(currAdapter as MediaAdapter).updateMedia(mAllMedia)
measureRecyclerViewContent(mAllMedia)
} else {
textChanged(mLastSearchedText)
}
setupScrollDirection()
}
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.allowBubbleDisplay = config.showInfoBubble
media_horizontal_fastscroller.setViews(media_grid) {
media_horizontal_fastscroller.updateBubbleText(getBubbleTextItem(it, sorting))
}
} else {
media_vertical_fastscroller.allowBubbleDisplay = config.showInfoBubble
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<ThumbnailItem>) {
media_grid.onGlobalLayout {
if (config.scrollHorizontally) {
calculateContentWidth(media)
} else {
calculateContentHeight(media)
}
}
}
private fun calculateContentWidth(media: ArrayList<ThumbnailItem>) {
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<ThumbnailItem>) {
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<ThumbnailItem>
}
runOnUiThread {
setupAdapter()
}
startAsyncTask(false)
}
}
private fun startAsyncTask(updateItems: Boolean) {
mCurrAsyncTask?.stopFetching()
mCurrAsyncTask = GetMediaAsynctask(applicationContext, "", showAll = true) {
mAllMedia = it.clone() as ArrayList<ThumbnailItem>
if (updateItems) {
textChanged(mLastSearchedText)
}
}
mCurrAsyncTask!!.execute()
}
override fun refreshItems() {
startAsyncTask(true)
}
override fun tryDeleteFiles(fileDirItems: ArrayList<FileDirItem>) {
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<String>) {
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<FileDirItem>) {
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<String>) {
}
}

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.activities
package com.simplemobiletools.gallery.pro.activities
import android.annotation.SuppressLint
import android.app.Activity
@ -10,13 +10,15 @@ import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.isActivityDestroyed
import com.simplemobiletools.commons.extensions.checkAppSideloading
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.helpers.isNougatPlus
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.gallery.R
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
@ -28,7 +30,11 @@ class SetWallpaperActivity : SimpleActivity(), CropImageView.OnCropImageComplete
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)
@ -39,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()
@ -58,36 +79,25 @@ 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.apply {
findItem(R.id.portrait_aspect_ratio).isVisible = isLandscapeRatio
findItem(R.id.landscape_aspect_ratio).isVisible = !isLandscapeRatio
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.save -> confirmWallpaper()
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")
@ -109,12 +119,12 @@ class SetWallpaperActivity : SimpleActivity(), CropImageView.OnCropImageComplete
@SuppressLint("NewApi")
override fun onCropImageComplete(view: CropImageView?, result: CropImageView.CropResult) {
if (isActivityDestroyed())
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()
@ -132,7 +142,7 @@ class SetWallpaperActivity : SimpleActivity(), CropImageView.OnCropImageComplete
setResult(Activity.RESULT_CANCELED)
}
finish()
}.start()
}
} else {
toast("${getString(R.string.image_editing_failed)}: ${result.error.message}")
}

View file

@ -0,0 +1,862 @@
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.ManageBottomActionsDialog
import com.simplemobiletools.gallery.pro.dialogs.ManageExtendedDetailsDialog
import com.simplemobiletools.gallery.pro.extensions.*
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()
setupAnimateGifs()
setupMaxBrightness()
setupCropThumbnails()
setupDarkBackground()
setupScrollHorizontally()
setupScreenRotation()
setupHideSystemUI()
setupHiddenItemPasswordProtection()
setupAppPasswordProtection()
setupFileDeletionPasswordProtection()
setupDeleteEmptyFolders()
setupAllowPhotoGestures()
setupAllowVideoGestures()
setupAllowDownGesture()
setupAllowRotatingWithGestures()
setupShowNotch()
setupBottomActions()
setupThumbnailVideoDuration()
setupThumbnailFileTypes()
setupShowMediaCount()
setupKeepLastModified()
setupShowInfoBubble()
setupEnablePullToRefresh()
setupAllowZoomingImages()
setupShowHighestQuality()
setupAllowOneToOneZoom()
setupAllowInstantChange()
setupShowExtendedDetails()
setupHideExtendedDetails()
setupManageExtendedDetails()
setupSkipDeleteConfirmation()
setupManageBottomActions()
setupUseRecycleBin()
setupShowRecycleBin()
setupShowRecycleBinLast()
setupEmptyRecycleBin()
updateTextColors(settings_holder)
setupSectionColors()
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 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 setupThumbnailVideoDuration() {
settings_show_thumbnail_video_duration.isChecked = config.showThumbnailVideoDuration
settings_show_thumbnail_video_duration_holder.setOnClickListener {
settings_show_thumbnail_video_duration.toggle()
config.showThumbnailVideoDuration = settings_show_thumbnail_video_duration.isChecked
}
}
private fun setupThumbnailFileTypes() {
settings_show_thumbnail_file_types.isChecked = config.showThumbnailFileTypes
settings_show_thumbnail_file_types_holder.setOnClickListener {
settings_show_thumbnail_file_types.toggle()
config.showThumbnailFileTypes = settings_show_thumbnail_file_types.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 setupAllowPhotoGestures() {
settings_allow_photo_gestures.isChecked = config.allowPhotoGestures
settings_allow_photo_gestures_holder.setOnClickListener {
settings_allow_photo_gestures.toggle()
config.allowPhotoGestures = settings_allow_photo_gestures.isChecked
}
}
private fun setupAllowVideoGestures() {
settings_allow_video_gestures.isChecked = config.allowVideoGestures
settings_allow_video_gestures_holder.setOnClickListener {
settings_allow_video_gestures.toggle()
config.allowVideoGestures = settings_allow_video_gestures.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 setupShowMediaCount() {
settings_show_media_count.isChecked = config.showMediaCount
settings_show_media_count_holder.setOnClickListener {
settings_show_media_count.toggle()
config.showMediaCount = settings_show_media_count.isChecked
}
}
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 setupShowInfoBubble() {
settings_show_info_bubble.isChecked = config.showInfoBubble
settings_show_info_bubble_holder.setOnClickListener {
settings_show_info_bubble.toggle()
config.showInfoBubble = settings_show_info_bubble.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 setupExportSettings() {
settings_export_holder.setOnClickListener {
val configItems = LinkedHashMap<String, Any>().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_MEDIA_COUNT, config.showMediaCount)
put(SHOW_INFO_BUBBLE, config.showInfoBubble)
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)
}
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<String, Any>()
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_MEDIA_COUNT -> config.showMediaCount = value.toBoolean()
SHOW_INFO_BUBBLE -> config.showInfoBubble = 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()
ALBUM_COVERS -> {
val existingCovers = config.parseAlbumCovers()
val existingCoverPaths = existingCovers.map { it.path }.toMutableList() as ArrayList<String>
val listType = object : TypeToken<List<AlbumCover>>() {}.type
val covers = Gson().fromJson<ArrayList<AlbumCover>>(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()
}
}
}

View file

@ -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)
}
}
}
}

View file

@ -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<Favorite>()
val favoritePaths = mediaDB.getFavorites().map { it.path }.toMutableList() as ArrayList<String>
favoritePaths.forEach {
favorites.add(getFavoriteFromPath(it))
}
favoritesDB.insertAll(favorites)
runOnUiThread {
launchActivity()
}
}
}
}
}
private fun launchActivity() {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.activities
package com.simplemobiletools.gallery.pro.activities
import android.os.Bundle

View file

@ -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) {}
}

View file

@ -0,0 +1,180 @@
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.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.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<Directory>()
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 {
loadJpg(path, config_image, config.cropThumbnails)
}
}
}
}
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()
}
}

View file

@ -0,0 +1,709 @@
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.view.Menu
import android.view.View
import android.view.ViewGroup
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.SHOW_ALL_TABS
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.helpers.isOreoPlus
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.view.dir_check
import kotlinx.android.synthetic.main.directory_item_grid.view.dir_location
import kotlinx.android.synthetic.main.directory_item_grid.view.dir_lock
import kotlinx.android.synthetic.main.directory_item_grid.view.dir_name
import kotlinx.android.synthetic.main.directory_item_grid.view.dir_pin
import kotlinx.android.synthetic.main.directory_item_grid.view.dir_thumbnail
import kotlinx.android.synthetic.main.directory_item_grid.view.photo_cnt
import kotlinx.android.synthetic.main.directory_item_list.view.*
import java.io.File
class DirectoryAdapter(activity: BaseSimpleActivity, var dirs: ArrayList<Directory>, 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 showMediaCount = config.showMediaCount
private var animateGifs = config.animateGifs
private var cropThumbnails = config.cropThumbnails
private var groupDirectSubfolders = config.groupDirectSubfolders
private var currentDirectoriesHash = dirs.hashCode()
private var lockedFolderPaths = ArrayList<String>()
init {
setupDragListener(true)
fillLockedFolders()
}
override fun getActionMenuId() = R.menu.cab_directories
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutType = if (isListViewType) R.layout.directory_item_list else R.layout.directory_item_grid
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<String>) {
menu.findItem(R.id.cab_hide).isVisible = selectedPaths.any { !it.doesThisOrParentHaveNoMedia() }
menu.findItem(R.id.cab_unhide).isVisible = selectedPaths.any { it.doesThisOrParentHaveNoMedia() }
}
private fun checkPinBtnVisibility(menu: Menu, selectedPaths: ArrayList<String>) {
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 && !activity.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) && !activity.config.isFolderProtected(it) } as ArrayList<String>
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 || !activity.config.isFolderProtected(it)) }.forEach {
val path = it
activity.handleLockedFolderOpening(path) { success ->
if (success) {
if (path.containsNoMedia()) {
activity.removeNoMedia(path) {
if (activity.config.shouldShowHidden) {
updateFolderNames()
} else {
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}
}
}
}
}
}
}
}
private fun hideFolders(paths: ArrayList<String>) {
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 = activity.config.includedFolders
val hidden = activity.getString(R.string.hidden)
dirs.forEach {
it.name = activity.checkAppendingHidden(it.path, hidden, includedFolders)
}
listener?.updateDirectories(dirs.toMutableList() as ArrayList)
activity.runOnUiThread {
updateDirs(dirs)
}
}
private fun hideFolder(path: String) {
activity.addNoMedia(path) {
if (activity.config.shouldShowHidden) {
updateFolderNames()
} else {
val affectedPositions = ArrayList<Int>()
val includedFolders = activity.config.includedFolders
val newDirs = dirs.filterIndexed { index, directory ->
val removeDir = directory.path.doesThisOrParentHaveNoMedia() && !includedFolders.contains(directory.path)
if (removeDir) {
affectedPositions.add(index)
}
!removeDir
} as ArrayList<Directory>
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) {
activity.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<String>()
val showHidden = activity.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<FileDirItem>
activity.tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
val destinationPath = it
val newPaths = fileDirItems.map { "$destinationPath/${it.name}" }.toMutableList() as java.util.ArrayList<String>
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<File>(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 { !activity.config.isFolderProtected(it.absolutePath) }.toMutableList() as ArrayList<File>
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<AlbumCover>) {
activity.config.albumCovers = Gson().toJson(albumCovers)
finishActMode()
listener?.refreshItems()
}
private fun getSelectedItems() = selectedKeys.mapNotNull { getItemWithKey(it) } as ArrayList<Directory>
private fun getSelectedPaths() = getSelectedItems().map { it.path } as ArrayList<String>
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<Directory>) {
val directories = newDirs.clone() as ArrayList<Directory>
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()
}
fun updateShowMediaCount(showMediaCount: Boolean) {
this.showMediaCount = showMediaCount
notifyDataSetChanged()
}
private fun setupView(view: View, directory: Directory) {
val isSelected = selectedKeys.contains(directory.path.hashCode())
view.apply {
dir_name.text = if (groupDirectSubfolders && directory.subfoldersCount > 1) "${directory.name} (${directory.subfoldersCount})" else directory.name
dir_path?.text = "${directory.path.substringBeforeLast("/")}/"
photo_cnt.text = directory.subfoldersMediaCount.toString()
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 (lockedFolderPaths.contains(directory.path)) {
dir_lock.beVisible()
dir_lock.background = ColorDrawable(config.backgroundColor)
dir_lock.applyColorFilter(config.backgroundColor.getContrastColor())
} else {
dir_lock.beGone()
activity.loadImage(thumbnailType, directory.tmb, dir_thumbnail, scrollHorizontally, animateGifs, cropThumbnails)
}
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.beVisibleIf(showMediaCount)
if (isListViewType) {
dir_name.setTextColor(textColor)
dir_path.setTextColor(textColor)
photo_cnt.setTextColor(textColor)
dir_pin.applyColorFilter(textColor)
dir_location.applyColorFilter(textColor)
}
}
}
}

View file

@ -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<FilterItem>, val itemClick: (Int) -> Unit) : RecyclerView.Adapter<FiltersAdapter.ViewHolder>() {
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
}
}
}

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.adapters
package com.simplemobiletools.gallery.pro.adapters
import android.view.Menu
import android.view.View
@ -7,8 +7,8 @@ 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.R
import com.simplemobiletools.gallery.extensions.config
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.*
@ -25,12 +25,6 @@ class ManageFoldersAdapter(activity: BaseSimpleActivity, var folders: ArrayList<
override fun prepareActionMode(menu: Menu) {}
override fun prepareItemSelection(view: View) {}
override fun markItemSelection(select: Boolean, view: View?) {
view?.manage_folder_holder?.isSelected = select
}
override fun actionItemPressed(id: Int) {
when (id) {
R.id.cab_remove -> removeSelection()
@ -39,20 +33,33 @@ class ManageFoldersAdapter(activity: BaseSimpleActivity, var folders: ArrayList<
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]
val view = holder.bindView(folder) { itemView, adapterPosition ->
holder.bindView(folder, true, true) { itemView, adapterPosition ->
setupView(itemView, folder)
}
bindViewHolder(holder, position, view)
bindViewHolder(holder)
}
override fun getItemCount() = folders.size
private fun getSelectedItems() = folders.filter { selectedKeys.contains(it.hashCode()) } as ArrayList<String>
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)
@ -61,20 +68,20 @@ class ManageFoldersAdapter(activity: BaseSimpleActivity, var folders: ArrayList<
}
private fun removeSelection() {
val removeFolders = ArrayList<String>(selectedPositions.size)
val removeFolders = ArrayList<String>(selectedKeys.size)
val positions = getSelectedItemPositions()
selectedPositions.sortedDescending().forEach {
val folder = folders[it]
removeFolders.add(folder)
getSelectedItems().forEach {
removeFolders.add(it)
if (isShowingExcludedFolders) {
config.removeExcludedFolder(folder)
config.removeExcludedFolder(it)
} else {
config.removeIncludedFolder(folder)
config.removeIncludedFolder(it)
}
}
folders.removeAll(removeFolders)
removeSelectedItems()
removeSelectedItems(positions)
if (folders.isEmpty()) {
listener?.refreshItems()
}

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.adapters
package com.simplemobiletools.gallery.pro.adapters
import android.view.Menu
import android.view.View
@ -8,9 +8,9 @@ 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.R
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.extensions.removeNoMedia
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.*
@ -27,12 +27,6 @@ class ManageHiddenFoldersAdapter(activity: BaseSimpleActivity, var folders: Arra
override fun prepareActionMode(menu: Menu) {}
override fun prepareItemSelection(view: View) {}
override fun markItemSelection(select: Boolean, view: View?) {
view?.manage_folder_holder?.isSelected = select
}
override fun actionItemPressed(id: Int) {
when (id) {
R.id.cab_unhide -> tryUnhideFolders()
@ -41,20 +35,33 @@ class ManageHiddenFoldersAdapter(activity: BaseSimpleActivity, var folders: Arra
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]
val view = holder.bindView(folder) { itemView, adapterPosition ->
holder.bindView(folder, true, true) { itemView, adapterPosition ->
setupView(itemView, folder)
}
bindViewHolder(holder, position, view)
bindViewHolder(holder)
}
override fun getItemCount() = folders.size
private fun getSelectedItems() = folders.filter { selectedKeys.contains(it.hashCode()) } as ArrayList<String>
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)
@ -63,18 +70,20 @@ class ManageHiddenFoldersAdapter(activity: BaseSimpleActivity, var folders: Arra
}
private fun tryUnhideFolders() {
val removeFolders = ArrayList<String>(selectedPositions.size)
val removeFolders = ArrayList<String>(selectedKeys.size)
val sdCardPaths = ArrayList<String>()
selectedPositions.forEach {
if (activity.isPathOnSD(folders[it])) {
sdCardPaths.add(folders[it])
getSelectedItems().forEach {
if (activity.isPathOnSD(it)) {
sdCardPaths.add(it)
}
}
if (sdCardPaths.isNotEmpty()) {
activity.handleSAFDialog(sdCardPaths.first()) {
unhideFolders(removeFolders)
if (it) {
unhideFolders(removeFolders)
}
}
} else {
unhideFolders(removeFolders)
@ -82,14 +91,14 @@ class ManageHiddenFoldersAdapter(activity: BaseSimpleActivity, var folders: Arra
}
private fun unhideFolders(removeFolders: ArrayList<String>) {
selectedPositions.sortedDescending().forEach {
val folder = folders[it]
removeFolders.add(folder)
activity.removeNoMedia(folder)
val position = getSelectedItemPositions()
getSelectedItems().forEach {
removeFolders.add(it)
activity.removeNoMedia(it)
}
folders.removeAll(removeFolders)
removeSelectedItems()
removeSelectedItems(position)
if (folders.isEmpty()) {
listener?.refreshItems()
}

View file

@ -0,0 +1,569 @@
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.ensureBackgroundThread
import com.simplemobiletools.commons.helpers.isOreoPlus
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: MutableList<ThumbnailItem>, 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<String>()
private var rotatedImagePaths = ArrayList<String>()
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<String>
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<Medium>) {
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<Medium>) {
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()) {
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<String>
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<FileDirItem>(selectedKeys.size)
val removeMedia = ArrayList<Medium>(selectedKeys.size)
val positions = getSelectedItemPositions()
getSelectedItems().forEach {
fileDirItems.add(FileDirItem(it.path, it.name))
removeMedia.add(it)
}
media.removeAll(removeMedia)
listener?.tryDeleteFiles(fileDirItems)
removeSelectedItems(positions)
}
}
private fun getSelectedItems() = selectedKeys.mapNotNull { getItemWithKey(it) } as ArrayList<Medium>
private fun getSelectedPaths() = getSelectedItems().map { it.path } as ArrayList<String>
private fun getFirstSelectedItemPath() = getItemWithKey(selectedKeys.first())?.path
private fun getItemWithKey(key: Int): Medium? = media.firstOrNull { (it as? Medium)?.path?.hashCode() == key } as? Medium
fun updateMedia(newMedia: ArrayList<ThumbnailItem>) {
val thumbnailItems = newMedia.clone() as ArrayList<ThumbnailItem>
if (thumbnailItems.hashCode() != currentMediaHash) {
currentMediaHash = thumbnailItems.hashCode()
Handler().postDelayed({
media = thumbnailItems
enableInstantLoad()
notifyDataSetChanged()
finishActMode()
}, 100L)
}
}
fun updateDisplayFilenames(displayFilenames: Boolean) {
this.displayFilenames = displayFilenames
enableInstantLoad()
notifyDataSetChanged()
}
fun updateAnimateGifs(animateGifs: Boolean) {
this.animateGifs = animateGifs
notifyDataSetChanged()
}
fun updateCropThumbnails(cropThumbnails: Boolean) {
this.cropThumbnails = cropThumbnails
notifyDataSetChanged()
}
fun updateShowFileTypes(showFileTypes: Boolean) {
this.showFileTypes = showFileTypes
notifyDataSetChanged()
}
private fun enableInstantLoad() {
loadImageInstantly = true
delayHandler.postDelayed({
loadImageInstantly = false
}, INSTANT_LOAD_DURATION)
}
fun getItemBubbleText(position: Int, sorting: Int, dateFormat: String, timeFormat: String): String {
return (media[position] as? Medium)?.getBubbleText(sorting, activity, dateFormat, timeFormat) ?: ""
}
private fun setupThumbnail(view: View, medium: Medium) {
val isSelected = selectedKeys.contains(medium.path.hashCode())
view.apply {
play_outline.beVisibleIf(medium.isVideo() || medium.isPortrait())
if (medium.isVideo()) {
play_outline.setImageResource(R.drawable.ic_play_outline_vector)
play_outline.beVisible()
} else if (medium.isPortrait()) {
play_outline.setImageResource(R.drawable.ic_portrait_photo_vector)
play_outline.beVisibleIf(showFileTypes)
}
if (showFileTypes && (medium.isGIF() || medium.isRaw() || medium.isSVG())) {
file_type.setText(when (medium.type) {
TYPE_GIFS -> R.string.gif
TYPE_RAWS -> R.string.raw
else -> R.string.svg
})
file_type.beVisible()
} else {
file_type.beGone()
}
medium_name.beVisibleIf(displayFilenames || isListViewType)
medium_name.text = medium.name
medium_name.tag = medium.path
val showVideoDuration = medium.isVideo() && config.showThumbnailVideoDuration
if (showVideoDuration) {
video_duration.text = medium.videoDuration.getFormattedDuration()
}
video_duration.beVisibleIf(showVideoDuration)
medium_check?.beVisibleIf(isSelected)
if (isSelected) {
medium_check?.background?.applyColorFilter(primaryColor)
}
var path = medium.path
if (hasOTGConnected && context.isPathOnOTG(path)) {
path = path.getOTGPublicPath(context)
}
if (loadImageInstantly) {
activity.loadImage(medium.type, path, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails, rotatedImagePaths)
} else {
medium_thumbnail.setImageDrawable(null)
medium_thumbnail.isHorizontalScrolling = scrollHorizontally
delayHandler.postDelayed({
val isVisible = visibleItemPaths.contains(medium.path)
if (isVisible) {
activity.loadImage(medium.type, path, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails, rotatedImagePaths)
}
}, IMAGE_LOAD_DELAY)
}
if (isListViewType) {
medium_name.setTextColor(textColor)
play_outline.applyColorFilter(textColor)
}
}
}
private fun setupSection(view: View, section: ThumbnailSection) {
view.apply {
thumbnail_section.text = section.title
thumbnail_section.setTextColor(textColor)
}
}
}

View file

@ -1,27 +1,31 @@
package com.simplemobiletools.gallery.adapters
package com.simplemobiletools.gallery.pro.adapters
import android.os.Bundle
import android.os.Parcelable
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.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
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.PagerAdapter
import com.simplemobiletools.gallery.pro.activities.ViewPagerActivity
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.MEDIUM
import com.simplemobiletools.gallery.pro.helpers.SHOULD_INIT_FRAGMENT
import com.simplemobiletools.gallery.pro.models.Medium
class MyPagerAdapter(val activity: ViewPagerActivity, fm: FragmentManager, val media: MutableList<Medium>) : FragmentStatePagerAdapter(fm) {
private val fragments = HashMap<Int, ViewPagerFragment>()
var shouldInitFragment = true
override fun getCount() = media.size
override fun getItem(position: Int): Fragment {
val medium = media[position]
val bundle = Bundle()
bundle.putSerializable(MEDIUM, medium)
bundle.putBoolean(SHOULD_INIT_FRAGMENT, shouldInitFragment)
val fragment = if (medium.isVideo()) {
VideoFragment()
} else {

View file

@ -0,0 +1,88 @@
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.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.signature.ObjectKey
import com.simplemobiletools.commons.extensions.getFileKey
import com.simplemobiletools.gallery.pro.R
import kotlinx.android.synthetic.main.portrait_photo_item.view.*
import java.util.*
class PortraitPhotosAdapter(val context: Context, val photos: ArrayList<String>, val sideElementWidth: Int, val itemClick: (Int, Int) -> Unit) :
RecyclerView.Adapter<PortraitPhotosAdapter.ViewHolder>() {
var currentSelectionIndex = -1
var views = HashMap<Int, View>()
private var strokeBackground = context.resources.getDrawable(R.drawable.stroke_background)
private val itemWidth = context.resources.getDimension(R.dimen.portrait_photos_stripe_height).toInt()
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindView(photos[position], position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.portrait_photo_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount() = photos.size
fun setCurrentPhoto(position: Int) {
if (currentSelectionIndex != position) {
currentSelectionIndex = position
notifyDataSetChanged()
}
}
fun performClickOn(position: Int) {
views[position]?.performClick()
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindView(photo: String, position: Int): View {
itemView.apply {
portrait_photo_item_thumbnail.layoutParams.width = if (position == 0 || position == photos.size - 1) {
sideElementWidth
} else {
itemWidth
}
portrait_photo_item_thumbnail.background = if (photo.isEmpty() || position != currentSelectionIndex) {
null
} else {
strokeBackground
}
val options = RequestOptions()
.signature(ObjectKey(photo.getFileKey()))
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.centerCrop()
Glide.with(context)
.load(photo)
.transition(DrawableTransitionOptions.withCrossFade())
.apply(options)
.into(portrait_photo_item_thumbnail)
if (photo.isNotEmpty()) {
isClickable = true
views[position] = this
setOnClickListener {
itemClick(position, x.toInt())
setCurrentPhoto(position)
}
} else {
isClickable = false
}
}
return itemView
}
}
}

View file

@ -0,0 +1,60 @@
package com.simplemobiletools.gallery.pro.asynctasks
import android.content.Context
import android.os.AsyncTask
import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
import com.simplemobiletools.commons.helpers.SORT_BY_DATE_TAKEN
import com.simplemobiletools.commons.helpers.SORT_BY_SIZE
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.extensions.getFavoritePaths
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.models.Medium
import com.simplemobiletools.gallery.pro.models.ThumbnailItem
import java.util.*
class GetMediaAsynctask(val context: Context, val mPath: String, val isPickImage: Boolean = false, val isPickVideo: Boolean = false,
val showAll: Boolean, val callback: (media: ArrayList<ThumbnailItem>) -> Unit) :
AsyncTask<Void, Void, ArrayList<ThumbnailItem>>() {
private val mediaFetcher = MediaFetcher(context)
override fun doInBackground(vararg params: Void): ArrayList<ThumbnailItem> {
val pathToUse = if (showAll) SHOW_ALL else mPath
val folderGrouping = context.config.getFolderGrouping(pathToUse)
val fileSorting = context.config.getFolderSorting(pathToUse)
val getProperDateTaken = fileSorting and SORT_BY_DATE_TAKEN != 0 ||
folderGrouping and GROUP_BY_DATE_TAKEN_DAILY != 0 ||
folderGrouping and GROUP_BY_DATE_TAKEN_MONTHLY != 0
val getProperLastModified = fileSorting and SORT_BY_DATE_MODIFIED != 0 ||
folderGrouping and GROUP_BY_LAST_MODIFIED_DAILY != 0 ||
folderGrouping and GROUP_BY_LAST_MODIFIED_MONTHLY != 0
val getProperFileSize = fileSorting and SORT_BY_SIZE != 0
val favoritePaths = context.getFavoritePaths()
val getVideoDurations = context.config.showThumbnailVideoDuration
val media = if (showAll) {
val foldersToScan = mediaFetcher.getFoldersToScan().filter { it != RECYCLE_BIN && it != FAVORITES && !context.config.isFolderProtected(it) }
val media = ArrayList<Medium>()
foldersToScan.forEach {
val newMedia = mediaFetcher.getFilesFrom(it, isPickImage, isPickVideo, getProperDateTaken, getProperLastModified, getProperFileSize, favoritePaths, getVideoDurations)
media.addAll(newMedia)
}
mediaFetcher.sortMedia(media, context.config.getFolderSorting(SHOW_ALL))
media
} else {
mediaFetcher.getFilesFrom(mPath, isPickImage, isPickVideo, getProperDateTaken, getProperLastModified, getProperFileSize, favoritePaths, getVideoDurations)
}
return mediaFetcher.groupMedia(media, pathToUse)
}
override fun onPostExecute(media: ArrayList<ThumbnailItem>) {
super.onPostExecute(media)
callback(media)
}
fun stopFetching() {
mediaFetcher.shouldStop = true
cancel(true)
}
}

View file

@ -0,0 +1,78 @@
package com.simplemobiletools.gallery.pro.databases
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.simplemobiletools.gallery.pro.interfaces.*
import com.simplemobiletools.gallery.pro.models.*
@Database(entities = [Directory::class, Medium::class, Widget::class, DateTaken::class, Favorite::class], version = 8)
abstract class GalleryDatabase : RoomDatabase() {
abstract fun DirectoryDao(): DirectoryDao
abstract fun MediumDao(): MediumDao
abstract fun WidgetsDao(): WidgetsDao
abstract fun DateTakensDao(): DateTakensDao
abstract fun FavoritesDao(): FavoritesDao
companion object {
private var db: GalleryDatabase? = null
fun getInstance(context: Context): GalleryDatabase {
if (db == null) {
synchronized(GalleryDatabase::class) {
if (db == null) {
db = Room.databaseBuilder(context.applicationContext, GalleryDatabase::class.java, "gallery.db")
.fallbackToDestructiveMigration()
.addMigrations(MIGRATION_4_5)
.addMigrations(MIGRATION_5_6)
.addMigrations(MIGRATION_6_7)
.addMigrations(MIGRATION_7_8)
.build()
}
}
}
return db!!
}
fun destroyInstance() {
db = null
}
private val MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE media ADD COLUMN video_duration INTEGER default 0 NOT NULL")
}
}
private val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `widgets` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `widget_id` INTEGER NOT NULL, `folder_path` TEXT NOT NULL)")
database.execSQL("CREATE UNIQUE INDEX `index_widgets_widget_id` ON `widgets` (`widget_id`)")
}
}
private val MIGRATION_6_7 = object : Migration(6, 7) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `date_takens` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `full_path` TEXT NOT NULL, `filename` TEXT NOT NULL, `parent_path` TEXT NOT NULL, `date_taken` INTEGER NOT NULL, `last_fixed` INTEGER NOT NULL)")
database.execSQL("CREATE TABLE IF NOT EXISTS `favorites` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `full_path` TEXT NOT NULL, `filename` TEXT NOT NULL, `parent_path` TEXT NOT NULL)")
database.execSQL("CREATE UNIQUE INDEX `index_date_takens_full_path` ON `date_takens` (`full_path`)")
database.execSQL("CREATE UNIQUE INDEX `index_favorites_full_path` ON `favorites` (`full_path`)")
}
}
private val MIGRATION_7_8 = object : Migration(7, 8) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE directories ADD COLUMN sort_value TEXT default '' NOT NULL")
}
}
}
}

View file

@ -0,0 +1,90 @@
package com.simplemobiletools.gallery.pro.dialogs
import android.content.DialogInterface
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.*
import kotlinx.android.synthetic.main.dialog_change_grouping.view.*
class ChangeGroupingDialog(val activity: BaseSimpleActivity, val path: String = "", val callback: () -> Unit) :
DialogInterface.OnClickListener {
private var currGrouping = 0
private var config = activity.config
private val pathToUse = if (path.isEmpty()) SHOW_ALL else path
private var view: View
init {
view = activity.layoutInflater.inflate(R.layout.dialog_change_grouping, null).apply {
grouping_dialog_use_for_this_folder.isChecked = config.hasCustomGrouping(pathToUse)
grouping_dialog_radio_folder.beVisibleIf(path.isEmpty())
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, this)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this, R.string.group_by)
}
currGrouping = config.getFolderGrouping(pathToUse)
setupGroupRadio()
setupOrderRadio()
}
private fun setupGroupRadio() {
val groupingRadio = view.grouping_dialog_radio_grouping
val groupBtn = when {
currGrouping and GROUP_BY_NONE != 0 -> groupingRadio.grouping_dialog_radio_none
currGrouping and GROUP_BY_LAST_MODIFIED_DAILY != 0 -> groupingRadio.grouping_dialog_radio_last_modified_daily
currGrouping and GROUP_BY_LAST_MODIFIED_MONTHLY != 0 -> groupingRadio.grouping_dialog_radio_last_modified_monthly
currGrouping and GROUP_BY_DATE_TAKEN_DAILY != 0 -> groupingRadio.grouping_dialog_radio_date_taken_daily
currGrouping and GROUP_BY_DATE_TAKEN_MONTHLY != 0 -> groupingRadio.grouping_dialog_radio_date_taken_monthly
currGrouping and GROUP_BY_FILE_TYPE != 0 -> groupingRadio.grouping_dialog_radio_file_type
currGrouping and GROUP_BY_EXTENSION != 0 -> groupingRadio.grouping_dialog_radio_extension
else -> groupingRadio.grouping_dialog_radio_folder
}
groupBtn.isChecked = true
}
private fun setupOrderRadio() {
val orderRadio = view.grouping_dialog_radio_order
var orderBtn = orderRadio.grouping_dialog_radio_ascending
if (currGrouping and GROUP_DESCENDING != 0) {
orderBtn = orderRadio.grouping_dialog_radio_descending
}
orderBtn.isChecked = true
}
override fun onClick(dialog: DialogInterface, which: Int) {
val groupingRadio = view.grouping_dialog_radio_grouping
var grouping = when (groupingRadio.checkedRadioButtonId) {
R.id.grouping_dialog_radio_none -> GROUP_BY_NONE
R.id.grouping_dialog_radio_last_modified_daily -> GROUP_BY_LAST_MODIFIED_DAILY
R.id.grouping_dialog_radio_last_modified_monthly -> GROUP_BY_LAST_MODIFIED_MONTHLY
R.id.grouping_dialog_radio_date_taken_daily -> GROUP_BY_DATE_TAKEN_DAILY
R.id.grouping_dialog_radio_date_taken_monthly -> GROUP_BY_DATE_TAKEN_MONTHLY
R.id.grouping_dialog_radio_file_type -> GROUP_BY_FILE_TYPE
R.id.grouping_dialog_radio_extension -> GROUP_BY_EXTENSION
else -> GROUP_BY_FOLDER
}
if (view.grouping_dialog_radio_order.checkedRadioButtonId == R.id.grouping_dialog_radio_descending) {
grouping = grouping or GROUP_DESCENDING
}
if (view.grouping_dialog_use_for_this_folder.isChecked) {
config.saveFolderGrouping(pathToUse, grouping)
} else {
config.removeFolderGrouping(pathToUse)
config.groupBy = grouping
}
callback()
}
}

View file

@ -1,28 +1,37 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.content.DialogInterface
import android.support.v7.app.AlertDialog
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.isVisible
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.SHOW_ALL
import kotlinx.android.synthetic.main.dialog_change_sorting.view.*
class ChangeSortingDialog(val activity: BaseSimpleActivity, val isDirectorySorting: Boolean, showFolderCheckbox: Boolean,
class ChangeSortingDialog(val activity: BaseSimpleActivity, val isDirectorySorting: Boolean, val showFolderCheckbox: Boolean,
val path: String = "", val callback: () -> Unit) :
DialogInterface.OnClickListener {
private var currSorting = 0
private var config = activity.config
private var pathToUse = if (!isDirectorySorting && path.isEmpty()) SHOW_ALL else path
private var view: View
init {
currSorting = if (isDirectorySorting) config.directorySorting else config.getFolderSorting(pathToUse)
view = activity.layoutInflater.inflate(R.layout.dialog_change_sorting, null).apply {
use_for_this_folder_divider.beVisibleIf(showFolderCheckbox)
use_for_this_folder_divider.beVisibleIf(showFolderCheckbox || (currSorting and SORT_BY_NAME != 0 || currSorting and SORT_BY_PATH != 0))
sorting_dialog_numeric_sorting.beVisibleIf(showFolderCheckbox && (currSorting and SORT_BY_NAME != 0 || currSorting and SORT_BY_PATH != 0))
sorting_dialog_numeric_sorting.isChecked = currSorting and SORT_USE_NUMERIC_VALUE != 0
sorting_dialog_use_for_this_folder.beVisibleIf(showFolderCheckbox)
sorting_dialog_use_for_this_folder.isChecked = config.hasCustomSorting(path)
sorting_dialog_use_for_this_folder.isChecked = config.hasCustomSorting(pathToUse)
sorting_dialog_bottom_note.beVisibleIf(!isDirectorySorting)
}
AlertDialog.Builder(activity)
@ -32,19 +41,24 @@ class ChangeSortingDialog(val activity: BaseSimpleActivity, val isDirectorySorti
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
sortingRadio.setOnCheckedChangeListener { group, checkedId ->
val isSortingByNameOrPath = checkedId == sortingRadio.sorting_dialog_radio_name.id || checkedId == sortingRadio.sorting_dialog_radio_path.id
view.sorting_dialog_numeric_sorting.beVisibleIf(isSortingByNameOrPath)
view.use_for_this_folder_divider.beVisibleIf(view.sorting_dialog_numeric_sorting.isVisible() || view.sorting_dialog_use_for_this_folder.isVisible())
}
val sortBtn = when {
currSorting and SORT_BY_PATH != 0 -> sortingRadio.sorting_dialog_radio_path
currSorting and SORT_BY_SIZE != 0 -> sortingRadio.sorting_dialog_radio_size
currSorting and SORT_BY_DATE_MODIFIED != 0 -> sortingRadio.sorting_dialog_radio_last_modified
currSorting and SORT_BY_DATE_TAKEN != 0 -> sortingRadio.sorting_dialog_radio_date_taken
currSorting and SORT_BY_RANDOM != 0 -> sortingRadio.sorting_dialog_radio_random
else -> sortingRadio.sorting_dialog_radio_name
}
sortBtn.isChecked = true
@ -67,6 +81,7 @@ class ChangeSortingDialog(val activity: BaseSimpleActivity, val isDirectorySorti
R.id.sorting_dialog_radio_path -> SORT_BY_PATH
R.id.sorting_dialog_radio_size -> SORT_BY_SIZE
R.id.sorting_dialog_radio_last_modified -> SORT_BY_DATE_MODIFIED
R.id.sorting_dialog_radio_random -> SORT_BY_RANDOM
else -> SORT_BY_DATE_TAKEN
}
@ -74,13 +89,17 @@ class ChangeSortingDialog(val activity: BaseSimpleActivity, val isDirectorySorti
sorting = sorting or SORT_DESCENDING
}
if (view.sorting_dialog_numeric_sorting.isChecked) {
sorting = sorting or SORT_USE_NUMERIC_VALUE
}
if (isDirectorySorting) {
config.directorySorting = sorting
} else {
if (view.sorting_dialog_use_for_this_folder.isChecked) {
config.saveFileSorting(path, sorting)
config.saveCustomSorting(pathToUse, sorting)
} else {
config.removeFileSorting(path)
config.removeCustomSorting(pathToUse)
config.sorting = sorting
}
}

View file

@ -0,0 +1,73 @@
package com.simplemobiletools.gallery.pro.dialogs
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.SHOW_ALL
import com.simplemobiletools.gallery.pro.helpers.VIEW_TYPE_GRID
import com.simplemobiletools.gallery.pro.helpers.VIEW_TYPE_LIST
import kotlinx.android.synthetic.main.dialog_change_view_type.view.*
class ChangeViewTypeDialog(val activity: BaseSimpleActivity, val fromFoldersView: Boolean, val path: String = "", val callback: () -> Unit) {
private var view: View
private var config = activity.config
private var pathToUse = if (path.isEmpty()) SHOW_ALL else path
init {
view = activity.layoutInflater.inflate(R.layout.dialog_change_view_type, null).apply {
val viewToCheck = if (fromFoldersView) {
if (config.viewTypeFolders == VIEW_TYPE_GRID) {
change_view_type_dialog_radio_grid.id
} else {
change_view_type_dialog_radio_list.id
}
} else {
val currViewType = config.getFolderViewType(pathToUse)
if (currViewType == VIEW_TYPE_GRID) {
change_view_type_dialog_radio_grid.id
} else {
change_view_type_dialog_radio_list.id
}
}
change_view_type_dialog_radio.check(viewToCheck)
change_view_type_dialog_group_direct_subfolders.apply {
beVisibleIf(fromFoldersView)
isChecked = config.groupDirectSubfolders
}
change_view_type_dialog_use_for_this_folder.apply {
beVisibleIf(!fromFoldersView)
isChecked = config.hasCustomViewType(pathToUse)
}
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
val viewType = if (view.change_view_type_dialog_radio.checkedRadioButtonId == view.change_view_type_dialog_radio_grid.id) VIEW_TYPE_GRID else VIEW_TYPE_LIST
if (fromFoldersView) {
config.viewTypeFolders = viewType
config.groupDirectSubfolders = view.change_view_type_dialog_group_direct_subfolders.isChecked
} else {
if (view.change_view_type_dialog_use_for_this_folder.isChecked) {
config.saveFolderViewType(pathToUse, viewType)
} else {
config.removeFolderViewType(pathToUse)
config.viewTypeFiles = viewType
}
}
callback()
}
}

View file

@ -0,0 +1,31 @@
package com.simplemobiletools.gallery.pro.dialogs
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import kotlinx.android.synthetic.main.dialog_confirm_delete_folder.view.*
class ConfirmDeleteFolderDialog(activity: Activity, message: String, warningMessage: String, val callback: () -> Unit) {
var dialog: AlertDialog
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_confirm_delete_folder, null)
view.message.text = message
view.message_warning.text = warningMessage
val builder = AlertDialog.Builder(activity)
.setPositiveButton(R.string.yes) { dialog, which -> dialogConfirmed() }
builder.setNegativeButton(R.string.no, null)
dialog = builder.create().apply {
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
dialog.dismiss()
callback()
}
}

View file

@ -0,0 +1,39 @@
package com.simplemobiletools.gallery.pro.dialogs
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.extensions.showKeyboard
import com.simplemobiletools.commons.extensions.value
import com.simplemobiletools.gallery.pro.R
import kotlinx.android.synthetic.main.dialog_custom_aspect_ratio.view.*
class CustomAspectRatioDialog(val activity: BaseSimpleActivity, val defaultCustomAspectRatio: Pair<Float, Float>?, val callback: (aspectRatio: Pair<Float, Float>) -> Unit) {
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_custom_aspect_ratio, null).apply {
aspect_ratio_width.setText(defaultCustomAspectRatio?.first?.toInt()?.toString() ?: "")
aspect_ratio_height.setText(defaultCustomAspectRatio?.second?.toInt()?.toString() ?: "")
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this) {
showKeyboard(view.aspect_ratio_width)
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val width = getViewValue(view.aspect_ratio_width)
val height = getViewValue(view.aspect_ratio_height)
callback(Pair(width, height))
dismiss()
}
}
}
}
private fun getViewValue(view: EditText): Float {
val textValue = view.value
return if (textValue.isEmpty()) 0f else textValue.toFloat()
}
}

View file

@ -1,9 +1,9 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.app.Activity
import android.support.v7.app.AlertDialog
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.pro.R
import kotlinx.android.synthetic.main.dialog_delete_with_remember.view.*
class DeleteWithRememberDialog(val activity: Activity, val message: String, val callback: (remember: Boolean) -> Unit) {
@ -13,7 +13,7 @@ class DeleteWithRememberDialog(val activity: Activity, val message: String, val
init {
view.delete_remember_title.text = message
val builder = AlertDialog.Builder(activity)
.setPositiveButton(R.string.yes, { dialog, which -> dialogConfirmed() })
.setPositiveButton(R.string.yes) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.no, null)
dialog = builder.create().apply {

View file

@ -1,15 +1,15 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.support.v7.app.AlertDialog
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.getBasePath
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import kotlinx.android.synthetic.main.dialog_exclude_folder.view.*
class ExcludeFolderDialog(val activity: BaseSimpleActivity, val selectedPaths: List<String>, val callback: () -> Unit) {
@ -34,11 +34,11 @@ class ExcludeFolderDialog(val activity: BaseSimpleActivity, val selectedPaths: L
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, { dialog, which -> dialogConfirmed() })
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {

View file

@ -1,13 +1,11 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.support.v7.app.AlertDialog
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.helpers.TYPE_GIFS
import com.simplemobiletools.gallery.helpers.TYPE_IMAGES
import com.simplemobiletools.gallery.helpers.TYPE_VIDEOS
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.*
import kotlinx.android.synthetic.main.dialog_filter_media.view.*
class FilterMediaDialog(val activity: BaseSimpleActivity, val callback: (result: Int) -> Unit) {
@ -19,10 +17,13 @@ class FilterMediaDialog(val activity: BaseSimpleActivity, val callback: (result:
filter_media_images.isChecked = filterMedia and TYPE_IMAGES != 0
filter_media_videos.isChecked = filterMedia and TYPE_VIDEOS != 0
filter_media_gifs.isChecked = filterMedia and TYPE_GIFS != 0
filter_media_raws.isChecked = filterMedia and TYPE_RAWS != 0
filter_media_svgs.isChecked = filterMedia and TYPE_SVGS != 0
filter_media_portraits.isChecked = filterMedia and TYPE_PORTRAITS != 0
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, { dialog, which -> dialogConfirmed() })
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this, R.string.filter_media)
@ -37,6 +38,16 @@ class FilterMediaDialog(val activity: BaseSimpleActivity, val callback: (result:
result += TYPE_VIDEOS
if (view.filter_media_gifs.isChecked)
result += TYPE_GIFS
if (view.filter_media_raws.isChecked)
result += TYPE_RAWS
if (view.filter_media_svgs.isChecked)
result += TYPE_SVGS
if (view.filter_media_portraits.isChecked)
result += TYPE_PORTRAITS
if (result == 0) {
result = getDefaultFileFilter()
}
activity.config.filterMedia = result
callback(result)

View file

@ -0,0 +1,80 @@
package com.simplemobiletools.gallery.pro.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.*
import kotlinx.android.synthetic.main.dialog_manage_bottom_actions.view.*
class ManageBottomActionsDialog(val activity: BaseSimpleActivity, val callback: (result: Int) -> Unit) {
private var view = activity.layoutInflater.inflate(R.layout.dialog_manage_bottom_actions, null)
init {
val actions = activity.config.visibleBottomActions
view.apply {
manage_bottom_actions_toggle_favorite.isChecked = actions and BOTTOM_ACTION_TOGGLE_FAVORITE != 0
manage_bottom_actions_edit.isChecked = actions and BOTTOM_ACTION_EDIT != 0
manage_bottom_actions_share.isChecked = actions and BOTTOM_ACTION_SHARE != 0
manage_bottom_actions_delete.isChecked = actions and BOTTOM_ACTION_DELETE != 0
manage_bottom_actions_rotate.isChecked = actions and BOTTOM_ACTION_ROTATE != 0
manage_bottom_actions_properties.isChecked = actions and BOTTOM_ACTION_PROPERTIES != 0
manage_bottom_actions_change_orientation.isChecked = actions and BOTTOM_ACTION_CHANGE_ORIENTATION != 0
manage_bottom_actions_slideshow.isChecked = actions and BOTTOM_ACTION_SLIDESHOW != 0
manage_bottom_actions_show_on_map.isChecked = actions and BOTTOM_ACTION_SHOW_ON_MAP != 0
manage_bottom_actions_toggle_visibility.isChecked = actions and BOTTOM_ACTION_TOGGLE_VISIBILITY != 0
manage_bottom_actions_rename.isChecked = actions and BOTTOM_ACTION_RENAME != 0
manage_bottom_actions_set_as.isChecked = actions and BOTTOM_ACTION_SET_AS != 0
manage_bottom_actions_copy.isChecked = actions and BOTTOM_ACTION_COPY != 0
manage_bottom_actions_move.isChecked = actions and BOTTOM_ACTION_MOVE != 0
manage_bottom_actions_resize.isChecked = actions and BOTTOM_ACTION_RESIZE != 0
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
var result = 0
view.apply {
if (manage_bottom_actions_toggle_favorite.isChecked)
result += BOTTOM_ACTION_TOGGLE_FAVORITE
if (manage_bottom_actions_edit.isChecked)
result += BOTTOM_ACTION_EDIT
if (manage_bottom_actions_share.isChecked)
result += BOTTOM_ACTION_SHARE
if (manage_bottom_actions_delete.isChecked)
result += BOTTOM_ACTION_DELETE
if (manage_bottom_actions_rotate.isChecked)
result += BOTTOM_ACTION_ROTATE
if (manage_bottom_actions_properties.isChecked)
result += BOTTOM_ACTION_PROPERTIES
if (manage_bottom_actions_change_orientation.isChecked)
result += BOTTOM_ACTION_CHANGE_ORIENTATION
if (manage_bottom_actions_slideshow.isChecked)
result += BOTTOM_ACTION_SLIDESHOW
if (manage_bottom_actions_show_on_map.isChecked)
result += BOTTOM_ACTION_SHOW_ON_MAP
if (manage_bottom_actions_toggle_visibility.isChecked)
result += BOTTOM_ACTION_TOGGLE_VISIBILITY
if (manage_bottom_actions_rename.isChecked)
result += BOTTOM_ACTION_RENAME
if (manage_bottom_actions_set_as.isChecked)
result += BOTTOM_ACTION_SET_AS
if (manage_bottom_actions_copy.isChecked)
result += BOTTOM_ACTION_COPY
if (manage_bottom_actions_move.isChecked)
result += BOTTOM_ACTION_MOVE
if (manage_bottom_actions_resize.isChecked)
result += BOTTOM_ACTION_RESIZE
}
activity.config.visibleBottomActions = result
callback(result)
}
}

View file

@ -1,11 +1,11 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.support.v7.app.AlertDialog
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.helpers.*
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.*
import kotlinx.android.synthetic.main.dialog_manage_extended_details.view.*
class ManageExtendedDetailsDialog(val activity: BaseSimpleActivity, val callback: (result: Int) -> Unit) {
@ -22,17 +22,15 @@ class ManageExtendedDetailsDialog(val activity: BaseSimpleActivity, val callback
manage_extended_details_date_taken.isChecked = details and EXT_DATE_TAKEN != 0
manage_extended_details_camera.isChecked = details and EXT_CAMERA_MODEL != 0
manage_extended_details_exif.isChecked = details and EXT_EXIF_PROPERTIES != 0
manage_extended_details_duration.isChecked = details and EXT_DURATION != 0
manage_extended_details_artist.isChecked = details and EXT_ARTIST != 0
manage_extended_details_album.isChecked = details and EXT_ALBUM != 0
manage_extended_details_gps_coordinates.isChecked = details and EXT_GPS != 0
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, { dialog, which -> dialogConfirmed() })
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
@ -54,12 +52,8 @@ class ManageExtendedDetailsDialog(val activity: BaseSimpleActivity, val callback
result += EXT_CAMERA_MODEL
if (manage_extended_details_exif.isChecked)
result += EXT_EXIF_PROPERTIES
if (manage_extended_details_duration.isChecked)
result += EXT_DURATION
if (manage_extended_details_artist.isChecked)
result += EXT_ARTIST
if (manage_extended_details_album.isChecked)
result += EXT_ALBUM
if (manage_extended_details_gps_coordinates.isChecked)
result += EXT_GPS
}
activity.config.extendedDetails = result

View file

@ -0,0 +1,74 @@
package com.simplemobiletools.gallery.pro.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import kotlinx.android.synthetic.main.dialog_other_aspect_ratio.view.*
class OtherAspectRatioDialog(val activity: BaseSimpleActivity, val lastOtherAspectRatio: Pair<Float, Float>?, val callback: (aspectRatio: Pair<Float, Float>) -> Unit) {
private val dialog: AlertDialog
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_other_aspect_ratio, null).apply {
other_aspect_ratio_2_1.setOnClickListener { ratioPicked(Pair(2f, 1f)) }
other_aspect_ratio_3_2.setOnClickListener { ratioPicked(Pair(3f, 2f)) }
other_aspect_ratio_4_3.setOnClickListener { ratioPicked(Pair(4f, 3f)) }
other_aspect_ratio_5_3.setOnClickListener { ratioPicked(Pair(5f, 3f)) }
other_aspect_ratio_16_9.setOnClickListener { ratioPicked(Pair(16f, 9f)) }
other_aspect_ratio_19_9.setOnClickListener { ratioPicked(Pair(19f, 9f)) }
other_aspect_ratio_custom.setOnClickListener { customRatioPicked() }
other_aspect_ratio_1_2.setOnClickListener { ratioPicked(Pair(1f, 2f)) }
other_aspect_ratio_2_3.setOnClickListener { ratioPicked(Pair(2f, 3f)) }
other_aspect_ratio_3_4.setOnClickListener { ratioPicked(Pair(3f, 4f)) }
other_aspect_ratio_3_5.setOnClickListener { ratioPicked(Pair(3f, 5f)) }
other_aspect_ratio_9_16.setOnClickListener { ratioPicked(Pair(9f, 16f)) }
other_aspect_ratio_9_19.setOnClickListener { ratioPicked(Pair(9f, 19f)) }
val radio1SelectedItemId = when (lastOtherAspectRatio) {
Pair(2f, 1f) -> other_aspect_ratio_2_1.id
Pair(3f, 2f) -> other_aspect_ratio_3_2.id
Pair(4f, 3f) -> other_aspect_ratio_4_3.id
Pair(5f, 3f) -> other_aspect_ratio_5_3.id
Pair(16f, 9f) -> other_aspect_ratio_16_9.id
Pair(19f, 9f) -> other_aspect_ratio_19_9.id
else -> 0
}
other_aspect_ratio_dialog_radio_1.check(radio1SelectedItemId)
val radio2SelectedItemId = when (lastOtherAspectRatio) {
Pair(1f, 2f) -> other_aspect_ratio_1_2.id
Pair(2f, 3f) -> other_aspect_ratio_2_3.id
Pair(3f, 4f) -> other_aspect_ratio_3_4.id
Pair(3f, 5f) -> other_aspect_ratio_3_5.id
Pair(9f, 16f) -> other_aspect_ratio_9_16.id
Pair(9f, 19f) -> other_aspect_ratio_9_19.id
else -> 0
}
other_aspect_ratio_dialog_radio_2.check(radio2SelectedItemId)
if (radio1SelectedItemId == 0 && radio2SelectedItemId == 0) {
other_aspect_ratio_dialog_radio_1.check(other_aspect_ratio_custom.id)
}
}
dialog = AlertDialog.Builder(activity)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
}
private fun customRatioPicked() {
CustomAspectRatioDialog(activity, lastOtherAspectRatio) {
callback(it)
dialog.dismiss()
}
}
private fun ratioPicked(pair: Pair<Float, Float>) {
callback(pair)
dialog.dismiss()
}
}

View file

@ -0,0 +1,163 @@
package com.simplemobiletools.gallery.pro.dialogs
import android.view.KeyEvent
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.views.MyGridLayoutManager
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.adapters.DirectoryAdapter
import com.simplemobiletools.gallery.pro.extensions.*
import com.simplemobiletools.gallery.pro.helpers.VIEW_TYPE_GRID
import com.simplemobiletools.gallery.pro.models.Directory
import kotlinx.android.synthetic.main.dialog_directory_picker.view.*
class PickDirectoryDialog(val activity: BaseSimpleActivity, val sourcePath: String, showOtherFolderButton: Boolean, val showFavoritesBin: Boolean,
val callback: (path: String) -> Unit) {
private var dialog: AlertDialog
private var shownDirectories = ArrayList<Directory>()
private var allDirectories = ArrayList<Directory>()
private var openedSubfolders = arrayListOf("")
private var view = activity.layoutInflater.inflate(R.layout.dialog_directory_picker, null)
private var isGridViewType = activity.config.viewTypeFolders == VIEW_TYPE_GRID
private var showHidden = activity.config.shouldShowHidden
private var currentPathPrefix = ""
init {
(view.directories_grid.layoutManager as MyGridLayoutManager).apply {
orientation = if (activity.config.scrollHorizontally && isGridViewType) RecyclerView.HORIZONTAL else RecyclerView.VERTICAL
spanCount = if (isGridViewType) activity.config.dirColumnCnt else 1
}
val builder = AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.setOnKeyListener { dialogInterface, i, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_UP && i == KeyEvent.KEYCODE_BACK) {
backPressed()
}
true
}
if (showOtherFolderButton) {
builder.setNeutralButton(R.string.other_folder) { dialogInterface, i -> showOtherFolder() }
}
dialog = builder.create().apply {
activity.setupDialogStuff(view, this, R.string.select_destination) {
view.directories_show_hidden.beVisibleIf(!context.config.shouldShowHidden)
view.directories_show_hidden.setOnClickListener {
activity.handleHiddenFolderPasswordProtection {
view.directories_show_hidden.beGone()
showHidden = true
fetchDirectories(true)
}
}
}
}
fetchDirectories(false)
}
private fun fetchDirectories(forceShowHidden: Boolean) {
activity.getCachedDirectories(forceShowHidden = forceShowHidden) {
if (it.isNotEmpty()) {
it.forEach {
it.subfoldersMediaCount = it.mediaCnt
}
activity.runOnUiThread {
gotDirectories(activity.addTempFolderIfNeeded(it))
}
}
}
}
private fun showOtherFolder() {
FilePickerDialog(activity, sourcePath, false, showHidden, true, true) {
activity.handleLockedFolderOpening(it) { success ->
if (success) {
callback(it)
}
}
}
}
private fun gotDirectories(newDirs: ArrayList<Directory>) {
if (allDirectories.isEmpty()) {
allDirectories = newDirs.clone() as ArrayList<Directory>
}
val distinctDirs = newDirs.filter { showFavoritesBin || (!it.isRecycleBin() && !it.areFavorites()) }.distinctBy { it.path.getDistinctPath() }.toMutableList() as ArrayList<Directory>
val sortedDirs = activity.getSortedDirectories(distinctDirs)
val dirs = activity.getDirsToShow(sortedDirs, allDirectories, currentPathPrefix).clone() as ArrayList<Directory>
if (dirs.hashCode() == shownDirectories.hashCode()) {
return
}
shownDirectories = dirs
val adapter = DirectoryAdapter(activity, dirs.clone() as ArrayList<Directory>, null, view.directories_grid, true) {
val clickedDir = it as Directory
val path = clickedDir.path
if (clickedDir.subfoldersCount == 1 || !activity.config.groupDirectSubfolders) {
if (path.trimEnd('/') == sourcePath) {
activity.toast(R.string.source_and_destination_same)
return@DirectoryAdapter
} else {
activity.handleLockedFolderOpening(path) { success ->
if (success) {
callback(path)
}
}
dialog.dismiss()
}
} else {
currentPathPrefix = path
openedSubfolders.add(path)
gotDirectories(allDirectories)
}
}
val scrollHorizontally = activity.config.scrollHorizontally && isGridViewType
val sorting = activity.config.directorySorting
val dateFormat = activity.config.dateFormat
val timeFormat = activity.getTimeFormat()
view.apply {
directories_grid.adapter = adapter
directories_vertical_fastscroller.isHorizontal = false
directories_vertical_fastscroller.beGoneIf(scrollHorizontally)
directories_horizontal_fastscroller.isHorizontal = true
directories_horizontal_fastscroller.beVisibleIf(scrollHorizontally)
if (scrollHorizontally) {
directories_horizontal_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble
directories_horizontal_fastscroller.setViews(directories_grid) {
directories_horizontal_fastscroller.updateBubbleText(dirs[it].getBubbleText(sorting, activity, dateFormat, timeFormat))
}
} else {
directories_vertical_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble
directories_vertical_fastscroller.setViews(directories_grid) {
directories_vertical_fastscroller.updateBubbleText(dirs[it].getBubbleText(sorting, activity, dateFormat, timeFormat))
}
}
}
}
private fun backPressed() {
if (activity.config.groupDirectSubfolders) {
if (currentPathPrefix.isEmpty()) {
dialog.dismiss()
} else {
openedSubfolders.removeAt(openedSubfolders.size - 1)
currentPathPrefix = openedSubfolders.last()
gotDirectories(allDirectories)
}
} else {
dialog.dismiss()
}
}
}

View file

@ -1,43 +1,47 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.support.v7.app.AlertDialog
import android.support.v7.widget.GridLayoutManager
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.beGoneIf
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.getTimeFormat
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.views.MyGridLayoutManager
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.adapters.MediaAdapter
import com.simplemobiletools.gallery.asynctasks.GetMediaAsynctask
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.extensions.getCachedMedia
import com.simplemobiletools.gallery.helpers.VIEW_TYPE_GRID
import com.simplemobiletools.gallery.models.Medium
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.config
import com.simplemobiletools.gallery.pro.extensions.getCachedMedia
import com.simplemobiletools.gallery.pro.helpers.SHOW_ALL
import com.simplemobiletools.gallery.pro.helpers.VIEW_TYPE_GRID
import com.simplemobiletools.gallery.pro.models.Medium
import com.simplemobiletools.gallery.pro.models.ThumbnailItem
import kotlinx.android.synthetic.main.dialog_medium_picker.view.*
class PickMediumDialog(val activity: BaseSimpleActivity, val path: String, val callback: (path: String) -> Unit) {
var dialog: AlertDialog
var shownMedia = ArrayList<Medium>()
var shownMedia = ArrayList<ThumbnailItem>()
val view = activity.layoutInflater.inflate(R.layout.dialog_medium_picker, null)
var isGridViewType = activity.config.viewTypeFiles == VIEW_TYPE_GRID
val viewType = activity.config.getFolderViewType(if (activity.config.showAll) SHOW_ALL else path)
var isGridViewType = viewType == VIEW_TYPE_GRID
init {
(view.media_grid.layoutManager as MyGridLayoutManager).apply {
orientation = if (activity.config.scrollHorizontally && isGridViewType) GridLayoutManager.HORIZONTAL else GridLayoutManager.VERTICAL
orientation = if (activity.config.scrollHorizontally && isGridViewType) RecyclerView.HORIZONTAL else RecyclerView.VERTICAL
spanCount = if (isGridViewType) activity.config.mediaColumnCnt else 1
}
dialog = AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.setNeutralButton(R.string.other_folder, { dialogInterface, i -> showOtherFolder() })
.setNeutralButton(R.string.other_folder) { dialogInterface, i -> showOtherFolder() }
.create().apply {
activity.setupDialogStuff(view, this, R.string.select_photo)
}
activity.getCachedMedia(path) {
val media = it.filter { !it.isVideo() } as ArrayList
val media = it.filter { it is Medium } as ArrayList
if (media.isNotEmpty()) {
activity.runOnUiThread {
gotMedia(media)
@ -45,30 +49,34 @@ class PickMediumDialog(val activity: BaseSimpleActivity, val path: String, val c
}
}
GetMediaAsynctask(activity, path, true, false, false) {
GetMediaAsynctask(activity, path, false, false, false) {
gotMedia(it)
}.execute()
}
private fun showOtherFolder() {
PickDirectoryDialog(activity, path) {
PickDirectoryDialog(activity, path, true, true) {
callback(it)
dialog.dismiss()
}
}
private fun gotMedia(media: ArrayList<Medium>) {
private fun gotMedia(media: ArrayList<ThumbnailItem>) {
if (media.hashCode() == shownMedia.hashCode())
return
shownMedia = media
val adapter = MediaAdapter(activity, media, null, true, false, view.media_grid) {
callback((it as Medium).path)
dialog.dismiss()
val adapter = MediaAdapter(activity, shownMedia.clone() as ArrayList<ThumbnailItem>, null, true, false, path, view.media_grid, null) {
if (it is Medium) {
callback(it.path)
dialog.dismiss()
}
}
val scrollHorizontally = activity.config.scrollHorizontally && isGridViewType
val sorting = activity.config.getFileSorting(path)
val sorting = activity.config.getFolderSorting(if (path.isEmpty()) SHOW_ALL else path)
val dateFormat = activity.config.dateFormat
val timeFormat = activity.getTimeFormat()
view.apply {
media_grid.adapter = adapter
@ -81,12 +89,14 @@ class PickMediumDialog(val activity: BaseSimpleActivity, val path: String, val c
if (scrollHorizontally) {
media_horizontal_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble
media_horizontal_fastscroller.setViews(media_grid) {
media_horizontal_fastscroller.updateBubbleText(media[it].getBubbleText(sorting))
val medium = (media[it] as? Medium)
media_horizontal_fastscroller.updateBubbleText(medium?.getBubbleText(sorting, activity, dateFormat, timeFormat) ?: "")
}
} else {
media_vertical_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble
media_vertical_fastscroller.setViews(media_grid) {
media_vertical_fastscroller.updateBubbleText(media[it].getBubbleText(sorting))
val medium = (media[it] as? Medium)
media_vertical_fastscroller.updateBubbleText(medium?.getBubbleText(sorting, activity, dateFormat, timeFormat) ?: "")
}
}
}

View file

@ -0,0 +1,76 @@
package com.simplemobiletools.gallery.pro.dialogs
import android.graphics.Point
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.gallery.pro.R
import kotlinx.android.synthetic.main.dialog_resize_image.view.*
class ResizeDialog(val activity: BaseSimpleActivity, val size: Point, val callback: (newSize: Point) -> Unit) {
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_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.onTextChangeListener {
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())
}
}
}
heightView.onTextChangeListener {
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())
}
}
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this, R.string.resize_and_save) {
showKeyboard(view.image_width)
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(newSize)
dismiss()
}
}
}
}
private fun getViewValue(view: EditText): Int {
val textValue = view.value
return if (textValue.isEmpty()) 0 else textValue.toInt()
}
}

View file

@ -0,0 +1,125 @@
package com.simplemobiletools.gallery.pro.dialogs
import android.graphics.Point
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import kotlinx.android.synthetic.main.dialog_resize_image_with_path.view.*
class ResizeWithPathDialog(val activity: BaseSimpleActivity, val size: Point, val path: String, val callback: (newSize: Point, newPath: String) -> Unit) {
init {
var realPath = path.getParentPath()
val view = activity.layoutInflater.inflate(R.layout.dialog_resize_image_with_path, null).apply {
image_path.text = "${activity.humanizePath(realPath).trimEnd('/')}/"
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)
image_extension.setText(extension)
}
image_name.setText(name)
image_path.setOnClickListener {
FilePickerDialog(activity, realPath, false, activity.config.shouldShowHidden, true, true) {
image_path.text = activity.humanizePath(it)
realPath = it
}
}
}
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.onTextChangeListener {
if (widthView.hasFocus()) {
var width = getViewValue(widthView)
if (width > size.x) {
widthView.setText(size.x.toString())
width = size.x
}
heightView.setText((width / ratio).toInt().toString())
}
}
heightView.onTextChangeListener {
if (heightView.hasFocus()) {
var height = getViewValue(heightView)
if (height > size.y) {
heightView.setText(size.y.toString())
height = size.y
}
widthView.setText((height * ratio).toInt().toString())
}
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this) {
showKeyboard(view.image_width)
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))
val filename = view.image_name.value
val extension = view.image_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 newFilename = "$filename.$extension"
val newPath = "${realPath.trimEnd('/')}/$newFilename"
if (!newFilename.isAValidFilename()) {
activity.toast(R.string.filename_invalid_characters)
return@setOnClickListener
}
if (activity.getDoesFilePathExist(newPath)) {
val title = String.format(activity.getString(R.string.file_already_exists_overwrite), newFilename)
ConfirmationDialog(activity, title) {
callback(newSize, newPath)
dismiss()
}
} else {
callback(newSize, newPath)
dismiss()
}
}
}
}
}
private fun getViewValue(view: EditText): Int {
val textValue = view.value
return if (textValue.isEmpty()) 0 else textValue.toInt()
}
}

View file

@ -1,14 +1,15 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.support.v7.app.AlertDialog
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
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.pro.R
import kotlinx.android.synthetic.main.dialog_save_as.view.*
class SaveAsDialog(val activity: BaseSimpleActivity, val path: String, val appendFilename: Boolean, val callback: (savePath: String) -> Unit) {
class SaveAsDialog(val activity: BaseSimpleActivity, val path: String, val appendFilename: Boolean, val cancelCallback: (() -> Unit)? = null,
val callback: (savePath: String) -> Unit) {
init {
var realPath = path.getParentPath()
@ -32,7 +33,8 @@ class SaveAsDialog(val activity: BaseSimpleActivity, val path: String, val appen
save_as_name.setText(name)
save_as_path.setOnClickListener {
FilePickerDialog(activity, realPath, false, false, true) {
activity.hideKeyboard(save_as_path)
FilePickerDialog(activity, realPath, false, false, true, true) {
save_as_path.text = activity.humanizePath(it)
realPath = it
}
@ -41,7 +43,8 @@ class SaveAsDialog(val activity: BaseSimpleActivity, val path: String, val appen
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.setNegativeButton(R.string.cancel) { dialog, which -> cancelCallback?.invoke() }
.setOnCancelListener { cancelCallback?.invoke() }
.create().apply {
activity.setupDialogStuff(view, this, R.string.save_as) {
showKeyboard(view.save_as_name)

View file

@ -1,14 +1,19 @@
package com.simplemobiletools.gallery.dialogs
package com.simplemobiletools.gallery.pro.dialogs
import android.support.v7.app.AlertDialog
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.hideKeyboard
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.extensions.config
import com.simplemobiletools.gallery.helpers.SLIDESHOW_DEFAULT_INTERVAL
import com.simplemobiletools.commons.extensions.value
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_FADE
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_NONE
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_SLIDE
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_DEFAULT_INTERVAL
import kotlinx.android.synthetic.main.dialog_slideshow.view.*
class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit) {
@ -29,9 +34,16 @@ class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit
activity.hideKeyboard(v)
}
include_photos_holder.setOnClickListener {
interval_value.clearFocus()
include_photos.toggle()
animation_holder.setOnClickListener {
val items = arrayListOf(
RadioItem(SLIDESHOW_ANIMATION_NONE, activity.getString(R.string.no_animation)),
RadioItem(SLIDESHOW_ANIMATION_SLIDE, activity.getString(R.string.slide)),
RadioItem(SLIDESHOW_ANIMATION_FADE, activity.getString(R.string.fade)))
RadioGroupDialog(activity, items, activity.config.slideshowAnimation) {
activity.config.slideshowAnimation = it as Int
animation_value.text = getAnimationText()
}
}
include_videos_holder.setOnClickListener {
@ -49,11 +61,6 @@ class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit
random_order.toggle()
}
use_fade_holder.setOnClickListener {
interval_value.clearFocus()
use_fade.toggle()
}
move_backwards_holder.setOnClickListener {
interval_value.clearFocus()
move_backwards.toggle()
@ -73,11 +80,6 @@ class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit
activity.setupDialogStuff(view, this) {
hideKeyboard()
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
if (!view.include_photos.isChecked && !view.include_videos.isChecked && !view.include_gifs.isChecked) {
activity.toast(R.string.no_media_for_slideshow)
return@setOnClickListener
}
storeValues()
callback()
dismiss()
@ -90,11 +92,10 @@ class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit
val config = activity.config
view.apply {
interval_value.setText(config.slideshowInterval.toString())
include_photos.isChecked = config.slideshowIncludePhotos
animation_value.text = getAnimationText()
include_videos.isChecked = config.slideshowIncludeVideos
include_gifs.isChecked = config.slideshowIncludeGIFs
random_order.isChecked = config.slideshowRandomOrder
use_fade.isChecked = config.slideshowUseFade
move_backwards.isChecked = config.slideshowMoveBackwards
loop_slideshow.isChecked = config.loopSlideshow
}
@ -106,14 +107,29 @@ class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit
interval = SLIDESHOW_DEFAULT_INTERVAL.toString()
activity.config.apply {
slideshowAnimation = getAnimationValue(view.animation_value.value)
slideshowInterval = interval.toInt()
slideshowIncludePhotos = view.include_photos.isChecked
slideshowIncludeVideos = view.include_videos.isChecked
slideshowIncludeGIFs = view.include_gifs.isChecked
slideshowRandomOrder = view.random_order.isChecked
slideshowUseFade = view.use_fade.isChecked
slideshowMoveBackwards = view.move_backwards.isChecked
loopSlideshow = view.loop_slideshow.isChecked
}
}
private fun getAnimationText(): String {
return when (activity.config.slideshowAnimation) {
SLIDESHOW_ANIMATION_SLIDE -> activity.getString(R.string.slide)
SLIDESHOW_ANIMATION_FADE -> activity.getString(R.string.fade)
else -> activity.getString(R.string.no_animation)
}
}
private fun getAnimationValue(text: String): Int {
return when (text) {
activity.getString(R.string.slide) -> SLIDESHOW_ANIMATION_SLIDE
activity.getString(R.string.fade) -> SLIDESHOW_ANIMATION_FADE
else -> SLIDESHOW_ANIMATION_NONE
}
}
}

View file

@ -0,0 +1,661 @@
package com.simplemobiletools.gallery.pro.extensions
import android.annotation.TargetApi
import android.app.Activity
import android.content.ContentProviderOperation
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.provider.MediaStore.Images
import android.util.DisplayMetrics
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.gallery.pro.BuildConfig
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.activities.SimpleActivity
import com.simplemobiletools.gallery.pro.dialogs.PickDirectoryDialog
import com.simplemobiletools.gallery.pro.helpers.RECYCLE_BIN
import com.simplemobiletools.gallery.pro.models.DateTaken
import com.squareup.picasso.Picasso
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.*
fun Activity.sharePath(path: String) {
sharePathIntent(path, BuildConfig.APPLICATION_ID)
}
fun Activity.sharePaths(paths: ArrayList<String>) {
sharePathsIntent(paths, BuildConfig.APPLICATION_ID)
}
fun Activity.shareMediumPath(path: String) {
sharePath(path)
}
fun Activity.shareMediaPaths(paths: ArrayList<String>) {
sharePaths(paths)
}
fun Activity.setAs(path: String) {
setAsIntent(path, BuildConfig.APPLICATION_ID)
}
fun Activity.openPath(path: String, forceChooser: Boolean, extras: HashMap<String, Boolean> = HashMap()) {
openPathIntent(path, forceChooser, BuildConfig.APPLICATION_ID, extras = extras)
}
fun Activity.openEditor(path: String, forceChooser: Boolean = false) {
val newPath = path.removePrefix("file://")
openEditorIntent(newPath, forceChooser, BuildConfig.APPLICATION_ID)
}
fun Activity.launchCamera() {
val intent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
toast(R.string.no_app_found)
}
}
fun SimpleActivity.launchAbout() {
val licenses = LICENSE_GLIDE or LICENSE_CROPPER or LICENSE_RTL or LICENSE_SUBSAMPLING or LICENSE_PATTERN or LICENSE_REPRINT or LICENSE_GIF_DRAWABLE or
LICENSE_PICASSO or LICENSE_EXOPLAYER or LICENSE_PANORAMA_VIEW or LICENSE_SANSELAN or LICENSE_FILTERS or LICENSE_GESTURE_VIEWS
val faqItems = arrayListOf(
FAQItem(R.string.faq_5_title_commons, R.string.faq_5_text_commons),
FAQItem(R.string.faq_1_title, R.string.faq_1_text),
FAQItem(R.string.faq_2_title, R.string.faq_2_text),
FAQItem(R.string.faq_3_title, R.string.faq_3_text),
FAQItem(R.string.faq_4_title, R.string.faq_4_text),
FAQItem(R.string.faq_5_title, R.string.faq_5_text),
FAQItem(R.string.faq_6_title, R.string.faq_6_text),
FAQItem(R.string.faq_7_title, R.string.faq_7_text),
FAQItem(R.string.faq_8_title, R.string.faq_8_text),
FAQItem(R.string.faq_10_title, R.string.faq_10_text),
FAQItem(R.string.faq_11_title, R.string.faq_11_text),
FAQItem(R.string.faq_12_title, R.string.faq_12_text),
FAQItem(R.string.faq_13_title, R.string.faq_13_text),
FAQItem(R.string.faq_14_title, R.string.faq_14_text),
FAQItem(R.string.faq_15_title, R.string.faq_15_text),
FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons),
FAQItem(R.string.faq_6_title_commons, R.string.faq_6_text_commons),
FAQItem(R.string.faq_7_title_commons, R.string.faq_7_text_commons))
startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true)
}
fun AppCompatActivity.showSystemUI(toggleActionBarVisibility: Boolean) {
if (toggleActionBarVisibility) {
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(toggleActionBarVisibility: Boolean) {
if (toggleActionBarVisibility) {
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 BaseSimpleActivity.addNoMedia(path: String, callback: () -> Unit) {
val file = File(path, NOMEDIA)
if (getDoesFilePathExist(file.absolutePath)) {
callback()
return
}
if (needsStupidWritePermissions(path)) {
handleSAFDialog(file.absolutePath) {
if (!it) {
return@handleSAFDialog
}
val fileDocument = getDocumentFile(path)
if (fileDocument?.exists() == true && fileDocument.isDirectory) {
fileDocument.createFile("", NOMEDIA)
applicationContext.scanPathRecursively(file.absolutePath) {
callback()
}
} else {
toast(R.string.unknown_error_occurred)
callback()
}
}
} else {
try {
if (file.createNewFile()) {
rescanFolderMedia(file.absolutePath)
} else {
toast(R.string.unknown_error_occurred)
}
} catch (e: Exception) {
showErrorToast(e)
}
callback()
}
}
fun BaseSimpleActivity.removeNoMedia(path: String, callback: (() -> Unit)? = null) {
val file = File(path, NOMEDIA)
if (!getDoesFilePathExist(file.absolutePath)) {
callback?.invoke()
return
}
tryDeleteFileDirItem(file.toFileDirItem(applicationContext), false, false) {
callback?.invoke()
deleteFromMediaStore(file.absolutePath)
rescanFolderMedia(path)
}
}
fun BaseSimpleActivity.toggleFileVisibility(oldPath: String, hide: Boolean, callback: ((newPath: String) -> Unit)? = null) {
val path = oldPath.getParentPath()
var filename = oldPath.getFilenameFromPath()
if ((hide && filename.startsWith('.')) || (!hide && !filename.startsWith('.'))) {
callback?.invoke(oldPath)
return
}
filename = if (hide) {
".${filename.trimStart('.')}"
} else {
filename.substring(1, filename.length)
}
val newPath = "$path/$filename"
renameFile(oldPath, newPath) {
callback?.invoke(newPath)
ensureBackgroundThread {
updateDBMediaPath(oldPath, newPath)
}
}
}
fun BaseSimpleActivity.tryCopyMoveFilesTo(fileDirItems: ArrayList<FileDirItem>, isCopyOperation: Boolean, callback: (destinationPath: String) -> Unit) {
if (fileDirItems.isEmpty()) {
toast(R.string.unknown_error_occurred)
return
}
val source = fileDirItems[0].getParentPath()
PickDirectoryDialog(this, source, true, false) {
val destination = it
handleSAFDialog(source) {
if (it) {
copyMoveFilesTo(fileDirItems, source.trimEnd('/'), destination, isCopyOperation, true, config.shouldShowHidden, callback)
}
}
}
}
fun BaseSimpleActivity.tryDeleteFileDirItem(fileDirItem: FileDirItem, allowDeleteFolder: Boolean = false, deleteFromDatabase: Boolean,
callback: ((wasSuccess: Boolean) -> Unit)? = null) {
deleteFile(fileDirItem, allowDeleteFolder) {
if (deleteFromDatabase) {
ensureBackgroundThread {
deleteDBPath(fileDirItem.path)
runOnUiThread {
callback?.invoke(it)
}
}
} else {
callback?.invoke(it)
}
}
}
fun BaseSimpleActivity.movePathsInRecycleBin(paths: ArrayList<String>, callback: ((wasSuccess: Boolean) -> Unit)?) {
ensureBackgroundThread {
var pathsCnt = paths.size
val OTGPath = config.OTGPath
for (source in paths) {
if (OTGPath.isNotEmpty() && source.startsWith(OTGPath)) {
var inputStream: InputStream? = null
var out: OutputStream? = null
try {
val destination = "$recycleBinPath/$source"
val fileDocument = getSomeDocumentFile(source)
inputStream = applicationContext.contentResolver.openInputStream(fileDocument?.uri!!)
out = getFileOutputStreamSync(destination, source.getMimeType())
var copiedSize = 0L
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = inputStream!!.read(buffer)
while (bytes >= 0) {
out!!.write(buffer, 0, bytes)
copiedSize += bytes
bytes = inputStream.read(buffer)
}
out?.flush()
if (fileDocument?.getItemSize(true) == copiedSize && getDoesFilePathExist(destination)) {
mediaDB.updateDeleted("$RECYCLE_BIN$source", System.currentTimeMillis(), source)
pathsCnt--
}
} catch (e: Exception) {
showErrorToast(e)
return@ensureBackgroundThread
} finally {
inputStream?.close()
out?.close()
}
} else {
val file = File(source)
val internalFile = File(recycleBinPath, source)
val lastModified = file.lastModified()
try {
if (file.copyRecursively(internalFile, true)) {
mediaDB.updateDeleted("$RECYCLE_BIN$source", System.currentTimeMillis(), source)
pathsCnt--
if (config.keepLastModified) {
internalFile.setLastModified(lastModified)
}
}
} catch (e: Exception) {
showErrorToast(e)
return@ensureBackgroundThread
}
}
}
callback?.invoke(pathsCnt == 0)
}
}
fun BaseSimpleActivity.restoreRecycleBinPath(path: String, callback: () -> Unit) {
restoreRecycleBinPaths(arrayListOf(path), callback)
}
fun BaseSimpleActivity.restoreRecycleBinPaths(paths: ArrayList<String>, callback: () -> Unit) {
ensureBackgroundThread {
val newPaths = ArrayList<String>()
for (source in paths) {
val destination = source.removePrefix(recycleBinPath)
val lastModified = File(source).lastModified()
val isShowingSAF = handleSAFDialog(destination) {}
if (isShowingSAF) {
return@ensureBackgroundThread
}
var inputStream: InputStream? = null
var out: OutputStream? = null
try {
out = getFileOutputStreamSync(destination, source.getMimeType())
inputStream = getFileInputStreamSync(source)
var copiedSize = 0L
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = inputStream!!.read(buffer)
while (bytes >= 0) {
out!!.write(buffer, 0, bytes)
copiedSize += bytes
bytes = inputStream.read(buffer)
}
out?.flush()
if (File(source).length() == copiedSize) {
mediaDB.updateDeleted(destination.removePrefix(recycleBinPath), 0, "$RECYCLE_BIN$destination")
}
newPaths.add(destination)
if (config.keepLastModified) {
File(destination).setLastModified(lastModified)
}
} catch (e: Exception) {
showErrorToast(e)
} finally {
inputStream?.close()
out?.close()
}
}
runOnUiThread {
callback()
}
rescanPaths(newPaths) {
fixDateTaken(newPaths, false)
}
}
}
fun BaseSimpleActivity.emptyTheRecycleBin(callback: (() -> Unit)? = null) {
ensureBackgroundThread {
try {
recycleBin.deleteRecursively()
mediaDB.clearRecycleBin()
directoryDao.deleteRecycleBin()
toast(R.string.recycle_bin_emptied)
callback?.invoke()
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
fun BaseSimpleActivity.emptyAndDisableTheRecycleBin(callback: () -> Unit) {
ensureBackgroundThread {
emptyTheRecycleBin {
config.useRecycleBin = false
callback()
}
}
}
fun BaseSimpleActivity.showRecycleBinEmptyingDialog(callback: () -> Unit) {
ConfirmationDialog(this, "", R.string.empty_recycle_bin_confirmation, R.string.yes, R.string.no) {
callback()
}
}
fun BaseSimpleActivity.updateFavoritePaths(fileDirItems: ArrayList<FileDirItem>, destination: String) {
ensureBackgroundThread {
fileDirItems.forEach {
val newPath = "$destination/${it.name}"
updateDBMediaPath(it.path, newPath)
}
}
}
fun Activity.hasNavBar(): Boolean {
val display = windowManager.defaultDisplay
val realDisplayMetrics = DisplayMetrics()
display.getRealMetrics(realDisplayMetrics)
val displayMetrics = DisplayMetrics()
display.getMetrics(displayMetrics)
return (realDisplayMetrics.widthPixels - displayMetrics.widthPixels > 0) || (realDisplayMetrics.heightPixels - displayMetrics.heightPixels > 0)
}
fun Activity.fixDateTaken(paths: ArrayList<String>, showToasts: Boolean, hasRescanned: Boolean = false, callback: (() -> Unit)? = null) {
val BATCH_SIZE = 50
if (showToasts) {
toast(R.string.fixing)
}
val pathsToRescan = ArrayList<String>()
try {
var didUpdateFile = false
val operations = ArrayList<ContentProviderOperation>()
ensureBackgroundThread {
val dateTakens = ArrayList<DateTaken>()
for (path in paths) {
val dateTime = ExifInterface(path).getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL)
?: ExifInterface(path).getAttribute(ExifInterface.TAG_DATETIME) ?: continue
// some formats contain a "T" in the middle, some don't
// sample dates: 2015-07-26T14:55:23, 2018:09:05 15:09:05
val t = if (dateTime.substring(10, 11) == "T") "\'T\'" else " "
val separator = dateTime.substring(4, 5)
val format = "yyyy${separator}MM${separator}dd${t}kk:mm:ss"
val formatter = SimpleDateFormat(format, Locale.getDefault())
val timestamp = formatter.parse(dateTime).time
val uri = getFileUri(path)
ContentProviderOperation.newUpdate(uri).apply {
val selection = "${Images.Media.DATA} = ?"
val selectionArgs = arrayOf(path)
withSelection(selection, selectionArgs)
withValue(Images.Media.DATE_TAKEN, timestamp)
operations.add(build())
}
if (operations.size % BATCH_SIZE == 0) {
contentResolver.applyBatch(MediaStore.AUTHORITY, operations)
operations.clear()
}
mediaDB.updateFavoriteDateTaken(path, timestamp)
didUpdateFile = true
val dateTaken = DateTaken(null, path, path.getFilenameFromPath(), path.getParentPath(), timestamp, (System.currentTimeMillis() / 1000).toInt())
dateTakens.add(dateTaken)
if (!hasRescanned && getFileDateTaken(path) == 0L) {
pathsToRescan.add(path)
}
}
if (!didUpdateFile) {
if (showToasts) {
toast(R.string.no_date_takens_found)
}
runOnUiThread {
callback?.invoke()
}
return@ensureBackgroundThread
}
val resultSize = contentResolver.applyBatch(MediaStore.AUTHORITY, operations).size
if (resultSize == 0) {
didUpdateFile = false
}
if (hasRescanned || pathsToRescan.isEmpty()) {
if (dateTakens.isNotEmpty()) {
dateTakensDB.insertAll(dateTakens)
}
runOnUiThread {
if (showToasts) {
toast(if (didUpdateFile) R.string.dates_fixed_successfully else R.string.unknown_error_occurred)
}
callback?.invoke()
}
} else {
rescanPaths(pathsToRescan) {
fixDateTaken(paths, showToasts, true)
}
}
}
} catch (e: Exception) {
if (showToasts) {
showErrorToast(e)
}
}
}
fun BaseSimpleActivity.saveRotatedImageToFile(oldPath: String, newPath: String, degrees: Int, showToasts: Boolean, callback: () -> Unit) {
var newDegrees = degrees
if (newDegrees < 0) {
newDegrees += 360
}
if (oldPath == newPath && oldPath.isJpg()) {
if (tryRotateByExif(oldPath, newDegrees, showToasts, callback)) {
return
}
}
val tmpPath = "$recycleBinPath/.tmp_${newPath.getFilenameFromPath()}"
val tmpFileDirItem = FileDirItem(tmpPath, tmpPath.getFilenameFromPath())
try {
getFileOutputStream(tmpFileDirItem) {
if (it == null) {
if (showToasts) {
toast(R.string.unknown_error_occurred)
}
return@getFileOutputStream
}
val oldLastModified = File(oldPath).lastModified()
if (oldPath.isJpg()) {
copyFile(oldPath, tmpPath)
saveExifRotation(ExifInterface(tmpPath), newDegrees)
} else {
val inputstream = getFileInputStreamSync(oldPath)
val bitmap = BitmapFactory.decodeStream(inputstream)
saveFile(tmpPath, bitmap, it as FileOutputStream, newDegrees)
}
copyFile(tmpPath, newPath)
rescanPaths(arrayListOf(newPath))
fileRotatedSuccessfully(newPath, oldLastModified)
it.flush()
it.close()
callback.invoke()
}
} catch (e: OutOfMemoryError) {
if (showToasts) {
toast(R.string.out_of_memory_error)
}
} catch (e: Exception) {
if (showToasts) {
showErrorToast(e)
}
} finally {
tryDeleteFileDirItem(tmpFileDirItem, false, true)
}
}
@TargetApi(Build.VERSION_CODES.N)
fun Activity.tryRotateByExif(path: String, degrees: Int, showToasts: Boolean, callback: () -> Unit): Boolean {
return try {
val file = File(path)
val oldLastModified = file.lastModified()
if (saveImageRotation(path, degrees)) {
fileRotatedSuccessfully(path, oldLastModified)
callback.invoke()
if (showToasts) {
toast(R.string.file_saved)
}
true
} else {
false
}
} catch (e: Exception) {
if (showToasts) {
showErrorToast(e)
}
false
}
}
fun Activity.fileRotatedSuccessfully(path: String, lastModified: Long) {
if (config.keepLastModified) {
File(path).setLastModified(lastModified)
updateLastModified(path, lastModified)
}
Picasso.get().invalidate(path.getFileKey())
// we cannot refresh a specific image in Glide Cache, so just clear it all
val glide = Glide.get(applicationContext)
glide.clearDiskCache()
runOnUiThread {
glide.clearMemory()
}
}
fun BaseSimpleActivity.copyFile(source: String, destination: String) {
var inputStream: InputStream? = null
var out: OutputStream? = null
try {
out = getFileOutputStreamSync(destination, source.getMimeType())
inputStream = getFileInputStreamSync(source)
inputStream!!.copyTo(out!!)
} catch (e: Exception) {
showErrorToast(e)
} finally {
inputStream?.close()
out?.close()
}
}
fun saveFile(path: String, bitmap: Bitmap, out: FileOutputStream, degrees: Int) {
val matrix = Matrix()
matrix.postRotate(degrees.toFloat())
val bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bmp.compress(path.getCompressionFormat(), 90, out)
}
fun Activity.getShortcutImage(tmb: String, drawable: Drawable, callback: () -> Unit) {
ensureBackgroundThread {
val options = RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.fitCenter()
val size = resources.getDimension(R.dimen.shortcut_size).toInt()
val builder = Glide.with(this)
.asDrawable()
.load(tmb)
.apply(options)
.centerCrop()
.into(size, size)
try {
(drawable as LayerDrawable).setDrawableByLayerId(R.id.shortcut_image, builder.get())
} catch (e: Exception) {
}
runOnUiThread {
callback()
}
}
}
@TargetApi(Build.VERSION_CODES.N)
fun Activity.showFileOnMap(path: String) {
val exif = try {
if (path.startsWith("content://") && isNougatPlus()) {
ExifInterface(contentResolver.openInputStream(Uri.parse(path))!!)
} else {
ExifInterface(path)
}
} catch (e: Exception) {
showErrorToast(e)
return
}
val latLon = FloatArray(2)
if (exif.getLatLong(latLon)) {
showLocationOnMap("${latLon[0]}, ${latLon[1]}")
} else {
toast(R.string.unknown_location)
}
}

View file

@ -0,0 +1,33 @@
package com.simplemobiletools.gallery.pro.extensions
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.models.Medium
fun ArrayList<Medium>.getDirMediaTypes(): Int {
var types = 0
if (any { it.isImage() }) {
types += TYPE_IMAGES
}
if (any { it.isVideo() }) {
types += TYPE_VIDEOS
}
if (any { it.isGIF() }) {
types += TYPE_GIFS
}
if (any { it.isRaw() }) {
types += TYPE_RAWS
}
if (any { it.isSVG() }) {
types += TYPE_SVGS
}
if (any { it.isPortrait() }) {
types += TYPE_PORTRAITS
}
return types
}

View file

@ -0,0 +1,909 @@
package com.simplemobiletools.gallery.pro.extensions
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.drawable.PictureDrawable
import android.media.AudioManager
import android.provider.MediaStore.Files
import android.provider.MediaStore.Images
import android.widget.ImageView
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.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.activities.SettingsActivity
import com.simplemobiletools.gallery.pro.asynctasks.GetMediaAsynctask
import com.simplemobiletools.gallery.pro.databases.GalleryDatabase
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.interfaces.*
import com.simplemobiletools.gallery.pro.models.*
import com.simplemobiletools.gallery.pro.svg.SvgSoftwareLayerSetter
import com.simplemobiletools.gallery.pro.views.MySquareImageView
import pl.droidsonroids.gif.GifDrawable
import java.io.File
import java.io.FileInputStream
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.util.HashSet
import java.util.LinkedHashSet
import kotlin.Comparator
import kotlin.collections.ArrayList
val Context.audioManager get() = getSystemService(Context.AUDIO_SERVICE) as AudioManager
fun Context.getHumanizedFilename(path: String): String {
val humanized = humanizePath(path)
return humanized.substring(humanized.lastIndexOf("/") + 1)
}
fun Context.launchSettings() {
startActivity(Intent(applicationContext, SettingsActivity::class.java))
}
val Context.config: Config get() = Config.newInstance(applicationContext)
val Context.widgetsDB: WidgetsDao get() = GalleryDatabase.getInstance(applicationContext).WidgetsDao()
val Context.mediaDB: MediumDao get() = GalleryDatabase.getInstance(applicationContext).MediumDao()
val Context.directoryDao: DirectoryDao get() = GalleryDatabase.getInstance(applicationContext).DirectoryDao()
val Context.favoritesDB: FavoritesDao get() = GalleryDatabase.getInstance(applicationContext).FavoritesDao()
val Context.dateTakensDB: DateTakensDao get() = GalleryDatabase.getInstance(applicationContext).DateTakensDao()
val Context.recycleBin: File get() = filesDir
val Context.recycleBinPath: String get() = filesDir.absolutePath
fun Context.movePinnedDirectoriesToFront(dirs: ArrayList<Directory>): ArrayList<Directory> {
val foundFolders = ArrayList<Directory>()
val pinnedFolders = config.pinnedFolders
dirs.forEach {
if (pinnedFolders.contains(it.path)) {
foundFolders.add(it)
}
}
dirs.removeAll(foundFolders)
dirs.addAll(0, foundFolders)
if (config.tempFolderPath.isNotEmpty()) {
val newFolder = dirs.firstOrNull { it.path == config.tempFolderPath }
if (newFolder != null) {
dirs.remove(newFolder)
dirs.add(0, newFolder)
}
}
if (config.showRecycleBinAtFolders && config.showRecycleBinLast) {
val binIndex = dirs.indexOfFirst { it.isRecycleBin() }
if (binIndex != -1) {
val bin = dirs.removeAt(binIndex)
dirs.add(bin)
}
}
return dirs
}
@Suppress("UNCHECKED_CAST")
fun Context.getSortedDirectories(source: ArrayList<Directory>): ArrayList<Directory> {
val sorting = config.directorySorting
val dirs = source.clone() as ArrayList<Directory>
if (sorting and SORT_BY_RANDOM != 0) {
dirs.shuffle()
return movePinnedDirectoriesToFront(dirs)
}
dirs.sortWith(Comparator { o1, o2 ->
o1 as Directory
o2 as Directory
var result = when {
sorting and SORT_BY_NAME != 0 -> {
if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
AlphanumericComparator().compare(o1.sortValue.toLowerCase(), o2.sortValue.toLowerCase())
} else {
o1.sortValue.toLowerCase().compareTo(o2.sortValue.toLowerCase())
}
}
sorting and SORT_BY_PATH != 0 -> {
if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
AlphanumericComparator().compare(o1.sortValue.toLowerCase(), o2.sortValue.toLowerCase())
} else {
o1.sortValue.toLowerCase().compareTo(o2.sortValue.toLowerCase())
}
}
sorting and SORT_BY_PATH != 0 -> AlphanumericComparator().compare(o1.sortValue.toLowerCase(), o2.sortValue.toLowerCase())
sorting and SORT_BY_SIZE != 0 -> (o1.sortValue.toLongOrNull() ?: 0).compareTo(o2.sortValue.toLongOrNull() ?: 0)
sorting and SORT_BY_DATE_MODIFIED != 0 -> (o1.sortValue.toLongOrNull() ?: 0).compareTo(o2.sortValue.toLongOrNull() ?: 0)
else -> (o1.sortValue.toLongOrNull() ?: 0).compareTo(o2.sortValue.toLongOrNull() ?: 0)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
result
})
return movePinnedDirectoriesToFront(dirs)
}
fun Context.getDirsToShow(dirs: ArrayList<Directory>, allDirs: ArrayList<Directory>, currentPathPrefix: String): ArrayList<Directory> {
return if (config.groupDirectSubfolders) {
dirs.forEach {
it.subfoldersCount = 0
it.subfoldersMediaCount = it.mediaCnt
}
val parentDirs = getDirectParentSubfolders(dirs, currentPathPrefix)
updateSubfolderCounts(dirs, parentDirs)
// show the current folder as an available option too, not just subfolders
if (currentPathPrefix.isNotEmpty()) {
val currentFolder = allDirs.firstOrNull { parentDirs.firstOrNull { it.path == currentPathPrefix } == null && it.path == currentPathPrefix }
currentFolder?.apply {
subfoldersCount = 1
parentDirs.add(this)
}
}
getSortedDirectories(parentDirs)
} else {
dirs.forEach { it.subfoldersMediaCount = it.mediaCnt }
dirs
}
}
fun Context.getDirectParentSubfolders(dirs: ArrayList<Directory>, currentPathPrefix: String): ArrayList<Directory> {
val folders = dirs.map { it.path }.sorted().toMutableSet() as HashSet<String>
val currentPaths = LinkedHashSet<String>()
val foldersWithoutMediaFiles = ArrayList<String>()
var newDirId = 1000L
for (path in folders) {
if (path == RECYCLE_BIN || path == FAVORITES) {
continue
}
if (currentPathPrefix.isNotEmpty()) {
if (!path.startsWith(currentPathPrefix, true)) {
continue
}
if (!File(path).parent.equals(currentPathPrefix, true)) {
continue
}
}
if (currentPathPrefix.isNotEmpty() && path == currentPathPrefix || File(path).parent.equals(currentPathPrefix, true)) {
currentPaths.add(path)
} else if (folders.any { !it.equals(path, true) && (File(path).parent.equals(it, true) || File(it).parent.equals(File(path).parent, true)) }) {
// if we have folders like
// /storage/emulated/0/Pictures/Images and
// /storage/emulated/0/Pictures/Screenshots,
// but /storage/emulated/0/Pictures is empty, still Pictures with the first folders thumbnails and proper other info
val parent = File(path).parent
if (parent != null && !folders.contains(parent) && dirs.none { it.path == parent }) {
currentPaths.add(parent)
val isSortingAscending = config.sorting.isSortingAscending()
val subDirs = dirs.filter { File(it.path).parent.equals(File(path).parent, true) } as ArrayList<Directory>
if (subDirs.isNotEmpty()) {
val lastModified = if (isSortingAscending) {
subDirs.minBy { it.modified }?.modified
} else {
subDirs.maxBy { it.modified }?.modified
} ?: 0
val dateTaken = if (isSortingAscending) {
subDirs.minBy { it.taken }?.taken
} else {
subDirs.maxBy { it.taken }?.taken
} ?: 0
var mediaTypes = 0
subDirs.forEach {
mediaTypes = mediaTypes or it.types
}
val directory = Directory(newDirId++,
parent,
subDirs.first().tmb,
getFolderNameFromPath(parent),
subDirs.sumBy { it.mediaCnt },
lastModified,
dateTaken,
subDirs.sumByLong { it.size },
getPathLocation(parent),
mediaTypes,
"")
directory.containsMediaFilesDirectly = false
dirs.add(directory)
currentPaths.add(parent)
foldersWithoutMediaFiles.add(parent)
}
}
} else {
currentPaths.add(path)
}
}
var areDirectSubfoldersAvailable = false
currentPaths.forEach {
val path = it
currentPaths.forEach {
if (!foldersWithoutMediaFiles.contains(it) && !it.equals(path, true) && File(it).parent?.equals(path, true) == true) {
areDirectSubfoldersAvailable = true
}
}
}
if (currentPathPrefix.isEmpty() && folders.contains(RECYCLE_BIN)) {
currentPaths.add(RECYCLE_BIN)
}
if (currentPathPrefix.isEmpty() && folders.contains(FAVORITES)) {
currentPaths.add(FAVORITES)
}
if (folders.size == currentPaths.size) {
return dirs.filter { currentPaths.contains(it.path) } as ArrayList<Directory>
}
folders.clear()
folders.addAll(currentPaths)
val dirsToShow = dirs.filter { folders.contains(it.path) } as ArrayList<Directory>
return if (areDirectSubfoldersAvailable) {
getDirectParentSubfolders(dirsToShow, currentPathPrefix)
} else {
dirsToShow
}
}
fun Context.updateSubfolderCounts(children: ArrayList<Directory>, parentDirs: ArrayList<Directory>) {
for (child in children) {
var longestSharedPath = ""
for (parentDir in parentDirs) {
if (parentDir.path == child.path) {
longestSharedPath = child.path
continue
}
if (child.path.startsWith(parentDir.path, true) && parentDir.path.length > longestSharedPath.length) {
longestSharedPath = parentDir.path
}
}
// make sure we count only the proper direct subfolders, grouped the same way as on the main screen
parentDirs.firstOrNull { it.path == longestSharedPath }?.apply {
if (path.equals(child.path, true) || path.equals(File(child.path).parent, true) || children.any { it.path.equals(File(child.path).parent, true) }) {
if (child.containsMediaFilesDirectly) {
subfoldersCount++
}
if (path != child.path) {
subfoldersMediaCount += child.mediaCnt
}
}
}
}
}
fun Context.getNoMediaFolders(callback: (folders: ArrayList<String>) -> Unit) {
ensureBackgroundThread {
val folders = ArrayList<String>()
val uri = Files.getContentUri("external")
val projection = arrayOf(Files.FileColumns.DATA)
val selection = "${Files.FileColumns.MEDIA_TYPE} = ? AND ${Files.FileColumns.TITLE} LIKE ?"
val selectionArgs = arrayOf(Files.FileColumns.MEDIA_TYPE_NONE.toString(), "%$NOMEDIA%")
val sortOrder = "${Files.FileColumns.DATE_MODIFIED} DESC"
val OTGPath = config.OTGPath
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)
if (cursor?.moveToFirst() == true) {
do {
val path = cursor.getStringValue(Files.FileColumns.DATA) ?: continue
val noMediaFile = File(path)
if (getDoesFilePathExist(noMediaFile.absolutePath, OTGPath) && noMediaFile.name == NOMEDIA) {
folders.add("${noMediaFile.parent}/")
}
} while (cursor.moveToNext())
}
} finally {
cursor?.close()
}
callback(folders)
}
}
fun Context.rescanFolderMedia(path: String) {
ensureBackgroundThread {
rescanFolderMediaSync(path)
}
}
fun Context.rescanFolderMediaSync(path: String) {
getCachedMedia(path) {
val cached = it
GetMediaAsynctask(applicationContext, path, false, false, false) {
ensureBackgroundThread {
val newMedia = it
val media = newMedia.filter { it is Medium } as ArrayList<Medium>
try {
mediaDB.insertAll(media)
cached.forEach {
if (!newMedia.contains(it)) {
val mediumPath = (it as? Medium)?.path
if (mediumPath != null) {
deleteDBPath(mediumPath)
}
}
}
} catch (ignored: Exception) {
}
}
}.execute()
}
}
fun Context.storeDirectoryItems(items: ArrayList<Directory>) {
ensureBackgroundThread {
directoryDao.insertAll(items)
}
}
fun Context.checkAppendingHidden(path: String, hidden: String, includedFolders: MutableSet<String>): String {
val dirName = getFolderNameFromPath(path)
return if (path.doesThisOrParentHaveNoMedia() && !path.isThisOrParentIncluded(includedFolders)) {
"$dirName $hidden"
} else {
dirName
}
}
fun Context.getFolderNameFromPath(path: String): String {
return when (path) {
internalStoragePath -> getString(R.string.internal)
sdCardPath -> getString(R.string.sd_card)
otgPath -> getString(R.string.usb)
FAVORITES -> getString(R.string.favorites)
RECYCLE_BIN -> getString(R.string.recycle_bin)
else -> path.getFilenameFromPath()
}
}
fun Context.loadImage(type: Int, path: String, target: MySquareImageView, horizontalScroll: Boolean, animateGifs: Boolean, cropThumbnails: Boolean,
skipMemoryCacheAtPaths: ArrayList<String>? = null) {
target.isHorizontalScrolling = horizontalScroll
if (type == TYPE_IMAGES || type == TYPE_VIDEOS || type == TYPE_RAWS || type == TYPE_PORTRAITS) {
if (type == TYPE_IMAGES && path.isPng()) {
loadPng(path, target, cropThumbnails, skipMemoryCacheAtPaths)
} else {
loadJpg(path, target, cropThumbnails, skipMemoryCacheAtPaths)
}
} else if (type == TYPE_GIFS) {
if (!animateGifs) {
loadStaticGIF(path, target, cropThumbnails, skipMemoryCacheAtPaths)
return
}
try {
val gifDrawable = GifDrawable(path)
target.setImageDrawable(gifDrawable)
gifDrawable.start()
target.scaleType = if (cropThumbnails) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.FIT_CENTER
} catch (e: Exception) {
loadStaticGIF(path, target, cropThumbnails, skipMemoryCacheAtPaths)
} catch (e: OutOfMemoryError) {
loadStaticGIF(path, target, cropThumbnails, skipMemoryCacheAtPaths)
}
} else if (type == TYPE_SVGS) {
loadSVG(path, target, cropThumbnails)
}
}
fun Context.addTempFolderIfNeeded(dirs: ArrayList<Directory>): ArrayList<Directory> {
val tempFolderPath = config.tempFolderPath
return if (tempFolderPath.isNotEmpty()) {
val directories = ArrayList<Directory>()
val newFolder = Directory(null, tempFolderPath, "", tempFolderPath.getFilenameFromPath(), 0, 0, 0, 0L, getPathLocation(tempFolderPath), 0, "")
directories.add(newFolder)
directories.addAll(dirs)
directories
} else {
dirs
}
}
fun Context.getPathLocation(path: String): Int {
return when {
isPathOnSD(path) -> LOCATION_SD
isPathOnOTG(path) -> LOCATION_OTG
else -> LOCATION_INTERNAL
}
}
fun Context.loadPng(path: String, target: MySquareImageView, cropThumbnails: Boolean, skipMemoryCacheAtPaths: ArrayList<String>? = null) {
val options = RequestOptions()
.signature(path.getFileSignature())
.skipMemoryCache(skipMemoryCacheAtPaths?.contains(path) == true)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.priority(Priority.LOW)
.format(DecodeFormat.PREFER_ARGB_8888)
val builder = Glide.with(applicationContext)
.asBitmap()
.load(path)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options).into(target)
}
fun Context.loadJpg(path: String, target: MySquareImageView, cropThumbnails: Boolean, skipMemoryCacheAtPaths: ArrayList<String>? = null) {
val options = RequestOptions()
.signature(path.getFileSignature())
.skipMemoryCache(skipMemoryCacheAtPaths?.contains(path) == true)
.priority(Priority.LOW)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
val builder = Glide.with(applicationContext)
.load(path)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options)
.transition(DrawableTransitionOptions.withCrossFade())
.into(target)
}
fun Context.loadStaticGIF(path: String, target: MySquareImageView, cropThumbnails: Boolean, skipMemoryCacheAtPaths: ArrayList<String>? = null) {
val options = RequestOptions()
.signature(path.getFileSignature())
.skipMemoryCache(skipMemoryCacheAtPaths?.contains(path) == true)
.priority(Priority.LOW)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
val builder = Glide.with(applicationContext)
.asBitmap() // make sure the GIF wont animate
.load(path)
if (cropThumbnails) options.centerCrop() else options.fitCenter()
builder.apply(options)
.into(target)
}
fun Context.loadSVG(path: String, target: MySquareImageView, cropThumbnails: Boolean) {
target.scaleType = if (cropThumbnails) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.FIT_CENTER
val options = RequestOptions().signature(path.getFileSignature())
Glide.with(applicationContext)
.`as`(PictureDrawable::class.java)
.listener(SvgSoftwareLayerSetter())
.load(path)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade())
.into(target)
}
fun Context.getCachedDirectories(getVideosOnly: Boolean = false, getImagesOnly: Boolean = false, forceShowHidden: Boolean = false, callback: (ArrayList<Directory>) -> Unit) {
ensureBackgroundThread {
val directories = try {
directoryDao.getAll() as ArrayList<Directory>
} catch (e: Exception) {
ArrayList<Directory>()
}
if (!config.showRecycleBinAtFolders) {
directories.removeAll { it.isRecycleBin() }
}
val shouldShowHidden = config.shouldShowHidden || forceShowHidden
val excludedPaths = config.excludedFolders
val includedPaths = config.includedFolders
var filteredDirectories = directories.filter { it.path.shouldFolderBeVisible(excludedPaths, includedPaths, shouldShowHidden, this) } as ArrayList<Directory>
val filterMedia = config.filterMedia
filteredDirectories = (when {
getVideosOnly -> filteredDirectories.filter { it.types and TYPE_VIDEOS != 0 }
getImagesOnly -> filteredDirectories.filter { it.types and TYPE_IMAGES != 0 }
else -> filteredDirectories.filter {
(filterMedia and TYPE_IMAGES != 0 && it.types and TYPE_IMAGES != 0) ||
(filterMedia and TYPE_VIDEOS != 0 && it.types and TYPE_VIDEOS != 0) ||
(filterMedia and TYPE_GIFS != 0 && it.types and TYPE_GIFS != 0) ||
(filterMedia and TYPE_RAWS != 0 && it.types and TYPE_RAWS != 0) ||
(filterMedia and TYPE_SVGS != 0 && it.types and TYPE_SVGS != 0) ||
(filterMedia and TYPE_PORTRAITS != 0 && it.types and TYPE_PORTRAITS != 0)
}
}) as ArrayList<Directory>
val hiddenString = resources.getString(R.string.hidden)
filteredDirectories.forEach {
it.name = if (it.path.doesThisOrParentHaveNoMedia() && !it.path.isThisOrParentIncluded(includedPaths)) {
"${it.name.removeSuffix(hiddenString).trim()} $hiddenString"
} else {
it.name.removeSuffix(hiddenString).trim()
}
}
val clone = filteredDirectories.clone() as ArrayList<Directory>
callback(clone.distinctBy { it.path.getDistinctPath() } as ArrayList<Directory>)
removeInvalidDBDirectories(filteredDirectories)
}
}
fun Context.getCachedMedia(path: String, getVideosOnly: Boolean = false, getImagesOnly: Boolean = false, callback: (ArrayList<ThumbnailItem>) -> Unit) {
ensureBackgroundThread {
val mediaFetcher = MediaFetcher(this)
val foldersToScan = if (path.isEmpty()) mediaFetcher.getFoldersToScan() else arrayListOf(path)
var media = ArrayList<Medium>()
if (path == FAVORITES) {
media.addAll(mediaDB.getFavorites())
}
if (path == RECYCLE_BIN) {
media.addAll(getUpdatedDeletedMedia())
}
if (config.filterMedia and TYPE_PORTRAITS != 0) {
val foldersToAdd = ArrayList<String>()
for (folder in foldersToScan) {
val allFiles = File(folder).listFiles() ?: continue
allFiles.filter { it.name.startsWith("img_", true) && it.isDirectory }.forEach {
foldersToAdd.add(it.absolutePath)
}
}
foldersToScan.addAll(foldersToAdd)
}
val shouldShowHidden = config.shouldShowHidden
foldersToScan.filter { path.isNotEmpty() || !config.isFolderProtected(it) }.forEach {
try {
val currMedia = mediaDB.getMediaFromPath(it)
media.addAll(currMedia)
} catch (ignored: Exception) {
}
}
if (!shouldShowHidden) {
media = media.filter { !it.path.contains("/.") } as ArrayList<Medium>
}
val filterMedia = config.filterMedia
media = (when {
getVideosOnly -> media.filter { it.type == TYPE_VIDEOS }
getImagesOnly -> media.filter { it.type == TYPE_IMAGES }
else -> media.filter {
(filterMedia and TYPE_IMAGES != 0 && it.type == TYPE_IMAGES) ||
(filterMedia and TYPE_VIDEOS != 0 && it.type == TYPE_VIDEOS) ||
(filterMedia and TYPE_GIFS != 0 && it.type == TYPE_GIFS) ||
(filterMedia and TYPE_RAWS != 0 && it.type == TYPE_RAWS) ||
(filterMedia and TYPE_SVGS != 0 && it.type == TYPE_SVGS) ||
(filterMedia and TYPE_PORTRAITS != 0 && it.type == TYPE_PORTRAITS)
}
}) as ArrayList<Medium>
val pathToUse = if (path.isEmpty()) SHOW_ALL else path
mediaFetcher.sortMedia(media, config.getFolderSorting(pathToUse))
val grouped = mediaFetcher.groupMedia(media, pathToUse)
callback(grouped.clone() as ArrayList<ThumbnailItem>)
val OTGPath = config.OTGPath
try {
val mediaToDelete = ArrayList<Medium>()
// creating a new thread intentionally, do not reuse the common background thread
Thread {
media.filter { !getDoesFilePathExist(it.path, OTGPath) }.forEach {
if (it.path.startsWith(recycleBinPath)) {
deleteDBPath(it.path)
} else {
mediaToDelete.add(it)
}
}
if (mediaToDelete.isNotEmpty()) {
mediaDB.deleteMedia(*mediaToDelete.toTypedArray())
mediaToDelete.filter { it.isFavorite }.forEach {
favoritesDB.deleteFavoritePath(it.path)
}
}
}.start()
} catch (ignored: Exception) {
}
}
}
fun Context.removeInvalidDBDirectories(dirs: ArrayList<Directory>? = null) {
val dirsToCheck = dirs ?: directoryDao.getAll()
val OTGPath = config.OTGPath
dirsToCheck.filter { !it.areFavorites() && !it.isRecycleBin() && !getDoesFilePathExist(it.path, OTGPath) && it.path != config.tempFolderPath }.forEach {
try {
directoryDao.deleteDirPath(it.path)
} catch (ignored: Exception) {
}
}
}
fun Context.updateDBMediaPath(oldPath: String, newPath: String) {
val newFilename = newPath.getFilenameFromPath()
val newParentPath = newPath.getParentPath()
try {
mediaDB.updateMedium(newFilename, newPath, newParentPath, oldPath)
favoritesDB.updateFavorite(newFilename, newPath, newParentPath, oldPath)
} catch (ignored: Exception) {
}
}
fun Context.updateDBDirectory(directory: Directory) {
try {
directoryDao.updateDirectory(directory.path, directory.tmb, directory.mediaCnt, directory.modified, directory.taken, directory.size, directory.types, directory.sortValue)
} catch (ignored: Exception) {
}
}
fun Context.getOTGFolderChildren(path: String) = getDocumentFile(path)?.listFiles()
fun Context.getOTGFolderChildrenNames(path: String) = getOTGFolderChildren(path)?.map { it.name }?.toMutableList()
fun Context.getFavoritePaths(): ArrayList<String> {
return try {
favoritesDB.getValidFavoritePaths() as ArrayList<String>
} catch (e: Exception) {
ArrayList()
}
}
fun Context.getFavoriteFromPath(path: String) = Favorite(null, path, path.getFilenameFromPath(), path.getParentPath())
fun Context.updateFavorite(path: String, isFavorite: Boolean) {
if (isFavorite) {
favoritesDB.insert(getFavoriteFromPath(path))
} else {
favoritesDB.deleteFavoritePath(path)
}
}
// remove the "recycle_bin" from the file path prefix, replace it with real bin path /data/user...
fun Context.getUpdatedDeletedMedia(): ArrayList<Medium> {
val media = try {
mediaDB.getDeletedMedia() as ArrayList<Medium>
} catch (ignored: Exception) {
ArrayList<Medium>()
}
media.forEach {
it.path = File(recycleBinPath, it.path.removePrefix(RECYCLE_BIN)).toString()
}
return media
}
fun Context.deleteDBPath(path: String) {
deleteMediumWithPath(path.replaceFirst(recycleBinPath, RECYCLE_BIN))
}
fun Context.deleteMediumWithPath(path: String) {
try {
mediaDB.deleteMediumPath(path)
} catch (ignored: Exception) {
}
}
fun Context.updateWidgets() {
val widgetIDs = AppWidgetManager.getInstance(applicationContext).getAppWidgetIds(ComponentName(applicationContext, MyWidgetProvider::class.java))
if (widgetIDs.isNotEmpty()) {
Intent(applicationContext, MyWidgetProvider::class.java).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIDs)
sendBroadcast(this)
}
}
}
// based on https://github.com/sannies/mp4parser/blob/master/examples/src/main/java/com/google/code/mp4parser/example/PrintStructure.java
fun Context.parseFileChannel(path: String, fc: FileChannel, level: Int, start: Long, end: Long, callback: () -> Unit) {
val FILE_CHANNEL_CONTAINERS = arrayListOf("moov", "trak", "mdia", "minf", "udta", "stbl")
try {
var iteration = 0
var currEnd = end
fc.position(start)
if (currEnd <= 0) {
currEnd = start + fc.size()
}
while (currEnd - fc.position() > 8) {
// just a check to avoid deadloop at some videos
if (iteration++ > 50) {
return
}
val begin = fc.position()
val byteBuffer = ByteBuffer.allocate(8)
fc.read(byteBuffer)
byteBuffer.rewind()
val size = IsoTypeReader.readUInt32(byteBuffer)
val type = IsoTypeReader.read4cc(byteBuffer)
val newEnd = begin + size
if (type == "uuid") {
val fis = FileInputStream(File(path))
fis.skip(begin)
val sb = StringBuilder()
val buffer = ByteArray(1024)
while (sb.length < size) {
val n = fis.read(buffer)
if (n != -1) {
sb.append(String(buffer, 0, n))
} else {
break
}
}
val xmlString = sb.toString().toLowerCase()
if (xmlString.contains("gspherical:projectiontype>equirectangular") || xmlString.contains("gspherical:projectiontype=\"equirectangular\"")) {
callback.invoke()
}
return
}
if (FILE_CHANNEL_CONTAINERS.contains(type)) {
parseFileChannel(path, fc, level + 1, begin + 8, newEnd, callback)
}
fc.position(newEnd)
}
} catch (ignored: Exception) {
}
}
fun Context.addPathToDB(path: String) {
ensureBackgroundThread {
if (!getDoesFilePathExist(path)) {
return@ensureBackgroundThread
}
val type = when {
path.isVideoFast() -> TYPE_VIDEOS
path.isGif() -> TYPE_GIFS
path.isRawFast() -> TYPE_RAWS
path.isSvg() -> TYPE_SVGS
path.isPortrait() -> TYPE_PORTRAITS
else -> TYPE_IMAGES
}
try {
val isFavorite = favoritesDB.isFavorite(path)
val videoDuration = if (type == TYPE_VIDEOS) getDuration(path) ?: 0 else 0
val medium = Medium(null, path.getFilenameFromPath(), path, path.getParentPath(), System.currentTimeMillis(), System.currentTimeMillis(),
File(path).length(), type, videoDuration, isFavorite, 0L)
mediaDB.insert(medium)
} catch (ignored: Exception) {
}
}
}
fun Context.createDirectoryFromMedia(path: String, curMedia: ArrayList<Medium>, albumCovers: ArrayList<AlbumCover>, hiddenString: String,
includedFolders: MutableSet<String>, getProperFileSize: Boolean): Directory {
val OTGPath = config.OTGPath
val grouped = MediaFetcher(this).groupMedia(curMedia, path)
var thumbnail: String? = null
albumCovers.forEach {
if (it.path == path && getDoesFilePathExist(it.tmb, OTGPath)) {
thumbnail = it.tmb
}
}
if (thumbnail == null) {
val sortedMedia = grouped.filter { it is Medium }.toMutableList() as ArrayList<Medium>
thumbnail = sortedMedia.firstOrNull { getDoesFilePathExist(it.path, OTGPath) }?.path ?: ""
}
if (config.OTGPath.isNotEmpty() && thumbnail!!.startsWith(config.OTGPath)) {
thumbnail = thumbnail!!.getOTGPublicPath(applicationContext)
}
val isSortingAscending = config.directorySorting.isSortingAscending()
val defaultMedium = Medium(0, "", "", "", 0L, 0L, 0L, 0, 0, false, 0L)
val firstItem = curMedia.firstOrNull() ?: defaultMedium
val lastItem = curMedia.lastOrNull() ?: defaultMedium
val dirName = checkAppendingHidden(path, hiddenString, includedFolders)
val lastModified = if (isSortingAscending) Math.min(firstItem.modified, lastItem.modified) else Math.max(firstItem.modified, lastItem.modified)
val dateTaken = if (isSortingAscending) Math.min(firstItem.taken, lastItem.taken) else Math.max(firstItem.taken, lastItem.taken)
val size = if (getProperFileSize) curMedia.sumByLong { it.size } else 0L
val mediaTypes = curMedia.getDirMediaTypes()
val sortValue = getDirectorySortingValue(curMedia, path, dirName, size)
return Directory(null, path, thumbnail!!, dirName, curMedia.size, lastModified, dateTaken, size, getPathLocation(path), mediaTypes, sortValue)
}
fun Context.getDirectorySortingValue(media: ArrayList<Medium>, path: String, name: String, size: Long): String {
val sorting = config.directorySorting
val sorted = when {
sorting and SORT_BY_NAME != 0 -> return name
sorting and SORT_BY_PATH != 0 -> return path
sorting and SORT_BY_SIZE != 0 -> return size.toString()
sorting and SORT_BY_DATE_MODIFIED != 0 -> media.sortedBy { it.modified }
sorting and SORT_BY_DATE_TAKEN != 0 -> media.sortedBy { it.taken }
else -> media
}
val relevantMedium = if (sorting.isSortingAscending()) {
sorted.firstOrNull() ?: return ""
} else {
sorted.lastOrNull() ?: return ""
}
val result: Any = when {
sorting and SORT_BY_DATE_MODIFIED != 0 -> relevantMedium.modified
sorting and SORT_BY_DATE_TAKEN != 0 -> relevantMedium.taken
else -> 0
}
return result.toString()
}
fun Context.updateDirectoryPath(path: String) {
val mediaFetcher = MediaFetcher(applicationContext)
val getImagesOnly = false
val getVideosOnly = false
val hiddenString = getString(R.string.hidden)
val albumCovers = config.parseAlbumCovers()
val includedFolders = config.includedFolders
val sorting = config.getFolderSorting(path)
val grouping = config.getFolderGrouping(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 getProperFileSize = config.directorySorting and SORT_BY_SIZE != 0
val favoritePaths = getFavoritePaths()
val curMedia = mediaFetcher.getFilesFrom(path, getImagesOnly, getVideosOnly, getProperDateTaken, getProperLastModified, getProperFileSize, favoritePaths, false)
val directory = createDirectoryFromMedia(path, curMedia, albumCovers, hiddenString, includedFolders, getProperFileSize)
updateDBDirectory(directory)
}
fun Context.getFileDateTaken(path: String): Long {
val projection = arrayOf(
Images.Media.DATE_TAKEN
)
val uri = Files.getContentUri("external")
val selection = "${Images.Media.DATA} = ?"
val selectionArgs = arrayOf(path)
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getLongValue(Images.Media.DATE_TAKEN)
}
}
} catch (ignored: Exception) {
}
return 0L
}

View file

@ -0,0 +1,5 @@
package com.simplemobiletools.gallery.pro.extensions
import com.simplemobiletools.commons.models.FileDirItem
fun FileDirItem.isDownloadsFolder() = path.isDownloadsFolder()

View file

@ -0,0 +1,5 @@
package com.simplemobiletools.gallery.pro.extensions
import com.simplemobiletools.commons.helpers.SORT_DESCENDING
fun Int.isSortingAscending() = this and SORT_DESCENDING == 0

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.extensions
package com.simplemobiletools.gallery.pro.extensions
import android.content.Context
import android.content.res.Resources

View file

@ -0,0 +1,69 @@
package com.simplemobiletools.gallery.pro.extensions
import android.content.Context
import android.os.Environment
import com.simplemobiletools.commons.extensions.containsNoMedia
import com.simplemobiletools.commons.extensions.doesParentHaveNoMedia
import java.io.File
import java.io.IOException
fun String.isThisOrParentIncluded(includedPaths: MutableSet<String>) = includedPaths.any { equals(it, true) } || includedPaths.any { "$this/".startsWith("$it/", true) }
fun String.isThisOrParentExcluded(excludedPaths: MutableSet<String>) = excludedPaths.any { equals(it, true) } || excludedPaths.any { "$this/".startsWith("$it/", true) }
fun String.shouldFolderBeVisible(excludedPaths: MutableSet<String>, includedPaths: MutableSet<String>, showHidden: Boolean, context: Context): Boolean {
if (isEmpty()) {
return false
}
val file = File(this)
if (file.name.startsWith("img_", true)) {
val files = file.list()
if (files != null) {
if (files.any { it.contains("burst", true) }) {
return false
}
}
}
if (!showHidden && file.isHidden) {
return false
} else if (includedPaths.contains(this)) {
return true
}
val containsNoMedia = if (showHidden) {
false
} else {
file.containsNoMedia()
}
return if (!showHidden && containsNoMedia) {
false
} else if (excludedPaths.contains(this)) {
false
} else if (isThisOrParentIncluded(includedPaths)) {
true
} else if (isThisOrParentExcluded(excludedPaths)) {
false
} else if (!showHidden && file.isDirectory && file.canonicalFile == file.absoluteFile) {
var containsNoMediaOrDot = containsNoMedia || contains("/.")
if (!containsNoMediaOrDot) {
containsNoMediaOrDot = file.doesParentHaveNoMedia()
}
!containsNoMediaOrDot
} else {
true
}
}
// recognize /sdcard/DCIM as the same folder as /storage/emulated/0/DCIM
fun String.getDistinctPath(): String {
return try {
File(this).canonicalPath.toLowerCase()
} catch (e: IOException) {
toLowerCase()
}
}
fun String.isDownloadsFolder() = equals(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(), true)

View file

@ -1,4 +1,4 @@
package com.simplemobiletools.gallery.extensions
package com.simplemobiletools.gallery.pro.extensions
import android.os.SystemClock
import android.view.MotionEvent

View file

@ -0,0 +1,815 @@
package com.simplemobiletools.gallery.pro.fragments
import android.content.Intent
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.graphics.drawable.Drawable
import android.graphics.drawable.PictureDrawable
import android.media.ExifInterface.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.alexvasilkov.gestures.GestureController
import com.alexvasilkov.gestures.State
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
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.load.resource.bitmap.Rotate
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.davemorrissey.labs.subscaleview.DecoderFactory
import com.davemorrissey.labs.subscaleview.ImageDecoder
import com.davemorrissey.labs.subscaleview.ImageRegionDecoder
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.activities.PanoramaPhotoActivity
import com.simplemobiletools.gallery.pro.activities.PhotoActivity
import com.simplemobiletools.gallery.pro.adapters.PortraitPhotosAdapter
import com.simplemobiletools.gallery.pro.extensions.*
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.models.Medium
import com.simplemobiletools.gallery.pro.svg.SvgSoftwareLayerSetter
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import it.sephiroth.android.library.exif2.ExifInterface
import kotlinx.android.synthetic.main.pager_photo_item.view.*
import org.apache.sanselan.common.byteSources.ByteSourceInputStream
import org.apache.sanselan.formats.jpeg.JpegImageParser
import pl.droidsonroids.gif.InputSource
import java.io.File
import java.io.FileOutputStream
import java.util.*
import kotlin.math.ceil
class PhotoFragment : ViewPagerFragment() {
private val DEFAULT_DOUBLE_TAP_ZOOM = 2f
private val ZOOMABLE_VIEW_LOAD_DELAY = 100L
private val SAME_ASPECT_RATIO_THRESHOLD = 0.01
// devices with good displays, but the rest of the hardware not good enough for them
private val WEIRD_DEVICES = arrayListOf(
"motorola xt1685",
"google nexus 5x"
)
var mCurrentRotationDegrees = 0
private var mIsFragmentVisible = false
private var mIsFullscreen = false
private var mWasInit = false
private var mIsPanorama = false
private var mIsSubsamplingVisible = false // checking view.visibility is unreliable, use an extra variable for it
private var mCurrentPortraitPhotoPath = ""
private var mOriginalPath = ""
private var mImageOrientation = -1
private var mLoadZoomableViewHandler = Handler()
private var mScreenWidth = 0
private var mScreenHeight = 0
private var mCurrentGestureViewZoom = 1f
private var mStoredShowExtendedDetails = false
private var mStoredHideExtendedDetails = false
private var mStoredAllowDeepZoomableImages = false
private var mStoredShowHighestQuality = false
private var mStoredExtendedDetails = 0
private lateinit var mView: ViewGroup
private lateinit var mMedium: Medium
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
mView = (inflater.inflate(R.layout.pager_photo_item, container, false) as ViewGroup)
if (!arguments!!.getBoolean(SHOULD_INIT_FRAGMENT, true)) {
return mView
}
mMedium = arguments!!.getSerializable(MEDIUM) as Medium
mOriginalPath = mMedium.path
mView.apply {
subsampling_view.setOnClickListener { photoClicked() }
gestures_view.setOnClickListener { photoClicked() }
gif_view.setOnClickListener { photoClicked() }
instant_prev_item.setOnClickListener { listener?.goToPrevItem() }
instant_next_item.setOnClickListener { listener?.goToNextItem() }
panorama_outline.setOnClickListener { openPanorama() }
instant_prev_item.parentView = container
instant_next_item.parentView = container
photo_brightness_controller.initialize(activity!!, slide_info, true, container, singleTap = { x, y ->
mView.apply {
if (subsampling_view.isVisible()) {
subsampling_view.sendFakeClick(x, y)
} else {
gestures_view.sendFakeClick(x, y)
}
}
})
if (context.config.allowDownGesture) {
gif_view.setOnTouchListener { v, event ->
if (gif_view_frame.controller.state.zoom == 1f) {
handleEvent(event)
}
false
}
gestures_view.controller.addOnStateChangeListener(object : GestureController.OnStateChangeListener {
override fun onStateChanged(state: State) {
mCurrentGestureViewZoom = state.zoom
}
})
gestures_view.setOnTouchListener { v, event ->
if (mCurrentGestureViewZoom == 1f) {
handleEvent(event)
}
false
}
subsampling_view.setOnTouchListener { v, event ->
if (subsampling_view.isZoomedOut()) {
handleEvent(event)
}
false
}
}
}
checkScreenDimensions()
storeStateVariables()
if (!mIsFragmentVisible && activity is PhotoActivity) {
mIsFragmentVisible = true
}
if (mMedium.path.startsWith("content://") && !mMedium.path.startsWith("content://mms/")) {
mMedium.path = context!!.getRealPathFromURI(Uri.parse(mOriginalPath)) ?: mMedium.path
if (mMedium.path.isEmpty()) {
var out: FileOutputStream? = null
try {
var inputStream = context!!.contentResolver.openInputStream(Uri.parse(mOriginalPath))
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(mOriginalPath))
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(mOriginalPath).lastPathSegment)
out = FileOutputStream(file)
rotated.compress(Bitmap.CompressFormat.JPEG, 100, out)
mMedium.path = file.absolutePath
} catch (e: Exception) {
activity!!.toast(R.string.unknown_error_occurred)
return mView
} finally {
out?.close()
}
}
}
mIsFullscreen = activity!!.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == View.SYSTEM_UI_FLAG_FULLSCREEN
loadImage()
initExtendedDetails()
mWasInit = true
checkIfPanorama()
updateInstantSwitchWidths()
return mView
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
override fun onResume() {
super.onResume()
val config = context!!.config
if (mWasInit && (config.showExtendedDetails != mStoredShowExtendedDetails || config.extendedDetails != mStoredExtendedDetails)) {
initExtendedDetails()
}
if (mWasInit) {
if (config.allowZoomingImages != mStoredAllowDeepZoomableImages || config.showHighestQuality != mStoredShowHighestQuality) {
mIsSubsamplingVisible = false
mView.subsampling_view.beGone()
loadImage()
} else if (mMedium.isGIF()) {
loadGif()
}
}
val allowPhotoGestures = config.allowPhotoGestures
val allowInstantChange = config.allowInstantChange
mView.apply {
photo_brightness_controller.beVisibleIf(allowPhotoGestures)
instant_prev_item.beVisibleIf(allowInstantChange)
instant_next_item.beVisibleIf(allowInstantChange)
}
storeStateVariables()
}
override fun onDestroyView() {
super.onDestroyView()
if (activity?.isDestroyed == false) {
mView.subsampling_view.recycle()
try {
if (context != null) {
Glide.with(context!!).clear(mView.gestures_view)
}
} catch (ignored: Exception) {
}
}
mLoadZoomableViewHandler.removeCallbacksAndMessages(null)
if (mCurrentRotationDegrees != 0) {
ensureBackgroundThread {
val path = mMedium.path
(activity as? BaseSimpleActivity)?.saveRotatedImageToFile(path, path, mCurrentRotationDegrees, false) {}
}
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
if (!mWasInit) {
return
}
// avoid GIFs being skewed, played in wrong aspect ratio
if (mMedium.isGIF()) {
mView.onGlobalLayout {
if (activity != null) {
measureScreen()
Handler().postDelayed({
mView.gif_view_frame.controller.resetState()
loadGif()
}, 50)
}
}
} else {
hideZoomableView()
loadImage()
}
measureScreen()
initExtendedDetails()
updateInstantSwitchWidths()
}
override fun setMenuVisibility(menuVisible: Boolean) {
super.setMenuVisibility(menuVisible)
mIsFragmentVisible = menuVisible
if (mWasInit) {
if (!mMedium.isGIF()) {
photoFragmentVisibilityChanged(menuVisible)
}
}
}
private fun storeStateVariables() {
context!!.config.apply {
mStoredShowExtendedDetails = showExtendedDetails
mStoredHideExtendedDetails = hideExtendedDetails
mStoredAllowDeepZoomableImages = allowZoomingImages
mStoredShowHighestQuality = showHighestQuality
mStoredExtendedDetails = extendedDetails
}
}
private fun checkScreenDimensions() {
if (mScreenWidth == 0 || mScreenHeight == 0) {
measureScreen()
}
}
private fun measureScreen() {
val metrics = DisplayMetrics()
activity?.windowManager?.defaultDisplay?.getRealMetrics(metrics)
mScreenWidth = metrics.widthPixels
mScreenHeight = metrics.heightPixels
}
private fun photoFragmentVisibilityChanged(isVisible: Boolean) {
if (isVisible) {
scheduleZoomableView()
} else {
hideZoomableView()
}
}
private fun degreesForRotation(orientation: Int) = when (orientation) {
ORIENTATION_ROTATE_270 -> 270
ORIENTATION_ROTATE_180 -> 180
ORIENTATION_ROTATE_90 -> 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() {
checkScreenDimensions()
if (mMedium.isPortrait() && context != null) {
showPortraitStripe()
}
mImageOrientation = getImageOrientation()
when {
mMedium.isGIF() -> loadGif()
mMedium.isSVG() -> loadSVG()
else -> loadBitmap()
}
}
private fun loadGif() {
try {
val pathToLoad = getPathToLoad(mMedium)
val source = if (pathToLoad.startsWith("content://") || pathToLoad.startsWith("file://")) {
InputSource.UriSource(context!!.contentResolver, Uri.parse(pathToLoad))
} else {
InputSource.FileSource(pathToLoad)
}
mView.apply {
gestures_view.beGone()
gif_view.setInputSource(source)
gif_view_frame.beVisible()
}
} catch (e: Exception) {
loadBitmap()
} catch (e: OutOfMemoryError) {
loadBitmap()
}
}
private fun loadSVG() {
Glide.with(context!!)
.`as`(PictureDrawable::class.java)
.listener(SvgSoftwareLayerSetter())
.load(mMedium.path)
.into(mView.gestures_view)
}
private fun loadBitmap(addZoomableView: Boolean = true) {
val priority = if (mIsFragmentVisible) Priority.IMMEDIATE else Priority.NORMAL
val options = RequestOptions()
.signature(getFilePathToShow().getFileSignature())
.format(DecodeFormat.PREFER_ARGB_8888)
.priority(priority)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.fitCenter()
if (mCurrentRotationDegrees != 0) {
options.transform(Rotate(mCurrentRotationDegrees))
options.diskCacheStrategy(DiskCacheStrategy.NONE)
}
if (context == null) {
return
}
Glide.with(context!!)
.load(getFilePathToShow())
.apply(options)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
if (activity != null && !activity!!.isDestroyed && !activity!!.isFinishing) {
tryLoadingWithPicasso(addZoomableView)
}
return false
}
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
mView.gestures_view.controller.settings.isZoomEnabled = mMedium.isRaw() || mCurrentRotationDegrees != 0 || context?.config?.allowZoomingImages == false
if (mIsFragmentVisible && addZoomableView) {
scheduleZoomableView()
}
return false
}
}).into(mView.gestures_view)
}
private fun tryLoadingWithPicasso(addZoomableView: Boolean) {
var pathToLoad = if (getFilePathToShow().startsWith("content://")) getFilePathToShow() else "file://${getFilePathToShow()}"
pathToLoad = pathToLoad.replace("%", "%25").replace("#", "%23")
try {
val picasso = Picasso.get()
.load(pathToLoad)
.centerInside()
.stableKey(mMedium.path.getFileKey())
.resize(mScreenWidth, mScreenHeight)
if (mCurrentRotationDegrees != 0) {
picasso.rotate(mCurrentRotationDegrees.toFloat())
} else {
degreesForRotation(mImageOrientation).toFloat()
}
picasso.into(mView.gestures_view, object : Callback {
override fun onSuccess() {
mView.gestures_view.controller.settings.isZoomEnabled = mMedium.isRaw() || mCurrentRotationDegrees != 0 || context?.config?.allowZoomingImages == false
if (mIsFragmentVisible && addZoomableView) {
scheduleZoomableView()
}
}
override fun onError(e: Exception?) {
if (mMedium.path != mOriginalPath) {
mMedium.path = mOriginalPath
loadImage()
checkIfPanorama()
}
}
})
} catch (ignored: Exception) {
}
}
private fun showPortraitStripe() {
val files = File(mMedium.parentPath).listFiles()?.toMutableList() as? ArrayList<File>
if (files != null) {
val screenWidth = context!!.realScreenSize.x
val itemWidth = context!!.resources.getDimension(R.dimen.portrait_photos_stripe_height).toInt() + context!!.resources.getDimension(R.dimen.one_dp).toInt()
val sideWidth = screenWidth / 2 - itemWidth / 2
val fakeItemsCnt = ceil(sideWidth / itemWidth.toDouble()).toInt()
val paths = fillPhotoPaths(files, fakeItemsCnt)
var curWidth = itemWidth
while (curWidth < screenWidth) {
curWidth += itemWidth
}
val sideElementWidth = curWidth - screenWidth
val adapter = PortraitPhotosAdapter(context!!, paths, sideElementWidth) { position, x ->
if (mIsFullscreen) {
return@PortraitPhotosAdapter
}
mView.photo_portrait_stripe.smoothScrollBy((x + itemWidth / 2) - screenWidth / 2, 0)
if (paths[position] != mCurrentPortraitPhotoPath) {
mCurrentPortraitPhotoPath = paths[position]
hideZoomableView()
loadBitmap()
}
}
mView.photo_portrait_stripe.adapter = adapter
setupStripeBottomMargin()
val coverIndex = getCoverImageIndex(paths)
if (coverIndex != -1) {
mCurrentPortraitPhotoPath = paths[coverIndex]
setupStripeUpListener(adapter, screenWidth, itemWidth)
mView.photo_portrait_stripe.onGlobalLayout {
mView.photo_portrait_stripe.scrollBy((coverIndex - fakeItemsCnt) * itemWidth, 0)
adapter.setCurrentPhoto(coverIndex)
mView.photo_portrait_stripe_wrapper.beVisible()
if (mIsFullscreen) {
mView.photo_portrait_stripe_wrapper.alpha = 0f
}
}
}
}
}
private fun fillPhotoPaths(files: ArrayList<File>, fakeItemsCnt: Int): ArrayList<String> {
val paths = ArrayList<String>()
for (i in 0 until fakeItemsCnt) {
paths.add("")
}
files.forEach {
paths.add(it.absolutePath)
}
for (i in 0 until fakeItemsCnt) {
paths.add("")
}
return paths
}
private fun setupStripeBottomMargin() {
var bottomMargin = context!!.navigationBarHeight + context!!.resources.getDimension(R.dimen.normal_margin).toInt()
if (context!!.config.bottomActions) {
bottomMargin += context!!.resources.getDimension(R.dimen.bottom_actions_height).toInt()
}
(mView.photo_portrait_stripe_wrapper.layoutParams as RelativeLayout.LayoutParams).bottomMargin = bottomMargin
}
private fun getCoverImageIndex(paths: ArrayList<String>): Int {
var coverIndex = -1
paths.forEachIndexed { index, path ->
if (path.contains("cover", true)) {
coverIndex = index
}
}
if (coverIndex == -1) {
paths.forEachIndexed { index, path ->
if (path.isNotEmpty()) {
coverIndex = index
}
}
}
return coverIndex
}
private fun setupStripeUpListener(adapter: PortraitPhotosAdapter, screenWidth: Int, itemWidth: Int) {
mView.photo_portrait_stripe.setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_UP || event.action == MotionEvent.ACTION_CANCEL) {
var closestIndex = -1
var closestDistance = Integer.MAX_VALUE
val center = screenWidth / 2
for ((key, value) in adapter.views) {
val distance = Math.abs(value.x.toInt() + itemWidth / 2 - center)
if (distance < closestDistance) {
closestDistance = distance
closestIndex = key
}
}
Handler().postDelayed({
adapter.performClickOn(closestIndex)
}, 100)
}
false
}
}
private fun getFilePathToShow() = if (mMedium.isPortrait()) mCurrentPortraitPhotoPath else getPathToLoad(mMedium)
private fun openPanorama() {
Intent(context, PanoramaPhotoActivity::class.java).apply {
putExtra(PATH, mMedium.path)
startActivity(this)
}
}
private fun scheduleZoomableView() {
mLoadZoomableViewHandler.removeCallbacksAndMessages(null)
mLoadZoomableViewHandler.postDelayed({
if (mIsFragmentVisible && context?.config?.allowZoomingImages == true && (mMedium.isImage() || mMedium.isPortrait()) && !mIsSubsamplingVisible) {
addZoomableView()
}
}, ZOOMABLE_VIEW_LOAD_DELAY)
}
private fun addZoomableView() {
val rotation = degreesForRotation(mImageOrientation)
mIsSubsamplingVisible = true
val config = context!!.config
val showHighestQuality = config.showHighestQuality
val minTileDpi = if (showHighestQuality) -1 else getMinTileDpi()
val bitmapDecoder = object : DecoderFactory<ImageDecoder> {
override fun make() = MyGlideImageDecoder(rotation, mMedium.getSignature())
}
val regionDecoder = object : DecoderFactory<ImageRegionDecoder> {
override fun make() = PicassoRegionDecoder(showHighestQuality, mScreenWidth, mScreenHeight, minTileDpi)
}
var newOrientation = (rotation + mCurrentRotationDegrees) % 360
if (newOrientation < 0) {
newOrientation += 360
}
mView.subsampling_view.apply {
setMaxTileSize(if (showHighestQuality) Integer.MAX_VALUE else 4096)
setMinimumTileDpi(minTileDpi)
background = ColorDrawable(Color.TRANSPARENT)
bitmapDecoderFactory = bitmapDecoder
regionDecoderFactory = regionDecoder
maxScale = 10f
beVisible()
rotationEnabled = config.allowRotatingWithGestures
isOneToOneZoomEnabled = config.allowOneToOneZoom
orientation = newOrientation
setImage(getFilePathToShow())
onImageEventListener = object : SubsamplingScaleImageView.OnImageEventListener {
override fun onReady() {
background = ColorDrawable(if (config.blackBackground) Color.BLACK else config.backgroundColor)
val useWidth = if (mImageOrientation == ORIENTATION_ROTATE_90 || mImageOrientation == ORIENTATION_ROTATE_270) sHeight else sWidth
val useHeight = if (mImageOrientation == ORIENTATION_ROTATE_90 || mImageOrientation == ORIENTATION_ROTATE_270) sWidth else sHeight
doubleTapZoomScale = getDoubleTapZoomScale(useWidth, useHeight)
}
override fun onImageLoadError(e: Exception) {
mView.gestures_view.controller.settings.isZoomEnabled = true
background = ColorDrawable(Color.TRANSPARENT)
mIsSubsamplingVisible = false
beGone()
}
override fun onImageRotation(degrees: Int) {
val fullRotation = (rotation + degrees) % 360
val useWidth = if (fullRotation == 90 || fullRotation == 270) sHeight else sWidth
val useHeight = if (fullRotation == 90 || fullRotation == 270) sWidth else sHeight
doubleTapZoomScale = getDoubleTapZoomScale(useWidth, useHeight)
mCurrentRotationDegrees = (mCurrentRotationDegrees + degrees) % 360
loadBitmap(false)
activity?.invalidateOptionsMenu()
}
}
}
}
private fun getMinTileDpi(): Int {
val metrics = resources.displayMetrics
val averageDpi = (metrics.xdpi + metrics.ydpi) / 2
val device = "${Build.BRAND} ${Build.MODEL}".toLowerCase()
return when {
WEIRD_DEVICES.contains(device) -> WEIRD_TILE_DPI
averageDpi > 400 -> HIGH_TILE_DPI
averageDpi > 300 -> NORMAL_TILE_DPI
else -> LOW_TILE_DPI
}
}
private fun checkIfPanorama() {
mIsPanorama = try {
val inputStream = if (mMedium.path.startsWith("content:/")) context!!.contentResolver.openInputStream(Uri.parse(mMedium.path)) else File(mMedium.path).inputStream()
val imageParser = JpegImageParser().getXmpXml(ByteSourceInputStream(inputStream, mMedium.name), HashMap<String, Any>())
imageParser.contains("GPano:UsePanoramaViewer=\"True\"", true) ||
imageParser.contains("<GPano:UsePanoramaViewer>True</GPano:UsePanoramaViewer>", true) ||
imageParser.contains("GPano:FullPanoWidthPixels=")
} catch (e: Exception) {
false
} catch (e: OutOfMemoryError) {
false
}
mView.panorama_outline.beVisibleIf(mIsPanorama)
if (mIsFullscreen) {
mView.panorama_outline.alpha = 0f
}
}
private fun getImageOrientation(): Int {
val defaultOrientation = -1
var orient = defaultOrientation
try {
val path = getFilePathToShow()
orient = if (path.startsWith("content:/")) {
val inputStream = context!!.contentResolver.openInputStream(Uri.parse(path))
val exif = ExifInterface()
exif.readExif(inputStream, ExifInterface.Options.OPTION_ALL)
val tag = exif.getTag(ExifInterface.TAG_ORIENTATION)
tag?.getValueAsInt(defaultOrientation) ?: defaultOrientation
} else {
val exif = android.media.ExifInterface(path)
exif.getAttributeInt(TAG_ORIENTATION, defaultOrientation)
}
if (orient == defaultOrientation || context!!.isPathOnOTG(getFilePathToShow())) {
val uri = if (path.startsWith("content:/")) Uri.parse(path) else Uri.fromFile(File(path))
val inputStream = context!!.contentResolver.openInputStream(uri)
val exif2 = ExifInterface()
exif2.readExif(inputStream, ExifInterface.Options.OPTION_ALL)
orient = exif2.getTag(ExifInterface.TAG_ORIENTATION)?.getValueAsInt(defaultOrientation) ?: defaultOrientation
}
} catch (ignored: Exception) {
} catch (ignored: OutOfMemoryError) {
}
return orient
}
private fun getDoubleTapZoomScale(width: Int, height: Int): Float {
val bitmapAspectRatio = height / width.toFloat()
val screenAspectRatio = mScreenHeight / mScreenWidth.toFloat()
return if (context == null || Math.abs(bitmapAspectRatio - screenAspectRatio) < SAME_ASPECT_RATIO_THRESHOLD) {
DEFAULT_DOUBLE_TAP_ZOOM
} else if (context!!.portrait && bitmapAspectRatio <= screenAspectRatio) {
mScreenHeight / height.toFloat()
} else if (context!!.portrait && bitmapAspectRatio > screenAspectRatio) {
mScreenWidth / width.toFloat()
} else if (!context!!.portrait && bitmapAspectRatio >= screenAspectRatio) {
mScreenWidth / width.toFloat()
} else if (!context!!.portrait && bitmapAspectRatio < screenAspectRatio) {
mScreenHeight / height.toFloat()
} else {
DEFAULT_DOUBLE_TAP_ZOOM
}
}
fun rotateImageViewBy(degrees: Int) {
if (mIsSubsamplingVisible) {
mView.subsampling_view.rotateBy(degrees)
} else {
mCurrentRotationDegrees = (mCurrentRotationDegrees + degrees) % 360
mLoadZoomableViewHandler.removeCallbacksAndMessages(null)
mIsSubsamplingVisible = false
loadBitmap()
}
}
private fun initExtendedDetails() {
if (context!!.config.showExtendedDetails) {
mView.photo_details.apply {
beInvisible() // make it invisible so we can measure it, but not show yet
text = getMediumExtendedDetails(mMedium)
onGlobalLayout {
if (isAdded) {
val realY = getExtendedDetailsY(height)
if (realY > 0) {
y = realY
beVisibleIf(text.isNotEmpty())
alpha = if (!context!!.config.hideExtendedDetails || !mIsFullscreen) 1f else 0f
}
}
}
}
} else {
mView.photo_details.beGone()
}
}
private fun hideZoomableView() {
if (context?.config?.allowZoomingImages == true) {
mIsSubsamplingVisible = false
mView.subsampling_view.recycle()
mView.subsampling_view.beGone()
mLoadZoomableViewHandler.removeCallbacksAndMessages(null)
}
}
private fun photoClicked() {
listener?.fragmentClicked()
}
private fun updateInstantSwitchWidths() {
mView.instant_prev_item.layoutParams.width = mScreenWidth / 7
mView.instant_next_item.layoutParams.width = mScreenWidth / 7
}
override fun fullscreenToggled(isFullscreen: Boolean) {
this.mIsFullscreen = isFullscreen
mView.apply {
photo_details.apply {
if (mStoredShowExtendedDetails && isVisible() && context != null && resources != null) {
animate().y(getExtendedDetailsY(height))
if (mStoredHideExtendedDetails) {
animate().alpha(if (isFullscreen) 0f else 1f).start()
}
}
}
if (mIsPanorama) {
panorama_outline.animate().alpha(if (isFullscreen) 0f else 1f).start()
panorama_outline.isClickable = !isFullscreen
}
if (mWasInit && mMedium.isPortrait()) {
photo_portrait_stripe_wrapper.animate().alpha(if (isFullscreen) 0f else 1f).start()
}
}
}
private fun getExtendedDetailsY(height: Int): Float {
val smallMargin = context?.resources?.getDimension(R.dimen.small_margin) ?: return 0f
val fullscreenOffset = smallMargin + if (mIsFullscreen) 0 else context!!.navigationBarHeight
val actionsHeight = if (context!!.config.bottomActions && !mIsFullscreen) resources.getDimension(R.dimen.bottom_actions_height) else 0f
return context!!.realScreenSize.y - height - actionsHeight - fullscreenOffset
}
}

View file

@ -0,0 +1,802 @@
package com.simplemobiletools.gallery.pro.fragments
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Point
import android.graphics.SurfaceTexture
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.util.DisplayMetrics
import android.view.*
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.TextView
import com.bumptech.glide.Glide
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.upstream.FileDataSource
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.activities.PanoramaVideoActivity
import com.simplemobiletools.gallery.pro.activities.VideoActivity
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.extensions.hasNavBar
import com.simplemobiletools.gallery.pro.extensions.parseFileChannel
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.models.Medium
import com.simplemobiletools.gallery.pro.views.MediaSideScroll
import kotlinx.android.synthetic.main.bottom_video_time_holder.view.*
import kotlinx.android.synthetic.main.pager_video_item.view.*
import java.io.File
import java.io.FileInputStream
class VideoFragment : ViewPagerFragment(), TextureView.SurfaceTextureListener, SeekBar.OnSeekBarChangeListener {
private val PROGRESS = "progress"
private var mIsFullscreen = false
private var mWasFragmentInit = false
private var mIsPanorama = false
private var mIsFragmentVisible = false
private var mIsDragged = false
private var mWasVideoStarted = false
private var mWasPlayerInited = false
private var mWasLastPositionRestored = false
private var mPlayOnPrepared = false
private var mIsPlayerPrepared = false
private var mCurrTime = 0
private var mDuration = 0
private var mPositionWhenInit = 0
private var mPositionAtPause = 0L
var mIsPlaying = false
private var mExoPlayer: SimpleExoPlayer? = null
private var mVideoSize = Point(1, 1)
private var mTimerHandler = Handler()
private var mStoredShowExtendedDetails = false
private var mStoredHideExtendedDetails = false
private var mStoredBottomActions = true
private var mStoredExtendedDetails = 0
private var mStoredRememberLastVideoPosition = false
private lateinit var mTimeHolder: View
private lateinit var mBrightnessSideScroll: MediaSideScroll
private lateinit var mVolumeSideScroll: MediaSideScroll
private lateinit var mView: View
private lateinit var mMedium: Medium
private lateinit var mConfig: Config
private lateinit var mTextureView: TextureView
private lateinit var mCurrTimeView: TextView
private lateinit var mPlayPauseButton: ImageView
private lateinit var mSeekBar: SeekBar
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mMedium = arguments!!.getSerializable(MEDIUM) as Medium
mConfig = context!!.config
mView = inflater.inflate(R.layout.pager_video_item, container, false).apply {
panorama_outline.setOnClickListener { openPanorama() }
video_curr_time.setOnClickListener { skip(false) }
video_duration.setOnClickListener { skip(true) }
video_holder.setOnClickListener { toggleFullscreen() }
video_preview.setOnClickListener { toggleFullscreen() }
video_surface_frame.controller.settings.swallowDoubleTaps = true
video_play_outline.setOnClickListener {
if (mConfig.openVideosOnSeparateScreen) {
launchVideoPlayer()
} else {
togglePlayPause()
}
}
mPlayPauseButton = video_toggle_play_pause
mPlayPauseButton.setOnClickListener {
togglePlayPause()
}
mSeekBar = video_seekbar
mSeekBar.setOnSeekBarChangeListener(this@VideoFragment)
// adding an empty click listener just to avoid ripple animation at toggling fullscreen
mSeekBar.setOnClickListener { }
mTimeHolder = video_time_holder
mCurrTimeView = video_curr_time
mBrightnessSideScroll = video_brightness_controller
mVolumeSideScroll = video_volume_controller
mTextureView = video_surface
mTextureView.surfaceTextureListener = this@VideoFragment
val gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
if (!mConfig.allowInstantChange) {
toggleFullscreen()
return true
}
val viewWidth = width
val instantWidth = viewWidth / 7
val clickedX = e?.rawX ?: 0f
when {
clickedX <= instantWidth -> listener?.goToPrevItem()
clickedX >= viewWidth - instantWidth -> listener?.goToNextItem()
else -> toggleFullscreen()
}
return true
}
override fun onDoubleTap(e: MotionEvent?): Boolean {
if (e != null) {
handleDoubleTap(e.rawX)
}
return true
}
})
video_preview.setOnTouchListener { view, event ->
handleEvent(event)
false
}
video_surface_frame.setOnTouchListener { view, event ->
if (video_surface_frame.controller.state.zoom == 1f) {
handleEvent(event)
}
gestureDetector.onTouchEvent(event)
false
}
}
if (!arguments!!.getBoolean(SHOULD_INIT_FRAGMENT, true)) {
return mView
}
storeStateVariables()
Glide.with(context!!).load(mMedium.path).into(mView.video_preview)
// setMenuVisibility is not called at VideoActivity (third party intent)
if (!mIsFragmentVisible && activity is VideoActivity) {
mIsFragmentVisible = true
}
mIsFullscreen = activity!!.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == View.SYSTEM_UI_FLAG_FULLSCREEN
initTimeHolder()
checkIfPanorama()
ensureBackgroundThread {
activity?.getVideoResolution(mMedium.path)?.apply {
mVideoSize.x = x
mVideoSize.y = y
}
}
if (mIsPanorama) {
mView.apply {
panorama_outline.beVisible()
video_play_outline.beGone()
mVolumeSideScroll.beGone()
mBrightnessSideScroll.beGone()
Glide.with(context!!).load(mMedium.path).into(video_preview)
}
}
if (!mIsPanorama) {
if (savedInstanceState != null) {
mCurrTime = savedInstanceState.getInt(PROGRESS)
}
mWasFragmentInit = true
setVideoSize()
mView.apply {
mBrightnessSideScroll.initialize(activity!!, slide_info, true, container, singleTap = { x, y ->
if (mConfig.allowInstantChange) {
listener?.goToPrevItem()
} else {
toggleFullscreen()
}
}, doubleTap = { x, y ->
doSkip(false)
})
mVolumeSideScroll.initialize(activity!!, slide_info, false, container, singleTap = { x, y ->
if (mConfig.allowInstantChange) {
listener?.goToNextItem()
} else {
toggleFullscreen()
}
}, doubleTap = { x, y ->
doSkip(true)
})
video_surface.onGlobalLayout {
if (mIsFragmentVisible && mConfig.autoplayVideos && !mConfig.openVideosOnSeparateScreen) {
playVideo()
}
}
}
}
setupVideoDuration()
if (mStoredRememberLastVideoPosition) {
restoreLastVideoSavedPosition()
}
return mView
}
override fun onResume() {
super.onResume()
mConfig = context!!.config // make sure we get a new config, in case the user changed something in the app settings
activity!!.updateTextColors(mView.video_holder)
val allowVideoGestures = mConfig.allowVideoGestures
mTextureView.beGoneIf(mConfig.openVideosOnSeparateScreen || mIsPanorama)
mView.video_surface_frame.beGoneIf(mTextureView.isGone())
mVolumeSideScroll.beVisibleIf(allowVideoGestures && !mIsPanorama)
mBrightnessSideScroll.beVisibleIf(allowVideoGestures && !mIsPanorama)
checkExtendedDetails()
initTimeHolder()
storeStateVariables()
}
override fun onPause() {
super.onPause()
storeStateVariables()
pauseVideo()
if (mStoredRememberLastVideoPosition && mIsFragmentVisible && mWasVideoStarted) {
saveVideoProgress()
}
}
override fun onDestroy() {
super.onDestroy()
if (activity?.isChangingConfigurations == false) {
cleanup()
}
}
override fun setMenuVisibility(menuVisible: Boolean) {
super.setMenuVisibility(menuVisible)
if (mIsFragmentVisible && !menuVisible) {
pauseVideo()
}
mIsFragmentVisible = menuVisible
if (mWasFragmentInit && menuVisible && mConfig.autoplayVideos && !mConfig.openVideosOnSeparateScreen) {
playVideo()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
setVideoSize()
initTimeHolder()
checkExtendedDetails()
mView.video_surface_frame.onGlobalLayout {
mView.video_surface_frame.controller.resetState()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(PROGRESS, mCurrTime)
}
private fun storeStateVariables() {
mConfig.apply {
mStoredShowExtendedDetails = showExtendedDetails
mStoredHideExtendedDetails = hideExtendedDetails
mStoredExtendedDetails = extendedDetails
mStoredBottomActions = bottomActions
mStoredRememberLastVideoPosition = rememberLastVideoPosition
}
}
private fun saveVideoProgress() {
if (!videoEnded()) {
if (mExoPlayer != null) {
mConfig.saveLastVideoPosition(mMedium.path, mExoPlayer!!.currentPosition.toInt() / 1000)
} else {
mConfig.saveLastVideoPosition(mMedium.path, mPositionAtPause.toInt() / 1000)
}
}
}
private fun restoreLastVideoSavedPosition() {
val pos = mConfig.getLastVideoPosition(mMedium.path)
if (pos > 0) {
mPositionAtPause = pos * 1000L
setPosition(pos)
}
}
private fun setupTimeHolder() {
mSeekBar.max = mDuration
mView.video_duration.text = mDuration.getFormattedDuration()
setupTimer()
}
private fun setupTimer() {
activity?.runOnUiThread(object : Runnable {
override fun run() {
if (mExoPlayer != null && !mIsDragged && mIsPlaying) {
mCurrTime = (mExoPlayer!!.currentPosition / 1000).toInt()
mSeekBar.progress = mCurrTime
mCurrTimeView.text = mCurrTime.getFormattedDuration()
}
mTimerHandler.postDelayed(this, 1000)
}
})
}
private fun initExoPlayer() {
if (activity == null || mConfig.openVideosOnSeparateScreen || mIsPanorama || mExoPlayer != null) {
return
}
mExoPlayer = ExoPlayerFactory.newSimpleInstance(context)
mExoPlayer!!.seekParameters = SeekParameters.CLOSEST_SYNC
if (mConfig.loopVideos && listener?.isSlideShowActive() == false) {
mExoPlayer?.repeatMode = Player.REPEAT_MODE_ONE
}
val isContentUri = mMedium.path.startsWith("content://")
val uri = if (isContentUri) Uri.parse(mMedium.path) else Uri.fromFile(File(mMedium.path))
val dataSpec = DataSpec(uri)
val fileDataSource = if (isContentUri) ContentDataSource(context) else FileDataSource()
try {
fileDataSource.open(dataSpec)
} catch (e: Exception) {
activity?.showErrorToast(e)
return
}
val factory = DataSource.Factory { fileDataSource }
val audioSource = ExtractorMediaSource(fileDataSource.uri, factory, DefaultExtractorsFactory(), null, null)
mPlayOnPrepared = true
mExoPlayer!!.audioStreamType = C.STREAM_TYPE_MUSIC
mExoPlayer!!.prepare(audioSource)
if (mTextureView.surfaceTexture != null) {
mExoPlayer!!.setVideoSurface(Surface(mTextureView.surfaceTexture))
}
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) {
mSeekBar.progress = 0
mCurrTimeView.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 : SimpleExoPlayer.VideoListener {
override fun onVideoSizeChanged(width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float) {
mVideoSize.x = width
mVideoSize.y = (height / pixelWidthHeightRatio).toInt()
setVideoSize()
}
override fun onRenderedFirstFrame() {}
})
}
private fun launchVideoPlayer() {
listener?.launchViewVideoIntent(mMedium.path)
}
private fun toggleFullscreen() {
listener?.fragmentClicked()
}
private fun handleDoubleTap(x: Float) {
val viewWidth = mView.width
val instantWidth = viewWidth / 7
when {
x <= instantWidth -> doSkip(false)
x >= viewWidth - instantWidth -> doSkip(true)
else -> togglePlayPause()
}
}
private fun checkExtendedDetails() {
if (mConfig.showExtendedDetails) {
mView.video_details.apply {
beInvisible() // make it invisible so we can measure it, but not show yet
text = getMediumExtendedDetails(mMedium)
onGlobalLayout {
if (isAdded) {
val realY = getExtendedDetailsY(height)
if (realY > 0) {
y = realY
beVisibleIf(text.isNotEmpty())
alpha = if (!mConfig.hideExtendedDetails || !mIsFullscreen) 1f else 0f
}
}
}
}
} else {
mView.video_details.beGone()
}
}
private fun initTimeHolder() {
var right = 0
var bottom = context!!.navigationBarHeight
if (mConfig.bottomActions) {
bottom += resources.getDimension(R.dimen.bottom_actions_height).toInt()
}
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE && activity?.hasNavBar() == true) {
right += activity!!.navigationBarWidth
}
(mTimeHolder.layoutParams as RelativeLayout.LayoutParams).apply {
bottomMargin = bottom
rightMargin = right
}
mTimeHolder.beInvisibleIf(mIsFullscreen)
}
private fun checkIfPanorama() {
try {
val fis = FileInputStream(File(mMedium.path))
fis.use {
context!!.parseFileChannel(mMedium.path, it.channel, 0, 0, 0) {
mIsPanorama = true
}
}
} catch (ignored: Exception) {
} catch (ignored: OutOfMemoryError) {
}
}
private fun openPanorama() {
Intent(context, PanoramaVideoActivity::class.java).apply {
putExtra(PATH, mMedium.path)
startActivity(this)
}
}
override fun fullscreenToggled(isFullscreen: Boolean) {
mIsFullscreen = isFullscreen
val newAlpha = if (isFullscreen) 0f else 1f
if (!mIsFullscreen) {
mTimeHolder.beVisible()
}
mSeekBar.setOnSeekBarChangeListener(if (mIsFullscreen) null else this)
arrayOf(mView.video_curr_time, mView.video_duration, mView.video_toggle_play_pause).forEach {
it.isClickable = !mIsFullscreen
}
mTimeHolder.animate().alpha(newAlpha).start()
mView.video_details.apply {
if (mStoredShowExtendedDetails && isVisible() && context != null && resources != null) {
animate().y(getExtendedDetailsY(height))
if (mStoredHideExtendedDetails) {
animate().alpha(newAlpha).start()
}
}
}
}
private fun getExtendedDetailsY(height: Int): Float {
val smallMargin = context?.resources?.getDimension(R.dimen.small_margin) ?: return 0f
val fullscreenOffset = smallMargin + if (mIsFullscreen) 0 else context!!.navigationBarHeight
var actionsHeight = 0f
if (!mIsFullscreen) {
actionsHeight += resources.getDimension(R.dimen.video_player_play_pause_size)
if (mConfig.bottomActions) {
actionsHeight += resources.getDimension(R.dimen.bottom_actions_height)
}
}
return context!!.realScreenSize.y - height - actionsHeight - fullscreenOffset
}
private fun skip(forward: Boolean) {
if (mIsPanorama) {
return
} else if (mExoPlayer == null) {
playVideo()
return
}
mPositionAtPause = 0L
doSkip(forward)
}
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()
}
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser) {
if (mExoPlayer != null) {
if (!mWasPlayerInited) {
mPositionWhenInit = progress
}
setPosition(progress)
}
if (mExoPlayer == null) {
mPositionAtPause = progress * 1000L
playVideo()
}
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
if (mExoPlayer == null) {
return
}
mExoPlayer!!.playWhenReady = false
mIsDragged = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
if (mIsPanorama) {
openPanorama()
return
}
if (mExoPlayer == null) {
return
}
if (mIsPlaying) {
mExoPlayer!!.playWhenReady = true
} else {
playVideo()
}
mIsDragged = false
}
private fun togglePlayPause() {
if (activity == null || !isAdded) {
return
}
if (mIsPlaying) {
pauseVideo()
} else {
playVideo()
}
}
fun playVideo() {
if (mExoPlayer == null) {
initExoPlayer()
return
}
if (mView.video_preview.isVisible()) {
mView.video_preview.beGone()
initExoPlayer()
}
val wasEnded = videoEnded()
if (wasEnded) {
setPosition(0)
}
if (mStoredRememberLastVideoPosition && !mWasLastPositionRestored) {
mWasLastPositionRestored = true
restoreLastVideoSavedPosition()
}
if (!wasEnded || !mConfig.loopVideos) {
mPlayPauseButton.setImageResource(R.drawable.ic_pause_outline_vector)
}
if (!mWasVideoStarted) {
mView.video_play_outline.beGone()
mPlayPauseButton.beVisible()
}
mWasVideoStarted = true
if (mIsPlayerPrepared) {
mIsPlaying = true
}
mExoPlayer?.playWhenReady = true
activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
private fun pauseVideo() {
if (mExoPlayer == null) {
return
}
mIsPlaying = false
if (!videoEnded()) {
mExoPlayer?.playWhenReady = false
}
mPlayPauseButton.setImageResource(R.drawable.ic_play_outline_vector)
activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
mPositionAtPause = mExoPlayer?.currentPosition ?: 0L
releaseExoPlayer()
}
private fun videoEnded(): Boolean {
val currentPos = mExoPlayer?.currentPosition ?: 0
val duration = mExoPlayer?.duration ?: 0
return currentPos != 0L && currentPos >= duration
}
private fun setPosition(seconds: Int) {
mExoPlayer?.seekTo(seconds * 1000L)
mSeekBar.progress = seconds
mCurrTimeView.text = seconds.getFormattedDuration()
if (!mIsPlaying) {
mPositionAtPause = mExoPlayer?.currentPosition ?: 0L
}
}
private fun setupVideoDuration() {
ensureBackgroundThread {
mDuration = context?.getDuration(mMedium.path) ?: 0
activity?.runOnUiThread {
setupTimeHolder()
setPosition(0)
}
}
}
private fun videoPrepared() {
if (mDuration == 0) {
mDuration = (mExoPlayer!!.duration / 1000).toInt()
setupTimeHolder()
setPosition(mCurrTime)
if (mIsFragmentVisible && (mConfig.autoplayVideos)) {
playVideo()
}
}
if (mPositionWhenInit != 0 && !mWasPlayerInited) {
setPosition(mPositionWhenInit)
mPositionWhenInit = 0
}
mIsPlayerPrepared = true
if (mPlayOnPrepared && !mIsPlaying) {
if (mPositionAtPause != 0L) {
mExoPlayer?.seekTo(mPositionAtPause)
mPositionAtPause = 0L
}
playVideo()
}
mWasPlayerInited = true
mPlayOnPrepared = false
}
private fun videoCompleted() {
if (!isAdded || mExoPlayer == null) {
return
}
mCurrTime = (mExoPlayer!!.duration / 1000).toInt()
if (listener?.videoEnded() == false && mConfig.loopVideos) {
playVideo()
} else {
mSeekBar.progress = mSeekBar.max
mCurrTimeView.text = mDuration.getFormattedDuration()
pauseVideo()
}
}
private fun cleanup() {
pauseVideo()
releaseExoPlayer()
if (mWasFragmentInit) {
mCurrTimeView.text = 0.getFormattedDuration()
mSeekBar.progress = 0
mTimerHandler.removeCallbacksAndMessages(null)
}
}
private fun releaseExoPlayer() {
mIsPlayerPrepared = false
mExoPlayer?.stop()
ensureBackgroundThread {
mExoPlayer?.release()
mExoPlayer = null
}
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) {}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) {}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?) = false
override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) {
ensureBackgroundThread {
mExoPlayer?.setVideoSurface(Surface(mTextureView.surfaceTexture))
}
}
private fun setVideoSize() {
if (activity == null || mConfig.openVideosOnSeparateScreen) {
return
}
val videoProportion = mVideoSize.x.toFloat() / mVideoSize.y.toFloat()
val display = activity!!.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()
mTextureView.layoutParams.apply {
if (videoProportion > screenProportion) {
width = screenWidth
height = (screenWidth.toFloat() / videoProportion).toInt()
} else {
width = (videoProportion * screenHeight.toFloat()).toInt()
height = screenHeight
}
mTextureView.layoutParams = this
}
}
}

View file

@ -0,0 +1,154 @@
package com.simplemobiletools.gallery.pro.fragments
import android.media.ExifInterface
import android.provider.MediaStore
import android.provider.MediaStore.Files
import android.provider.MediaStore.Images
import android.view.MotionEvent
import androidx.fragment.app.Fragment
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.models.Medium
import java.io.File
abstract class ViewPagerFragment : Fragment() {
var listener: FragmentListener? = null
private var mTouchDownTime = 0L
private var mTouchDownX = 0f
private var mTouchDownY = 0f
private var mCloseDownThreshold = 100f
private var mIgnoreCloseDown = false
abstract fun fullscreenToggled(isFullscreen: Boolean)
interface FragmentListener {
fun fragmentClicked()
fun videoEnded(): Boolean
fun goToPrevItem()
fun goToNextItem()
fun launchViewVideoIntent(path: String)
fun isSlideShowActive(): Boolean
}
fun getMediumExtendedDetails(medium: Medium): String {
val file = File(medium.path)
if (context?.getDoesFilePathExist(file.absolutePath) == false) {
return ""
}
val path = "${file.parent.trimEnd('/')}/"
val exif = try {
ExifInterface(medium.path)
} catch (e: Exception) {
return ""
}
val details = StringBuilder()
val detailsFlag = context!!.config.extendedDetails
if (detailsFlag and EXT_NAME != 0) {
medium.name.let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_PATH != 0) {
path.let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_SIZE != 0) {
file.length().formatSize().let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_RESOLUTION != 0) {
context!!.getResolution(file.absolutePath)?.formatAsResolution().let { if (it?.isNotEmpty() == true) details.appendln(it) }
}
if (detailsFlag and EXT_LAST_MODIFIED != 0) {
getFileLastModified(file).let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_DATE_TAKEN != 0) {
exif.getExifDateTaken(context!!).let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_CAMERA_MODEL != 0) {
exif.getExifCameraModel().let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_EXIF_PROPERTIES != 0) {
exif.getExifProperties().let { if (it.isNotEmpty()) details.appendln(it) }
}
if (detailsFlag and EXT_GPS != 0) {
getLatLonAltitude(medium.path).let { if (it.isNotEmpty()) details.appendln(it) }
}
return details.toString().trim()
}
fun getPathToLoad(medium: Medium) = if (context?.isPathOnOTG(medium.path) == true) medium.path.getOTGPublicPath(context!!) else medium.path
private fun getFileLastModified(file: File): String {
val projection = arrayOf(Images.Media.DATE_MODIFIED)
val uri = Files.getContentUri("external")
val selection = "${MediaStore.MediaColumns.DATA} = ?"
val selectionArgs = arrayOf(file.absolutePath)
val cursor = context!!.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
return if (cursor.moveToFirst()) {
val dateModified = cursor.getLongValue(Images.Media.DATE_MODIFIED) * 1000L
dateModified.formatDate(context!!)
} else {
file.lastModified().formatDate(context!!)
}
}
return ""
}
private fun getLatLonAltitude(path: String): String {
var result = ""
val exif = try {
ExifInterface(path)
} catch (e: Exception) {
return ""
}
val latLon = FloatArray(2)
if (exif.getLatLong(latLon)) {
result = "${latLon[0]}, ${latLon[1]}"
}
val altitude = exif.getAltitude(0.0)
if (altitude != 0.0) {
result += ", ${altitude}m"
}
return result.trimStart(',').trim()
}
protected fun handleEvent(event: MotionEvent) {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
mTouchDownTime = System.currentTimeMillis()
mTouchDownX = event.x
mTouchDownY = event.y
}
MotionEvent.ACTION_POINTER_DOWN -> mIgnoreCloseDown = true
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
val diffX = mTouchDownX - event.x
val diffY = mTouchDownY - event.y
val downGestureDuration = System.currentTimeMillis() - mTouchDownTime
if (!mIgnoreCloseDown && Math.abs(diffY) > Math.abs(diffX) && diffY < -mCloseDownThreshold && downGestureDuration < MAX_CLOSE_DOWN_GESTURE_DURATION && context?.config?.allowDownGesture == true) {
activity?.supportFinishAfterTransition()
}
mIgnoreCloseDown = false
}
}
}
}

View file

@ -0,0 +1,495 @@
package com.simplemobiletools.gallery.pro.helpers
import android.content.Context
import android.content.res.Configuration
import android.os.Environment
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.pro.R
import com.simplemobiletools.gallery.pro.models.AlbumCover
import java.util.*
class Config(context: Context) : BaseConfig(context) {
companion object {
fun newInstance(context: Context) = Config(context)
}
var directorySorting: Int
get(): Int = prefs.getInt(DIRECTORY_SORT_ORDER, SORT_BY_DATE_MODIFIED or SORT_DESCENDING)
set(order) = prefs.edit().putInt(DIRECTORY_SORT_ORDER, order).apply()
fun saveFolderGrouping(path: String, value: Int) {
if (path.isEmpty()) {
groupBy = value
} else {
prefs.edit().putInt(GROUP_FOLDER_PREFIX + path.toLowerCase(), value).apply()
}
}
fun getFolderGrouping(path: String): Int {
var groupBy = prefs.getInt(GROUP_FOLDER_PREFIX + path.toLowerCase(), groupBy)
if (path != SHOW_ALL && groupBy and GROUP_BY_FOLDER != 0) {
groupBy -= GROUP_BY_FOLDER + 1
}
return groupBy
}
fun removeFolderGrouping(path: String) {
prefs.edit().remove(GROUP_FOLDER_PREFIX + path.toLowerCase()).apply()
}
fun hasCustomGrouping(path: String) = prefs.contains(GROUP_FOLDER_PREFIX + path.toLowerCase())
fun saveFolderViewType(path: String, value: Int) {
if (path.isEmpty()) {
viewTypeFiles = value
} else {
prefs.edit().putInt(VIEW_TYPE_PREFIX + path.toLowerCase(), value).apply()
}
}
fun getFolderViewType(path: String) = prefs.getInt(VIEW_TYPE_PREFIX + path.toLowerCase(), viewTypeFiles)
fun removeFolderViewType(path: String) {
prefs.edit().remove(VIEW_TYPE_PREFIX + path.toLowerCase()).apply()
}
fun hasCustomViewType(path: String) = prefs.contains(VIEW_TYPE_PREFIX + path.toLowerCase())
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 isThirdPartyIntent: Boolean
get() = prefs.getBoolean(IS_THIRD_PARTY_INTENT, false)
set(isThirdPartyIntent) = prefs.edit().putBoolean(IS_THIRD_PARTY_INTENT, isThirdPartyIntent).apply()
var pinnedFolders: Set<String>
get() = prefs.getStringSet(PINNED_FOLDERS, HashSet<String>())!!
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<String>) {
val currPinnedFolders = HashSet<String>(pinnedFolders)
currPinnedFolders.addAll(paths)
pinnedFolders = currPinnedFolders.filter { it.isNotEmpty() }.toHashSet()
if (paths.contains(RECYCLE_BIN)) {
showRecycleBinLast = false
}
}
fun removePinnedFolders(paths: Set<String>) {
val currPinnedFolders = HashSet<String>(pinnedFolders)
currPinnedFolders.removeAll(paths)
pinnedFolders = currPinnedFolders
}
fun addExcludedFolder(path: String) {
addExcludedFolders(HashSet<String>(Arrays.asList(path)))
}
fun addExcludedFolders(paths: Set<String>) {
val currExcludedFolders = HashSet<String>(excludedFolders)
currExcludedFolders.addAll(paths)
excludedFolders = currExcludedFolders.filter { it.isNotEmpty() }.toHashSet()
}
fun removeExcludedFolder(path: String) {
val currExcludedFolders = HashSet<String>(excludedFolders)
currExcludedFolders.remove(path)
excludedFolders = currExcludedFolders
}
var excludedFolders: MutableSet<String>
get() = prefs.getStringSet(EXCLUDED_FOLDERS, HashSet())!!
set(excludedFolders) = prefs.edit().remove(EXCLUDED_FOLDERS).putStringSet(EXCLUDED_FOLDERS, excludedFolders).apply()
fun addIncludedFolder(path: String) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.add(path)
includedFolders = currIncludedFolders
}
fun addIncludedFolders(paths: Set<String>) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.addAll(paths)
includedFolders = currIncludedFolders.filter { it.isNotEmpty() }.toHashSet()
}
fun removeIncludedFolder(path: String) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.remove(path)
includedFolders = currIncludedFolders
}
var includedFolders: MutableSet<String>
get() = prefs.getStringSet(INCLUDED_FOLDERS, HashSet<String>())!!
set(includedFolders) = prefs.edit().remove(INCLUDED_FOLDERS).putStringSet(INCLUDED_FOLDERS, includedFolders).apply()
var autoplayVideos: Boolean
get() = prefs.getBoolean(AUTOPLAY_VIDEOS, false)
set(autoplayVideos) = prefs.edit().putBoolean(AUTOPLAY_VIDEOS, autoplayVideos).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 showThumbnailVideoDuration: Boolean
get() = prefs.getBoolean(SHOW_THUMBNAIL_VIDEO_DURATION, false)
set(showThumbnailVideoDuration) = prefs.edit().putBoolean(SHOW_THUMBNAIL_VIDEO_DURATION, showThumbnailVideoDuration).apply()
var showThumbnailFileTypes: Boolean
get() = prefs.getBoolean(SHOW_THUMBNAIL_FILE_TYPES, true)
set(showThumbnailFileTypes) = prefs.edit().putBoolean(SHOW_THUMBNAIL_FILE_TYPES, showThumbnailFileTypes).apply()
var screenRotation: Int
get() = prefs.getInt(SCREEN_ROTATION, ROTATE_BY_SYSTEM_SETTING)
set(screenRotation) = prefs.edit().putInt(SCREEN_ROTATION, screenRotation).apply()
var fileLoadingPriority: Int
get() = prefs.getInt(FILE_LOADING_PRIORITY, PRIORITY_COMPROMISE)
set(fileLoadingPriority) = prefs.edit().putInt(FILE_LOADING_PRIORITY, fileLoadingPriority).apply()
var loopVideos: Boolean
get() = prefs.getBoolean(LOOP_VIDEOS, false)
set(loop) = prefs.edit().putBoolean(LOOP_VIDEOS, loop).apply()
var openVideosOnSeparateScreen: Boolean
get() = prefs.getBoolean(OPEN_VIDEOS_ON_SEPARATE_SCREEN, false)
set(openVideosOnSeparateScreen) = prefs.edit().putBoolean(OPEN_VIDEOS_ON_SEPARATE_SCREEN, openVideosOnSeparateScreen).apply()
var displayFileNames: Boolean
get() = prefs.getBoolean(DISPLAY_FILE_NAMES, false)
set(display) = prefs.edit().putBoolean(DISPLAY_FILE_NAMES, display).apply()
var blackBackground: Boolean
get() = prefs.getBoolean(BLACK_BACKGROUND, false)
set(blackBackground) = prefs.edit().putBoolean(BLACK_BACKGROUND, blackBackground).apply()
var filterMedia: Int
get() = prefs.getInt(FILTER_MEDIA, getDefaultFileFilter())
set(filterMedia) = prefs.edit().putInt(FILTER_MEDIA, filterMedia).apply()
var dirColumnCnt: Int
get() = prefs.getInt(getDirectoryColumnsField(), getDefaultDirectoryColumnCount())
set(dirColumnCnt) = prefs.edit().putInt(getDirectoryColumnsField(), dirColumnCnt).apply()
var allowInstantChange: Boolean
get() = prefs.getBoolean(ALLOW_INSTANT_CHANGE, false)
set(allowInstantChange) = prefs.edit().putBoolean(ALLOW_INSTANT_CHANGE, allowInstantChange).apply()
private fun getDirectoryColumnsField(): String {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
if (scrollHorizontally) {
DIR_HORIZONTAL_COLUMN_CNT
} else {
DIR_COLUMN_CNT
}
} else {
if (scrollHorizontally) {
DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT
} else {
DIR_LANDSCAPE_COLUMN_CNT
}
}
}
private fun getDefaultDirectoryColumnCount() = context.resources.getInteger(if (scrollHorizontally) R.integer.directory_columns_horizontal_scroll
else R.integer.directory_columns_vertical_scroll)
var mediaColumnCnt: Int
get() = prefs.getInt(getMediaColumnsField(), getDefaultMediaColumnCount())
set(mediaColumnCnt) = prefs.edit().putInt(getMediaColumnsField(), mediaColumnCnt).apply()
private fun getMediaColumnsField(): String {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
if (scrollHorizontally) {
MEDIA_HORIZONTAL_COLUMN_CNT
} else {
MEDIA_COLUMN_CNT
}
} else {
if (scrollHorizontally) {
MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT
} else {
MEDIA_LANDSCAPE_COLUMN_CNT
}
}
}
private fun getDefaultMediaColumnCount() = context.resources.getInteger(if (scrollHorizontally) R.integer.media_columns_horizontal_scroll
else R.integer.media_columns_vertical_scroll)
var albumCovers: String
get() = prefs.getString(ALBUM_COVERS, "")!!
set(albumCovers) = prefs.edit().putString(ALBUM_COVERS, albumCovers).apply()
fun parseAlbumCovers(): ArrayList<AlbumCover> {
val listType = object : TypeToken<List<AlbumCover>>() {}.type
return Gson().fromJson<ArrayList<AlbumCover>>(albumCovers, listType) ?: ArrayList(1)
}
var hideSystemUI: Boolean
get() = prefs.getBoolean(HIDE_SYSTEM_UI, false)
set(hideSystemUI) = prefs.edit().putBoolean(HIDE_SYSTEM_UI, hideSystemUI).apply()
var deleteEmptyFolders: Boolean
get() = prefs.getBoolean(DELETE_EMPTY_FOLDERS, false)
set(deleteEmptyFolders) = prefs.edit().putBoolean(DELETE_EMPTY_FOLDERS, deleteEmptyFolders).apply()
var allowPhotoGestures: Boolean
get() = prefs.getBoolean(ALLOW_PHOTO_GESTURES, false)
set(allowPhotoGestures) = prefs.edit().putBoolean(ALLOW_PHOTO_GESTURES, allowPhotoGestures).apply()
var allowVideoGestures: Boolean
get() = prefs.getBoolean(ALLOW_VIDEO_GESTURES, true)
set(allowVideoGestures) = prefs.edit().putBoolean(ALLOW_VIDEO_GESTURES, allowVideoGestures).apply()
var showMediaCount: Boolean
get() = prefs.getBoolean(SHOW_MEDIA_COUNT, true)
set(showMediaCount) = prefs.edit().putBoolean(SHOW_MEDIA_COUNT, showMediaCount).apply()
var slideshowInterval: Int
get() = prefs.getInt(SLIDESHOW_INTERVAL, SLIDESHOW_DEFAULT_INTERVAL)
set(slideshowInterval) = prefs.edit().putInt(SLIDESHOW_INTERVAL, slideshowInterval).apply()
var slideshowIncludeVideos: Boolean
get() = prefs.getBoolean(SLIDESHOW_INCLUDE_VIDEOS, false)
set(slideshowIncludeVideos) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_VIDEOS, slideshowIncludeVideos).apply()
var slideshowIncludeGIFs: Boolean
get() = prefs.getBoolean(SLIDESHOW_INCLUDE_GIFS, false)
set(slideshowIncludeGIFs) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_GIFS, slideshowIncludeGIFs).apply()
var slideshowRandomOrder: Boolean
get() = prefs.getBoolean(SLIDESHOW_RANDOM_ORDER, false)
set(slideshowRandomOrder) = prefs.edit().putBoolean(SLIDESHOW_RANDOM_ORDER, slideshowRandomOrder).apply()
var slideshowMoveBackwards: Boolean
get() = prefs.getBoolean(SLIDESHOW_MOVE_BACKWARDS, false)
set(slideshowMoveBackwards) = prefs.edit().putBoolean(SLIDESHOW_MOVE_BACKWARDS, slideshowMoveBackwards).apply()
var slideshowAnimation: Int
get() = prefs.getInt(SLIDESHOW_ANIMATION, SLIDESHOW_ANIMATION_SLIDE)
set(slideshowAnimation) = prefs.edit().putInt(SLIDESHOW_ANIMATION, slideshowAnimation).apply()
var loopSlideshow: Boolean
get() = prefs.getBoolean(SLIDESHOW_LOOP, false)
set(loopSlideshow) = prefs.edit().putBoolean(SLIDESHOW_LOOP, loopSlideshow).apply()
var tempFolderPath: String
get() = prefs.getString(TEMP_FOLDER_PATH, "")!!
set(tempFolderPath) = prefs.edit().putString(TEMP_FOLDER_PATH, tempFolderPath).apply()
var viewTypeFolders: Int
get() = prefs.getInt(VIEW_TYPE_FOLDERS, VIEW_TYPE_GRID)
set(viewTypeFolders) = prefs.edit().putInt(VIEW_TYPE_FOLDERS, viewTypeFolders).apply()
var viewTypeFiles: Int
get() = prefs.getInt(VIEW_TYPE_FILES, VIEW_TYPE_GRID)
set(viewTypeFiles) = prefs.edit().putInt(VIEW_TYPE_FILES, viewTypeFiles).apply()
var showExtendedDetails: Boolean
get() = prefs.getBoolean(SHOW_EXTENDED_DETAILS, false)
set(showExtendedDetails) = prefs.edit().putBoolean(SHOW_EXTENDED_DETAILS, showExtendedDetails).apply()
var hideExtendedDetails: Boolean
get() = prefs.getBoolean(HIDE_EXTENDED_DETAILS, false)
set(hideExtendedDetails) = prefs.edit().putBoolean(HIDE_EXTENDED_DETAILS, hideExtendedDetails).apply()
var extendedDetails: Int
get() = prefs.getInt(EXTENDED_DETAILS, EXT_RESOLUTION or EXT_LAST_MODIFIED or EXT_EXIF_PROPERTIES)
set(extendedDetails) = prefs.edit().putInt(EXTENDED_DETAILS, extendedDetails).apply()
var wasNewAppShown: Boolean
get() = prefs.getBoolean(WAS_NEW_APP_SHOWN, false)
set(wasNewAppShown) = prefs.edit().putBoolean(WAS_NEW_APP_SHOWN, wasNewAppShown).apply()
var lastFilepickerPath: String
get() = prefs.getString(LAST_FILEPICKER_PATH, "")!!
set(lastFilepickerPath) = prefs.edit().putString(LAST_FILEPICKER_PATH, lastFilepickerPath).apply()
var tempSkipDeleteConfirmation: Boolean
get() = prefs.getBoolean(TEMP_SKIP_DELETE_CONFIRMATION, false)
set(tempSkipDeleteConfirmation) = prefs.edit().putBoolean(TEMP_SKIP_DELETE_CONFIRMATION, tempSkipDeleteConfirmation).apply()
var wereFavoritesPinned: Boolean
get() = prefs.getBoolean(WERE_FAVORITES_PINNED, false)
set(wereFavoritesPinned) = prefs.edit().putBoolean(WERE_FAVORITES_PINNED, wereFavoritesPinned).apply()
var wasRecycleBinPinned: Boolean
get() = prefs.getBoolean(WAS_RECYCLE_BIN_PINNED, false)
set(wasRecycleBinPinned) = prefs.edit().putBoolean(WAS_RECYCLE_BIN_PINNED, wasRecycleBinPinned).apply()
var wasSVGShowingHandled: Boolean
get() = prefs.getBoolean(WAS_SVG_SHOWING_HANDLED, false)
set(wasSVGShowingHandled) = prefs.edit().putBoolean(WAS_SVG_SHOWING_HANDLED, wasSVGShowingHandled).apply()
var groupBy: Int
get() = prefs.getInt(GROUP_BY, GROUP_BY_NONE)
set(groupBy) = prefs.edit().putInt(GROUP_BY, groupBy).apply()
var useRecycleBin: Boolean
get() = prefs.getBoolean(USE_RECYCLE_BIN, true)
set(useRecycleBin) = prefs.edit().putBoolean(USE_RECYCLE_BIN, useRecycleBin).apply()
var bottomActions: Boolean
get() = prefs.getBoolean(BOTTOM_ACTIONS, true)
set(bottomActions) = prefs.edit().putBoolean(BOTTOM_ACTIONS, bottomActions).apply()
fun removeLastVideoPosition(path: String) {
prefs.edit().remove("$LAST_VIDEO_POSITION_PREFIX${path.toLowerCase()}").apply()
}
fun saveLastVideoPosition(path: String, value: Int) {
if (path.isNotEmpty()) {
prefs.edit().putInt("$LAST_VIDEO_POSITION_PREFIX${path.toLowerCase()}", value).apply()
}
}
fun getLastVideoPosition(path: String) = prefs.getInt("$LAST_VIDEO_POSITION_PREFIX${path.toLowerCase()}", 0)
fun getAllLastVideoPositions() = prefs.all.filterKeys {
it.startsWith(LAST_VIDEO_POSITION_PREFIX)
}
var rememberLastVideoPosition: Boolean
get() = prefs.getBoolean(REMEMBER_LAST_VIDEO_POSITION, false)
set(rememberLastVideoPosition) {
if (!rememberLastVideoPosition) {
getAllLastVideoPositions().forEach {
prefs.edit().remove(it.key).apply()
}
}
prefs.edit().putBoolean(REMEMBER_LAST_VIDEO_POSITION, rememberLastVideoPosition).apply()
}
var visibleBottomActions: Int
get() = prefs.getInt(VISIBLE_BOTTOM_ACTIONS, DEFAULT_BOTTOM_ACTIONS)
set(visibleBottomActions) = prefs.edit().putInt(VISIBLE_BOTTOM_ACTIONS, visibleBottomActions).apply()
// if a user hides a folder, then enables temporary hidden folder displaying, make sure we show it properly
var everShownFolders: Set<String>
get() = prefs.getStringSet(EVER_SHOWN_FOLDERS, getEverShownFolders())!!
set(everShownFolders) = prefs.edit().putStringSet(EVER_SHOWN_FOLDERS, everShownFolders).apply()
private fun getEverShownFolders() = hashSetOf(
internalStoragePath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath,
"${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath}/Screenshots",
"internalStoragePath/WhatsApp/Media/WhatsApp Images",
"internalStoragePath/WhatsApp/Media/WhatsApp Video"
)
var showRecycleBinAtFolders: Boolean
get() = prefs.getBoolean(SHOW_RECYCLE_BIN_AT_FOLDERS, true)
set(showRecycleBinAtFolders) = prefs.edit().putBoolean(SHOW_RECYCLE_BIN_AT_FOLDERS, showRecycleBinAtFolders).apply()
var allowZoomingImages: Boolean
get() = prefs.getBoolean(ALLOW_ZOOMING_IMAGES, true)
set(allowZoomingImages) = prefs.edit().putBoolean(ALLOW_ZOOMING_IMAGES, allowZoomingImages).apply()
var lastBinCheck: Long
get() = prefs.getLong(LAST_BIN_CHECK, 0L)
set(lastBinCheck) = prefs.edit().putLong(LAST_BIN_CHECK, lastBinCheck).apply()
var showHighestQuality: Boolean
get() = prefs.getBoolean(SHOW_HIGHEST_QUALITY, false)
set(showHighestQuality) = prefs.edit().putBoolean(SHOW_HIGHEST_QUALITY, showHighestQuality).apply()
var showRecycleBinLast: Boolean
get() = prefs.getBoolean(SHOW_RECYCLE_BIN_LAST, false)
set(showRecycleBinLast) = prefs.edit().putBoolean(SHOW_RECYCLE_BIN_LAST, showRecycleBinLast).apply()
var allowDownGesture: Boolean
get() = prefs.getBoolean(ALLOW_DOWN_GESTURE, true)
set(allowDownGesture) = prefs.edit().putBoolean(ALLOW_DOWN_GESTURE, allowDownGesture).apply()
var lastEditorCropAspectRatio: Int
get() = prefs.getInt(LAST_EDITOR_CROP_ASPECT_RATIO, ASPECT_RATIO_FREE)
set(lastEditorCropAspectRatio) = prefs.edit().putInt(LAST_EDITOR_CROP_ASPECT_RATIO, lastEditorCropAspectRatio).apply()
var lastEditorCropOtherAspectRatioX: Float
get() = prefs.getFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X, 2f)
set(lastEditorCropOtherAspectRatioX) = prefs.edit().putFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X, lastEditorCropOtherAspectRatioX).apply()
var lastEditorCropOtherAspectRatioY: Float
get() = prefs.getFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y, 1f)
set(lastEditorCropOtherAspectRatioY) = prefs.edit().putFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y, lastEditorCropOtherAspectRatioY).apply()
var groupDirectSubfolders: Boolean
get() = prefs.getBoolean(GROUP_DIRECT_SUBFOLDERS, false)
set(groupDirectSubfolders) = prefs.edit().putBoolean(GROUP_DIRECT_SUBFOLDERS, groupDirectSubfolders).apply()
var showWidgetFolderName: Boolean
get() = prefs.getBoolean(SHOW_WIDGET_FOLDER_NAME, true)
set(showWidgetFolderName) = prefs.edit().putBoolean(SHOW_WIDGET_FOLDER_NAME, showWidgetFolderName).apply()
var allowOneToOneZoom: Boolean
get() = prefs.getBoolean(ALLOW_ONE_TO_ONE_ZOOM, false)
set(allowOneToOneZoom) = prefs.edit().putBoolean(ALLOW_ONE_TO_ONE_ZOOM, allowOneToOneZoom).apply()
var allowRotatingWithGestures: Boolean
get() = prefs.getBoolean(ALLOW_ROTATING_WITH_GESTURES, true)
set(allowRotatingWithGestures) = prefs.edit().putBoolean(ALLOW_ROTATING_WITH_GESTURES, allowRotatingWithGestures).apply()
var lastEditorDrawColor: Int
get() = prefs.getInt(LAST_EDITOR_DRAW_COLOR, primaryColor)
set(lastEditorDrawColor) = prefs.edit().putInt(LAST_EDITOR_DRAW_COLOR, lastEditorDrawColor).apply()
var lastEditorBrushSize: Int
get() = prefs.getInt(LAST_EDITOR_BRUSH_SIZE, 50)
set(lastEditorBrushSize) = prefs.edit().putInt(LAST_EDITOR_BRUSH_SIZE, lastEditorBrushSize).apply()
var showNotch: Boolean
get() = prefs.getBoolean(SHOW_NOTCH, true)
set(showNotch) = prefs.edit().putBoolean(SHOW_NOTCH, showNotch).apply()
var spamFoldersChecked: Boolean
get() = prefs.getBoolean(SPAM_FOLDERS_CHECKED, false)
set(spamFoldersChecked) = prefs.edit().putBoolean(SPAM_FOLDERS_CHECKED, spamFoldersChecked).apply()
var editorBrushColor: Int
get() = prefs.getInt(EDITOR_BRUSH_COLOR, -1)
set(editorBrushColor) = prefs.edit().putInt(EDITOR_BRUSH_COLOR, editorBrushColor).apply()
var editorBrushHardness: Float
get() = prefs.getFloat(EDITOR_BRUSH_HARDNESS, 0.5f)
set(editorBrushHardness) = prefs.edit().putFloat(EDITOR_BRUSH_HARDNESS, editorBrushHardness).apply()
var editorBrushSize: Float
get() = prefs.getFloat(EDITOR_BRUSH_SIZE, 0.05f)
set(editorBrushSize) = prefs.edit().putFloat(EDITOR_BRUSH_SIZE, editorBrushSize).apply()
var wereFavoritesMigrated: Boolean
get() = prefs.getBoolean(WERE_FAVORITES_MIGRATED, false)
set(wereFavoritesMigrated) = prefs.edit().putBoolean(WERE_FAVORITES_MIGRATED, wereFavoritesMigrated).apply()
}

View file

@ -0,0 +1,233 @@
package com.simplemobiletools.gallery.pro.helpers
import com.simplemobiletools.commons.helpers.MONTH_SECONDS
import com.simplemobiletools.commons.helpers.isQPlus
// shared preferences
const val DIRECTORY_SORT_ORDER = "directory_sort_order"
const val GROUP_FOLDER_PREFIX = "group_folder_"
const val VIEW_TYPE_PREFIX = "view_type_folder_"
const val SHOW_HIDDEN_MEDIA = "show_hidden_media"
const val TEMPORARILY_SHOW_HIDDEN = "temporarily_show_hidden"
const val IS_THIRD_PARTY_INTENT = "is_third_party_intent"
const val AUTOPLAY_VIDEOS = "autoplay_videos"
const val REMEMBER_LAST_VIDEO_POSITION = "remember_last_video_position"
const val LOOP_VIDEOS = "loop_videos"
const val OPEN_VIDEOS_ON_SEPARATE_SCREEN = "open_videos_on_separate_screen"
const val ANIMATE_GIFS = "animate_gifs"
const val MAX_BRIGHTNESS = "max_brightness"
const val CROP_THUMBNAILS = "crop_thumbnails"
const val SHOW_THUMBNAIL_VIDEO_DURATION = "show_thumbnail_video_duration"
const val SCREEN_ROTATION = "screen_rotation"
const val DISPLAY_FILE_NAMES = "display_file_names"
const val BLACK_BACKGROUND = "dark_background"
const val PINNED_FOLDERS = "pinned_folders"
const val FILTER_MEDIA = "filter_media"
const val DIR_COLUMN_CNT = "dir_column_cnt"
const val DIR_LANDSCAPE_COLUMN_CNT = "dir_landscape_column_cnt"
const val DIR_HORIZONTAL_COLUMN_CNT = "dir_horizontal_column_cnt"
const val DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "dir_landscape_horizontal_column_cnt"
const val MEDIA_COLUMN_CNT = "media_column_cnt"
const val MEDIA_LANDSCAPE_COLUMN_CNT = "media_landscape_column_cnt"
const val MEDIA_HORIZONTAL_COLUMN_CNT = "media_horizontal_column_cnt"
const val MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "media_landscape_horizontal_column_cnt"
const val SHOW_ALL = "show_all" // display images and videos from all folders together
const val HIDE_FOLDER_TOOLTIP_SHOWN = "hide_folder_tooltip_shown"
const val EXCLUDED_FOLDERS = "excluded_folders"
const val INCLUDED_FOLDERS = "included_folders"
const val ALBUM_COVERS = "album_covers"
const val HIDE_SYSTEM_UI = "hide_system_ui"
const val DELETE_EMPTY_FOLDERS = "delete_empty_folders"
const val ALLOW_PHOTO_GESTURES = "allow_photo_gestures"
const val ALLOW_VIDEO_GESTURES = "allow_video_gestures"
const val SHOW_MEDIA_COUNT = "show_media_count"
const val TEMP_FOLDER_PATH = "temp_folder_path"
const val VIEW_TYPE_FOLDERS = "view_type_folders"
const val VIEW_TYPE_FILES = "view_type_files"
const val SHOW_EXTENDED_DETAILS = "show_extended_details"
const val EXTENDED_DETAILS = "extended_details"
const val HIDE_EXTENDED_DETAILS = "hide_extended_details"
const val ALLOW_INSTANT_CHANGE = "allow_instant_change"
const val WAS_NEW_APP_SHOWN = "was_new_app_shown_clock"
const val LAST_FILEPICKER_PATH = "last_filepicker_path"
const val TEMP_SKIP_DELETE_CONFIRMATION = "temp_skip_delete_confirmation"
const val BOTTOM_ACTIONS = "bottom_actions"
const val LAST_VIDEO_POSITION_PREFIX = "last_video_position_"
const val VISIBLE_BOTTOM_ACTIONS = "visible_bottom_actions"
const val WERE_FAVORITES_PINNED = "were_favorites_pinned"
const val WAS_RECYCLE_BIN_PINNED = "was_recycle_bin_pinned"
const val USE_RECYCLE_BIN = "use_recycle_bin"
const val GROUP_BY = "group_by"
const val EVER_SHOWN_FOLDERS = "ever_shown_folders"
const val SHOW_RECYCLE_BIN_AT_FOLDERS = "show_recycle_bin_at_folders"
const val SHOW_RECYCLE_BIN_LAST = "show_recycle_bin_last"
const val ALLOW_ZOOMING_IMAGES = "allow_zooming_images"
const val WAS_SVG_SHOWING_HANDLED = "was_svg_showing_handled"
const val LAST_BIN_CHECK = "last_bin_check"
const val SHOW_HIGHEST_QUALITY = "show_highest_quality"
const val ALLOW_DOWN_GESTURE = "allow_down_gesture"
const val LAST_EDITOR_CROP_ASPECT_RATIO = "last_editor_crop_aspect_ratio"
const val LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X = "last_editor_crop_other_aspect_ratio_x_2"
const val LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y = "last_editor_crop_other_aspect_ratio_y_2"
const val GROUP_DIRECT_SUBFOLDERS = "group_direct_subfolders"
const val SHOW_WIDGET_FOLDER_NAME = "show_widget_folder_name"
const val ALLOW_ONE_TO_ONE_ZOOM = "allow_one_to_one_zoom"
const val ALLOW_ROTATING_WITH_GESTURES = "allow_rotating_with_gestures"
const val LAST_EDITOR_DRAW_COLOR = "last_editor_draw_color"
const val LAST_EDITOR_BRUSH_SIZE = "last_editor_brush_size"
const val SHOW_NOTCH = "show_notch"
const val FILE_LOADING_PRIORITY = "file_loading_priority"
const val SPAM_FOLDERS_CHECKED = "spam_folders_checked"
const val SHOW_THUMBNAIL_FILE_TYPES = "show_thumbnail_file_types"
const val EDITOR_BRUSH_COLOR = "editor_brush_color"
const val EDITOR_BRUSH_HARDNESS = "editor_brush_hardness"
const val EDITOR_BRUSH_SIZE = "editor_brush_size"
const val WERE_FAVORITES_MIGRATED = "were_favorites_migrated"
// slideshow
const val SLIDESHOW_INTERVAL = "slideshow_interval"
const val SLIDESHOW_INCLUDE_VIDEOS = "slideshow_include_videos"
const val SLIDESHOW_INCLUDE_GIFS = "slideshow_include_gifs"
const val SLIDESHOW_RANDOM_ORDER = "slideshow_random_order"
const val SLIDESHOW_MOVE_BACKWARDS = "slideshow_move_backwards"
const val SLIDESHOW_ANIMATION = "slideshow_animation"
const val SLIDESHOW_LOOP = "loop_slideshow"
const val SLIDESHOW_DEFAULT_INTERVAL = 5
const val SLIDESHOW_SLIDE_DURATION = 500L
const val SLIDESHOW_FADE_DURATION = 1500L
const val SLIDESHOW_START_ON_ENTER = "slideshow_start_on_enter"
// slideshow animations
const val SLIDESHOW_ANIMATION_NONE = 0
const val SLIDESHOW_ANIMATION_SLIDE = 1
const val SLIDESHOW_ANIMATION_FADE = 2
const val FAVORITES = "favorites"
const val RECYCLE_BIN = "recycle_bin"
const val SHOW_FAVORITES = "show_favorites"
const val SHOW_RECYCLE_BIN = "show_recycle_bin"
const val SHOW_NEXT_ITEM = "show_next_item"
const val SHOW_PREV_ITEM = "show_prev_item"
const val GO_TO_NEXT_ITEM = "go_to_next_item"
const val GO_TO_PREV_ITEM = "go_to_prev_item"
const val MAX_COLUMN_COUNT = 20
const val SHOW_TEMP_HIDDEN_DURATION = 300000L
const val CLICK_MAX_DURATION = 150
const val CLICK_MAX_DISTANCE = 100
const val MAX_CLOSE_DOWN_GESTURE_DURATION = 300
const val DRAG_THRESHOLD = 8
const val MONTH_MILLISECONDS = MONTH_SECONDS * 1000L
const val MIN_SKIP_LENGTH = 2000
const val HIDE_SYSTEM_UI_DELAY = 500L
const val MAX_PRINT_SIDE_SIZE = 4096
const val FAST_FORWARD_VIDEO_MS = 10000
const val DIRECTORY = "directory"
const val MEDIUM = "medium"
const val PATH = "path"
const val GET_IMAGE_INTENT = "get_image_intent"
const val GET_VIDEO_INTENT = "get_video_intent"
const val GET_ANY_INTENT = "get_any_intent"
const val SET_WALLPAPER_INTENT = "set_wallpaper_intent"
const val IS_VIEW_INTENT = "is_view_intent"
const val PICKED_PATHS = "picked_paths"
const val SHOULD_INIT_FRAGMENT = "should_init_fragment"
const val PORTRAIT_PATH = "portrait_path"
const val SKIP_AUTHENTICATION = "skip_authentication"
// rotations
const val ROTATE_BY_SYSTEM_SETTING = 0
const val ROTATE_BY_DEVICE_ROTATION = 1
const val ROTATE_BY_ASPECT_RATIO = 2
// file loading priority
const val PRIORITY_SPEED = 0
const val PRIORITY_COMPROMISE = 1
const val PRIORITY_VALIDITY = 2
// view types
const val VIEW_TYPE_GRID = 1
const val VIEW_TYPE_LIST = 2
// extended details values
const val EXT_NAME = 1
const val EXT_PATH = 2
const val EXT_SIZE = 4
const val EXT_RESOLUTION = 8
const val EXT_LAST_MODIFIED = 16
const val EXT_DATE_TAKEN = 32
const val EXT_CAMERA_MODEL = 64
const val EXT_EXIF_PROPERTIES = 128
const val EXT_DURATION = 256
const val EXT_ARTIST = 512
const val EXT_ALBUM = 1024
const val EXT_GPS = 2048
// media types
const val TYPE_IMAGES = 1
const val TYPE_VIDEOS = 2
const val TYPE_GIFS = 4
const val TYPE_RAWS = 8
const val TYPE_SVGS = 16
const val TYPE_PORTRAITS = 32
fun getDefaultFileFilter(): Int {
var mask = TYPE_IMAGES or TYPE_VIDEOS or TYPE_GIFS or TYPE_RAWS or TYPE_SVGS
if (isQPlus()) {
mask += TYPE_PORTRAITS
}
return mask
}
const val LOCATION_INTERNAL = 1
const val LOCATION_SD = 2
const val LOCATION_OTG = 3
const val GROUP_BY_NONE = 1
const val GROUP_BY_LAST_MODIFIED_DAILY = 2
const val GROUP_BY_DATE_TAKEN_DAILY = 4
const val GROUP_BY_FILE_TYPE = 8
const val GROUP_BY_EXTENSION = 16
const val GROUP_BY_FOLDER = 32
const val GROUP_BY_LAST_MODIFIED_MONTHLY = 64
const val GROUP_BY_DATE_TAKEN_MONTHLY = 128
const val GROUP_DESCENDING = 1024
// bottom actions
const val BOTTOM_ACTION_TOGGLE_FAVORITE = 1
const val BOTTOM_ACTION_EDIT = 2
const val BOTTOM_ACTION_SHARE = 4
const val BOTTOM_ACTION_DELETE = 8
const val BOTTOM_ACTION_ROTATE = 16
const val BOTTOM_ACTION_PROPERTIES = 32
const val BOTTOM_ACTION_CHANGE_ORIENTATION = 64
const val BOTTOM_ACTION_SLIDESHOW = 128
const val BOTTOM_ACTION_SHOW_ON_MAP = 256
const val BOTTOM_ACTION_TOGGLE_VISIBILITY = 512
const val BOTTOM_ACTION_RENAME = 1024
const val BOTTOM_ACTION_SET_AS = 2048
const val BOTTOM_ACTION_COPY = 4096
const val BOTTOM_ACTION_MOVE = 8192
const val BOTTOM_ACTION_RESIZE = 16384
const val DEFAULT_BOTTOM_ACTIONS = BOTTOM_ACTION_TOGGLE_FAVORITE or BOTTOM_ACTION_EDIT or BOTTOM_ACTION_SHARE or BOTTOM_ACTION_DELETE
// aspect ratios used at the editor for cropping
const val ASPECT_RATIO_FREE = 0
const val ASPECT_RATIO_ONE_ONE = 1
const val ASPECT_RATIO_FOUR_THREE = 2
const val ASPECT_RATIO_SIXTEEN_NINE = 3
const val ASPECT_RATIO_OTHER = 4
// some constants related to zooming videos
const val MIN_VIDEO_ZOOM_SCALE = 1f
const val MAX_VIDEO_ZOOM_SCALE = 5f
const val ZOOM_MODE_NONE = 0
const val ZOOM_MODE_DRAG = 1
const val ZOOM_MODE_ZOOM = 2
// constants related to image quality
const val LOW_TILE_DPI = 160
const val NORMAL_TILE_DPI = 220
const val WEIRD_TILE_DPI = 240
const val HIGH_TILE_DPI = 280

View file

@ -0,0 +1,8 @@
package com.simplemobiletools.gallery.pro.helpers
import android.view.View
import androidx.viewpager.widget.ViewPager
class DefaultPageTransformer : ViewPager.PageTransformer {
override fun transformPage(view: View, position: Float) {}
}

Some files were not shown because too many files have changed in this diff Show more