-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
MainActivity.kt
1562 lines (1367 loc) · 62.4 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.fossify.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.provider.MediaStore.Images
import android.provider.MediaStore.Video
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import org.fossify.commons.dialogs.CreateNewFolderDialog
import org.fossify.commons.dialogs.FilePickerDialog
import org.fossify.commons.dialogs.RadioGroupDialog
import org.fossify.commons.extensions.appLaunched
import org.fossify.commons.extensions.appLockManager
import org.fossify.commons.extensions.areSystemAnimationsEnabled
import org.fossify.commons.extensions.beGone
import org.fossify.commons.extensions.beVisible
import org.fossify.commons.extensions.beVisibleIf
import org.fossify.commons.extensions.checkWhatsNew
import org.fossify.commons.extensions.deleteFiles
import org.fossify.commons.extensions.getDoesFilePathExist
import org.fossify.commons.extensions.getFileCount
import org.fossify.commons.extensions.getFilePublicUri
import org.fossify.commons.extensions.getFilenameFromPath
import org.fossify.commons.extensions.getLatestMediaByDateId
import org.fossify.commons.extensions.getLatestMediaId
import org.fossify.commons.extensions.getMimeType
import org.fossify.commons.extensions.getProperBackgroundColor
import org.fossify.commons.extensions.getProperPrimaryColor
import org.fossify.commons.extensions.getProperSize
import org.fossify.commons.extensions.getProperTextColor
import org.fossify.commons.extensions.getStorageDirectories
import org.fossify.commons.extensions.getTimeFormat
import org.fossify.commons.extensions.handleHiddenFolderPasswordProtection
import org.fossify.commons.extensions.handleLockedFolderOpening
import org.fossify.commons.extensions.hasAllPermissions
import org.fossify.commons.extensions.hasOTGConnected
import org.fossify.commons.extensions.hasPermission
import org.fossify.commons.extensions.hideKeyboard
import org.fossify.commons.extensions.internalStoragePath
import org.fossify.commons.extensions.isExternalStorageManager
import org.fossify.commons.extensions.isGif
import org.fossify.commons.extensions.isGone
import org.fossify.commons.extensions.isImageFast
import org.fossify.commons.extensions.isMediaFile
import org.fossify.commons.extensions.isPathOnOTG
import org.fossify.commons.extensions.isRawFast
import org.fossify.commons.extensions.isSvg
import org.fossify.commons.extensions.isVideoFast
import org.fossify.commons.extensions.launchMoreAppsFromUsIntent
import org.fossify.commons.extensions.recycleBinPath
import org.fossify.commons.extensions.sdCardPath
import org.fossify.commons.extensions.showErrorToast
import org.fossify.commons.extensions.toFileDirItem
import org.fossify.commons.extensions.toast
import org.fossify.commons.extensions.underlineText
import org.fossify.commons.extensions.viewBinding
import org.fossify.commons.helpers.DAY_SECONDS
import org.fossify.commons.helpers.FAVORITES
import org.fossify.commons.helpers.PERMISSION_READ_STORAGE
import org.fossify.commons.helpers.SORT_BY_DATE_MODIFIED
import org.fossify.commons.helpers.SORT_BY_DATE_TAKEN
import org.fossify.commons.helpers.SORT_BY_SIZE
import org.fossify.commons.helpers.SORT_USE_NUMERIC_VALUE
import org.fossify.commons.helpers.VIEW_TYPE_GRID
import org.fossify.commons.helpers.VIEW_TYPE_LIST
import org.fossify.commons.helpers.ensureBackgroundThread
import org.fossify.commons.helpers.isRPlus
import org.fossify.commons.models.FileDirItem
import org.fossify.commons.models.RadioItem
import org.fossify.commons.models.Release
import org.fossify.commons.views.MyGridLayoutManager
import org.fossify.commons.views.MyRecyclerView
import org.fossify.gallery.BuildConfig
import org.fossify.gallery.R
import org.fossify.gallery.adapters.DirectoryAdapter
import org.fossify.gallery.databases.GalleryDatabase
import org.fossify.gallery.databinding.ActivityMainBinding
import org.fossify.gallery.dialogs.ChangeSortingDialog
import org.fossify.gallery.dialogs.ChangeViewTypeDialog
import org.fossify.gallery.dialogs.FilterMediaDialog
import org.fossify.gallery.dialogs.GrantAllFilesDialog
import org.fossify.gallery.extensions.addTempFolderIfNeeded
import org.fossify.gallery.extensions.config
import org.fossify.gallery.extensions.createDirectoryFromMedia
import org.fossify.gallery.extensions.directoryDB
import org.fossify.gallery.extensions.getCachedDirectories
import org.fossify.gallery.extensions.getCachedMedia
import org.fossify.gallery.extensions.getDirectorySortingValue
import org.fossify.gallery.extensions.getDirsToShow
import org.fossify.gallery.extensions.getDistinctPath
import org.fossify.gallery.extensions.getFavoritePaths
import org.fossify.gallery.extensions.getNoMediaFoldersSync
import org.fossify.gallery.extensions.getOTGFolderChildrenNames
import org.fossify.gallery.extensions.getSortedDirectories
import org.fossify.gallery.extensions.handleExcludedFolderPasswordProtection
import org.fossify.gallery.extensions.handleMediaManagementPrompt
import org.fossify.gallery.extensions.isDownloadsFolder
import org.fossify.gallery.extensions.launchAbout
import org.fossify.gallery.extensions.launchCamera
import org.fossify.gallery.extensions.launchSettings
import org.fossify.gallery.extensions.mediaDB
import org.fossify.gallery.extensions.movePathsInRecycleBin
import org.fossify.gallery.extensions.movePinnedDirectoriesToFront
import org.fossify.gallery.extensions.openRecycleBin
import org.fossify.gallery.extensions.removeInvalidDBDirectories
import org.fossify.gallery.extensions.storeDirectoryItems
import org.fossify.gallery.extensions.tryDeleteFileDirItem
import org.fossify.gallery.extensions.updateDBDirectory
import org.fossify.gallery.extensions.updateWidgets
import org.fossify.gallery.helpers.DIRECTORY
import org.fossify.gallery.helpers.GET_ANY_INTENT
import org.fossify.gallery.helpers.GET_IMAGE_INTENT
import org.fossify.gallery.helpers.GET_VIDEO_INTENT
import org.fossify.gallery.helpers.GROUP_BY_DATE_TAKEN_DAILY
import org.fossify.gallery.helpers.GROUP_BY_DATE_TAKEN_MONTHLY
import org.fossify.gallery.helpers.GROUP_BY_LAST_MODIFIED_DAILY
import org.fossify.gallery.helpers.GROUP_BY_LAST_MODIFIED_MONTHLY
import org.fossify.gallery.helpers.GROUP_DESCENDING
import org.fossify.gallery.helpers.LOCATION_INTERNAL
import org.fossify.gallery.helpers.MAX_COLUMN_COUNT
import org.fossify.gallery.helpers.MONTH_MILLISECONDS
import org.fossify.gallery.helpers.MediaFetcher
import org.fossify.gallery.helpers.PICKED_PATHS
import org.fossify.gallery.helpers.RECYCLE_BIN
import org.fossify.gallery.helpers.SET_WALLPAPER_INTENT
import org.fossify.gallery.helpers.SHOW_ALL
import org.fossify.gallery.helpers.SHOW_TEMP_HIDDEN_DURATION
import org.fossify.gallery.helpers.SKIP_AUTHENTICATION
import org.fossify.gallery.helpers.TYPE_GIFS
import org.fossify.gallery.helpers.TYPE_IMAGES
import org.fossify.gallery.helpers.TYPE_RAWS
import org.fossify.gallery.helpers.TYPE_SVGS
import org.fossify.gallery.helpers.TYPE_VIDEOS
import org.fossify.gallery.helpers.getDefaultFileFilter
import org.fossify.gallery.helpers.getPermissionToRequest
import org.fossify.gallery.helpers.getPermissionsToRequest
import org.fossify.gallery.interfaces.DirectoryOperationsListener
import org.fossify.gallery.jobs.NewPhotoFetcher
import org.fossify.gallery.models.Directory
import org.fossify.gallery.models.Medium
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.OutputStream
class MainActivity : SimpleActivity(), DirectoryOperationsListener {
companion object {
private const val PICK_MEDIA = 2
private const val PICK_WALLPAPER = 3
private const val LAST_MEDIA_CHECK_PERIOD = 3000L
}
private var mIsPickImageIntent = false
private var mIsPickVideoIntent = false
private var mIsGetImageContentIntent = false
private var mIsGetVideoContentIntent = false
private var mIsGetAnyContentIntent = false
private var mIsSetWallpaperIntent = false
private var mAllowPickingMultiple = false
private var mIsThirdPartyIntent = false
private var mIsGettingDirs = false
private var mLoadedInitialPhotos = false
private var mShouldStopFetching = false
private var mWasDefaultFolderChecked = false
private var mWasMediaManagementPromptShown = false
private var mLatestMediaId = 0L
private var mLatestMediaDateId = 0L
private var mCurrentPathPrefix = "" // used at "Group direct subfolders" for navigation
private var mOpenedSubfolders = arrayListOf("") // used at "Group direct subfolders" for navigating Up with the back button
private var mDateFormat = ""
private var mTimeFormat = ""
private var mLastMediaHandler = Handler()
private var mTempShowHiddenHandler = Handler()
private var mZoomListener: MyRecyclerView.MyZoomListener? = null
private var mLastMediaFetcher: MediaFetcher? = null
private var mDirs = ArrayList<Directory>()
private var mDirsIgnoringSearch = ArrayList<Directory>()
private var mStoredAnimateGifs = true
private var mStoredCropThumbnails = true
private var mStoredScrollHorizontally = true
private var mStoredTextColor = 0
private var mStoredPrimaryColor = 0
private var mStoredStyleString = ""
private val binding by viewBinding(ActivityMainBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
isMaterialActivity = true
super.onCreate(savedInstanceState)
setContentView(binding.root)
appLaunched(BuildConfig.APPLICATION_ID)
if (savedInstanceState == null) {
config.temporarilyShowHidden = false
config.temporarilyShowExcluded = false
config.tempSkipDeleteConfirmation = false
config.tempSkipRecycleBin = false
removeTempFolder()
checkRecycleBinItems()
startNewPhotoFetcher()
}
mIsPickImageIntent = isPickImageIntent(intent)
mIsPickVideoIntent = isPickVideoIntent(intent)
mIsGetImageContentIntent = isGetImageContentIntent(intent)
mIsGetVideoContentIntent = isGetVideoContentIntent(intent)
mIsGetAnyContentIntent = isGetAnyContentIntent(intent)
mIsSetWallpaperIntent = isSetWallpaperIntent(intent)
mAllowPickingMultiple = intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
mIsThirdPartyIntent = mIsPickImageIntent || mIsPickVideoIntent || mIsGetImageContentIntent || mIsGetVideoContentIntent ||
mIsGetAnyContentIntent || mIsSetWallpaperIntent
setupOptionsMenu()
refreshMenuItems()
updateMaterialActivityViews(
binding.directoriesCoordinator,
binding.directoriesGrid,
useTransparentNavigation = !config.scrollHorizontally,
useTopSearchMenu = true
)
binding.directoriesRefreshLayout.setOnRefreshListener { getDirectories() }
storeStateVariables()
checkWhatsNewDialog()
setupLatestMediaId()
if (!config.wereFavoritesPinned) {
config.addPinnedFolders(hashSetOf(FAVORITES))
config.wereFavoritesPinned = true
}
if (!config.wasRecycleBinPinned) {
config.addPinnedFolders(hashSetOf(RECYCLE_BIN))
config.wasRecycleBinPinned = true
config.saveFolderGrouping(SHOW_ALL, GROUP_BY_DATE_TAKEN_DAILY or GROUP_DESCENDING)
}
if (!config.wasSVGShowingHandled) {
config.wasSVGShowingHandled = true
if (config.filterMedia and TYPE_SVGS == 0) {
config.filterMedia += TYPE_SVGS
}
}
if (!config.wasSortingByNumericValueAdded) {
config.wasSortingByNumericValueAdded = true
config.sorting = config.sorting or SORT_USE_NUMERIC_VALUE
}
updateWidgets()
registerFileUpdateListener()
binding.directoriesSwitchSearching.setOnClickListener {
launchSearchActivity()
}
// just request the permission, tryLoadGallery will then trigger in onResume
handleMediaPermissions()
}
private fun handleMediaPermissions(callback: (() -> Unit)? = null) {
requestMediaPermissions(enableRationale = true) {
callback?.invoke()
if (isRPlus() && !mWasMediaManagementPromptShown) {
mWasMediaManagementPromptShown = true
handleMediaManagementPrompt { }
}
}
}
override fun onStart() {
super.onStart()
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
}
override fun onResume() {
super.onResume()
updateMenuColors()
config.isThirdPartyIntent = false
mDateFormat = config.dateFormat
mTimeFormat = getTimeFormat()
refreshMenuItems()
if (mStoredAnimateGifs != config.animateGifs) {
getRecyclerAdapter()?.updateAnimateGifs(config.animateGifs)
}
if (mStoredCropThumbnails != config.cropThumbnails) {
getRecyclerAdapter()?.updateCropThumbnails(config.cropThumbnails)
}
if (mStoredScrollHorizontally != config.scrollHorizontally) {
mLoadedInitialPhotos = false
binding.directoriesGrid.adapter = null
getDirectories()
}
if (mStoredTextColor != getProperTextColor()) {
getRecyclerAdapter()?.updateTextColor(getProperTextColor())
}
val primaryColor = getProperPrimaryColor()
if (mStoredPrimaryColor != primaryColor) {
getRecyclerAdapter()?.updatePrimaryColor()
}
val styleString = "${config.folderStyle}${config.showFolderMediaCount}${config.limitFolderTitle}"
if (mStoredStyleString != styleString) {
setupAdapter(mDirs, forceRecreate = true)
}
binding.directoriesFastscroller.updateColors(primaryColor)
binding.directoriesRefreshLayout.isEnabled = config.enablePullToRefresh
getRecyclerAdapter()?.apply {
dateFormat = config.dateFormat
timeFormat = getTimeFormat()
}
binding.directoriesEmptyPlaceholder.setTextColor(getProperTextColor())
binding.directoriesEmptyPlaceholder2.setTextColor(primaryColor)
binding.directoriesSwitchSearching.setTextColor(primaryColor)
binding.directoriesSwitchSearching.underlineText()
binding.directoriesEmptyPlaceholder2.bringToFront()
if (!binding.mainMenu.isSearchOpen) {
refreshMenuItems()
tryLoadGallery()
}
if (config.searchAllFilesByDefault) {
binding.mainMenu.updateHintText(getString(org.fossify.commons.R.string.search_files))
} else {
binding.mainMenu.updateHintText(getString(org.fossify.commons.R.string.search_folders))
}
}
override fun onPause() {
super.onPause()
binding.directoriesRefreshLayout.isRefreshing = false
mIsGettingDirs = false
storeStateVariables()
mLastMediaHandler.removeCallbacksAndMessages(null)
}
override fun onStop() {
super.onStop()
if (config.temporarilyShowHidden || config.tempSkipDeleteConfirmation || config.temporarilyShowExcluded) {
mTempShowHiddenHandler.postDelayed({
config.temporarilyShowHidden = false
config.temporarilyShowExcluded = false
config.tempSkipDeleteConfirmation = false
config.tempSkipRecycleBin = false
}, SHOW_TEMP_HIDDEN_DURATION)
} else {
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
}
}
override fun onDestroy() {
super.onDestroy()
if (!isChangingConfigurations) {
config.temporarilyShowHidden = false
config.temporarilyShowExcluded = false
config.tempSkipDeleteConfirmation = false
config.tempSkipRecycleBin = false
mTempShowHiddenHandler.removeCallbacksAndMessages(null)
removeTempFolder()
unregisterFileUpdateListener()
if (!config.showAll) {
mLastMediaFetcher?.shouldStop = true
GalleryDatabase.destroyInstance()
}
}
}
override fun onBackPressed() {
if (binding.mainMenu.isSearchOpen) {
binding.mainMenu.closeSearch()
} else if (config.groupDirectSubfolders) {
if (mCurrentPathPrefix.isEmpty()) {
super.onBackPressed()
} else {
mOpenedSubfolders.removeLast()
mCurrentPathPrefix = mOpenedSubfolders.last()
setupAdapter(mDirs)
}
} else {
appLockManager.lock()
super.onBackPressed()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_MEDIA && resultData != null) {
val resultIntent = Intent()
var resultUri: Uri? = null
if (mIsThirdPartyIntent) {
when {
intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true && intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0 -> {
resultUri = fillExtraOutput(resultData)
}
resultData.extras?.containsKey(PICKED_PATHS) == true -> fillPickedPaths(resultData, resultIntent)
else -> fillIntentPath(resultData, resultIntent)
}
}
if (resultUri != null) {
resultIntent.data = resultUri
resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
setResult(Activity.RESULT_OK, resultIntent)
finish()
} else if (requestCode == PICK_WALLPAPER) {
setResult(Activity.RESULT_OK)
finish()
}
}
super.onActivityResult(requestCode, resultCode, resultData)
}
private fun refreshMenuItems() {
if (!mIsThirdPartyIntent) {
binding.mainMenu.getToolbar().menu.apply {
findItem(R.id.column_count).isVisible = config.viewTypeFolders == VIEW_TYPE_GRID
findItem(R.id.set_as_default_folder).isVisible = !config.defaultFolder.isEmpty()
findItem(R.id.open_recycle_bin).isVisible = config.useRecycleBin && !config.showRecycleBinAtFolders
findItem(R.id.more_apps_from_us).isVisible = !resources.getBoolean(org.fossify.commons.R.bool.hide_google_relations)
}
}
binding.mainMenu.getToolbar().menu.apply {
findItem(R.id.temporarily_show_hidden).isVisible = !config.shouldShowHidden
findItem(R.id.stop_showing_hidden).isVisible = (!isRPlus() || isExternalStorageManager()) && config.temporarilyShowHidden
findItem(R.id.temporarily_show_excluded).isVisible = !config.temporarilyShowExcluded
findItem(R.id.stop_showing_excluded).isVisible = config.temporarilyShowExcluded
}
}
private fun setupOptionsMenu() {
val menuId = if (mIsThirdPartyIntent) {
R.menu.menu_main_intent
} else {
R.menu.menu_main
}
binding.mainMenu.getToolbar().inflateMenu(menuId)
binding.mainMenu.toggleHideOnScroll(!config.scrollHorizontally)
binding.mainMenu.setupMenu()
binding.mainMenu.onSearchOpenListener = {
if (config.searchAllFilesByDefault) {
launchSearchActivity()
}
}
binding.mainMenu.onSearchTextChangedListener = { text ->
setupAdapter(mDirsIgnoringSearch, text)
binding.directoriesRefreshLayout.isEnabled = text.isEmpty() && config.enablePullToRefresh
binding.directoriesSwitchSearching.beVisibleIf(text.isNotEmpty())
}
binding.mainMenu.getToolbar().setOnMenuItemClickListener { menuItem ->
when (menuItem.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.temporarily_show_excluded -> tryToggleTemporarilyShowExcluded()
R.id.stop_showing_excluded -> tryToggleTemporarilyShowExcluded()
R.id.create_new_folder -> createNewFolder()
R.id.open_recycle_bin -> openRecycleBin()
R.id.column_count -> changeColumnCount()
R.id.set_as_default_folder -> setAsDefaultFolder()
R.id.more_apps_from_us -> launchMoreAppsFromUsIntent()
R.id.settings -> launchSettings()
R.id.about -> launchAbout()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
private fun updateMenuColors() {
updateStatusbarColor(getProperBackgroundColor())
binding.mainMenu.updateColors()
}
private fun getRecyclerAdapter() = binding.directoriesGrid.adapter as? DirectoryAdapter
private fun storeStateVariables() {
mStoredTextColor = getProperTextColor()
mStoredPrimaryColor = getProperPrimaryColor()
config.apply {
mStoredAnimateGifs = animateGifs
mStoredCropThumbnails = cropThumbnails
mStoredScrollHorizontally = scrollHorizontally
mStoredStyleString = "$folderStyle$showFolderMediaCount$limitFolderTitle"
}
}
private fun startNewPhotoFetcher() {
val photoFetcher = NewPhotoFetcher()
if (!photoFetcher.isScheduled(applicationContext)) {
photoFetcher.scheduleJob(applicationContext)
}
}
private fun removeTempFolder() {
if (config.tempFolderPath.isNotEmpty()) {
val newFolder = File(config.tempFolderPath)
if (getDoesFilePathExist(newFolder.absolutePath) && newFolder.isDirectory) {
if (newFolder.getProperSize(true) == 0L && newFolder.getFileCount(true) == 0 && newFolder.list()?.isEmpty() == true) {
toast(String.format(getString(org.fossify.commons.R.string.deleting_folder), config.tempFolderPath), Toast.LENGTH_LONG)
tryDeleteFileDirItem(newFolder.toFileDirItem(applicationContext), true, true)
}
}
config.tempFolderPath = ""
}
}
private fun checkOTGPath() {
ensureBackgroundThread {
if (!config.wasOTGHandled && hasPermission(getPermissionToRequest()) && hasOTGConnected() && config.OTGPath.isEmpty()) {
getStorageDirectories().firstOrNull { it.trimEnd('/') != internalStoragePath && it.trimEnd('/') != sdCardPath }?.apply {
config.wasOTGHandled = true
val otgPath = trimEnd('/')
config.OTGPath = otgPath
config.addIncludedFolder(otgPath)
}
}
}
}
private fun checkDefaultSpamFolders() {
if (!config.spamFoldersChecked) {
val spamFolders = arrayListOf(
"/storage/emulated/0/Android/data/com.facebook.orca/files/stickers"
)
val OTGPath = config.OTGPath
spamFolders.forEach {
if (getDoesFilePathExist(it, OTGPath)) {
config.addExcludedFolder(it)
}
}
config.spamFoldersChecked = true
}
}
private fun tryLoadGallery() {
// avoid calling anything right after granting the permission, it will be called from onResume()
val wasMissingPermission = config.appRunCount == 1 && !hasAllPermissions(getPermissionsToRequest())
handleMediaPermissions {
if (wasMissingPermission) {
return@handleMediaPermissions
}
if (!mWasDefaultFolderChecked) {
openDefaultFolder()
mWasDefaultFolderChecked = true
}
checkOTGPath()
checkDefaultSpamFolders()
if (config.showAll) {
showAllMedia()
} else {
getDirectories()
}
setupLayoutManager()
}
}
private fun getDirectories() {
if (mIsGettingDirs) {
return
}
mShouldStopFetching = true
mIsGettingDirs = true
val getImagesOnly = mIsPickImageIntent || mIsGetImageContentIntent
val getVideosOnly = mIsPickVideoIntent || mIsGetVideoContentIntent
getCachedDirectories(getVideosOnly, getImagesOnly) {
gotDirectories(addTempFolderIfNeeded(it))
}
}
private fun launchSearchActivity() {
hideKeyboard()
Intent(this, SearchActivity::class.java).apply {
startActivity(this)
}
binding.mainMenu.postDelayed({
binding.mainMenu.closeSearch()
}, 500)
}
private fun showSortingDialog() {
ChangeSortingDialog(this, true, false) {
binding.directoriesGrid.adapter = null
if (config.directorySorting and SORT_BY_DATE_MODIFIED != 0 || config.directorySorting and SORT_BY_DATE_TAKEN != 0) {
getDirectories()
} else {
ensureBackgroundThread {
gotDirectories(getCurrentlyDisplayedDirs())
}
}
getRecyclerAdapter()?.directorySorting = config.directorySorting
}
}
private fun showFilterMediaDialog() {
FilterMediaDialog(this) {
mShouldStopFetching = true
binding.directoriesRefreshLayout.isRefreshing = true
binding.directoriesGrid.adapter = null
getDirectories()
}
}
private fun showAllMedia() {
config.showAll = true
Intent(this, MediaActivity::class.java).apply {
putExtra(DIRECTORY, "")
if (mIsThirdPartyIntent) {
handleMediaIntent(this)
} else {
hideKeyboard()
startActivity(this)
finish()
}
}
}
private fun changeViewType() {
ChangeViewTypeDialog(this, true) {
refreshMenuItems()
setupLayoutManager()
binding.directoriesGrid.adapter = null
setupAdapter(getRecyclerAdapter()?.dirs ?: mDirs)
}
}
private fun tryToggleTemporarilyShowHidden() {
if (config.temporarilyShowHidden) {
toggleTemporarilyShowHidden(false)
} else {
if (isRPlus() && !isExternalStorageManager()) {
GrantAllFilesDialog(this)
} else {
handleHiddenFolderPasswordProtection {
toggleTemporarilyShowHidden(true)
}
}
}
}
private fun toggleTemporarilyShowHidden(show: Boolean) {
mLoadedInitialPhotos = false
config.temporarilyShowHidden = show
binding.directoriesGrid.adapter = null
getDirectories()
refreshMenuItems()
}
private fun tryToggleTemporarilyShowExcluded() {
if (config.temporarilyShowExcluded) {
toggleTemporarilyShowExcluded(false)
} else {
handleExcludedFolderPasswordProtection {
toggleTemporarilyShowExcluded(true)
}
}
}
private fun toggleTemporarilyShowExcluded(show: Boolean) {
mLoadedInitialPhotos = false
config.temporarilyShowExcluded = show
binding.directoriesGrid.adapter = null
getDirectories()
refreshMenuItems()
}
override fun deleteFolders(folders: ArrayList<File>) {
val fileDirItems =
folders.asSequence().filter { it.isDirectory }.map { FileDirItem(it.absolutePath, it.name, true) }.toMutableList() as ArrayList<FileDirItem>
when {
fileDirItems.isEmpty() -> return
fileDirItems.size == 1 -> {
try {
toast(String.format(getString(org.fossify.commons.R.string.deleting_folder), fileDirItems.first().name))
} catch (e: Exception) {
showErrorToast(e)
}
}
else -> {
val baseString =
if (config.useRecycleBin && !config.tempSkipRecycleBin) org.fossify.commons.R.plurals.moving_items_into_bin else org.fossify.commons.R.plurals.delete_items
val deletingItems = resources.getQuantityString(baseString, fileDirItems.size, fileDirItems.size)
toast(deletingItems)
}
}
val itemsToDelete = ArrayList<FileDirItem>()
val filter = config.filterMedia
val showHidden = config.shouldShowHidden
fileDirItems.filter { it.isDirectory }.forEach {
val files = File(it.path).listFiles()
files?.filter {
it.absolutePath.isMediaFile() && (showHidden || !it.name.startsWith('.')) &&
((it.isImageFast() && filter and TYPE_IMAGES != 0) ||
(it.isVideoFast() && filter and TYPE_VIDEOS != 0) ||
(it.isGif() && filter and TYPE_GIFS != 0) ||
(it.isRawFast() && filter and TYPE_RAWS != 0) ||
(it.isSvg() && filter and TYPE_SVGS != 0))
}?.mapTo(itemsToDelete) { it.toFileDirItem(applicationContext) }
}
if (config.useRecycleBin && !config.tempSkipRecycleBin) {
val pathsToDelete = ArrayList<String>()
itemsToDelete.mapTo(pathsToDelete) { it.path }
movePathsInRecycleBin(pathsToDelete) {
if (it) {
deleteFilteredFileDirItems(itemsToDelete, folders)
} else {
toast(org.fossify.commons.R.string.unknown_error_occurred)
}
}
} else {
deleteFilteredFileDirItems(itemsToDelete, folders)
}
}
private fun deleteFilteredFileDirItems(fileDirItems: ArrayList<FileDirItem>, folders: ArrayList<File>) {
val OTGPath = config.OTGPath
deleteFiles(fileDirItems) {
runOnUiThread {
refreshItems()
}
ensureBackgroundThread {
folders.filter { !getDoesFilePathExist(it.absolutePath, OTGPath) }.forEach {
directoryDB.deleteDirPath(it.absolutePath)
}
if (config.deleteEmptyFolders) {
folders.filter { !it.absolutePath.isDownloadsFolder() && it.isDirectory && it.toFileDirItem(this).getProperFileCount(this, true) == 0 }
.forEach {
tryDeleteFileDirItem(it.toFileDirItem(this), true, true)
}
}
}
}
}
private fun setupLayoutManager() {
if (config.viewTypeFolders == VIEW_TYPE_GRID) {
setupGridLayoutManager()
} else {
setupListLayoutManager()
}
(binding.directoriesRefreshLayout.layoutParams as RelativeLayout.LayoutParams).addRule(RelativeLayout.BELOW, R.id.directories_switch_searching)
}
private fun setupGridLayoutManager() {
val layoutManager = binding.directoriesGrid.layoutManager as MyGridLayoutManager
if (config.scrollHorizontally) {
layoutManager.orientation = RecyclerView.HORIZONTAL
binding.directoriesRefreshLayout.layoutParams =
RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
} else {
layoutManager.orientation = RecyclerView.VERTICAL
binding.directoriesRefreshLayout.layoutParams =
RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
layoutManager.spanCount = config.dirColumnCnt
}
private fun setupListLayoutManager() {
val layoutManager = binding.directoriesGrid.layoutManager as MyGridLayoutManager
layoutManager.spanCount = 1
layoutManager.orientation = RecyclerView.VERTICAL
binding.directoriesRefreshLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
mZoomListener = null
}
private fun initZoomListener() {
if (config.viewTypeFolders == VIEW_TYPE_GRID) {
val layoutManager = binding.directoriesGrid.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 createNewFolder() {
FilePickerDialog(this, internalStoragePath, false, config.shouldShowHidden, false, true) {
CreateNewFolderDialog(this, it) {
config.tempFolderPath = it
ensureBackgroundThread {
gotDirectories(addTempFolderIfNeeded(getCurrentlyDisplayedDirs()))
}
}
}
}
private fun changeColumnCount() {
val items = ArrayList<RadioItem>()
for (i in 1..MAX_COLUMN_COUNT) {
items.add(RadioItem(i, resources.getQuantityString(org.fossify.commons.R.plurals.column_counts, i, i)))
}
val currentColumnCount = (binding.directoriesGrid.layoutManager as MyGridLayoutManager).spanCount
RadioGroupDialog(this, items, currentColumnCount) {
val newColumnCount = it as Int
if (currentColumnCount != newColumnCount) {
config.dirColumnCnt = newColumnCount
columnCountChanged()
}
}
}
private fun increaseColumnCount() {
config.dirColumnCnt += 1
columnCountChanged()
}
private fun reduceColumnCount() {
config.dirColumnCnt -= 1
columnCountChanged()
}
private fun columnCountChanged() {
(binding.directoriesGrid.layoutManager as MyGridLayoutManager).spanCount = config.dirColumnCnt
refreshMenuItems()
getRecyclerAdapter()?.apply {
notifyItemRangeChanged(0, dirs.size)
}
}
private fun isPickImageIntent(intent: Intent) = isPickIntent(intent) && (hasImageContentData(intent) || isImageType(intent))
private fun isPickVideoIntent(intent: Intent) = isPickIntent(intent) && (hasVideoContentData(intent) || isVideoType(intent))
private fun isPickIntent(intent: Intent) = intent.action == Intent.ACTION_PICK
private fun isGetContentIntent(intent: Intent) = intent.action == Intent.ACTION_GET_CONTENT && intent.type != null
private fun isGetImageContentIntent(intent: Intent) = isGetContentIntent(intent) &&
(intent.type!!.startsWith("image/") || intent.type == Images.Media.CONTENT_TYPE)
private fun isGetVideoContentIntent(intent: Intent) = isGetContentIntent(intent) &&
(intent.type!!.startsWith("video/") || intent.type == Video.Media.CONTENT_TYPE)
private fun isGetAnyContentIntent(intent: Intent) = isGetContentIntent(intent) && intent.type == "*/*"
private fun isSetWallpaperIntent(intent: Intent?) = intent?.action == Intent.ACTION_SET_WALLPAPER
private fun hasImageContentData(intent: Intent) = (intent.data == Images.Media.EXTERNAL_CONTENT_URI ||
intent.data == Images.Media.INTERNAL_CONTENT_URI)
private fun hasVideoContentData(intent: Intent) = (intent.data == Video.Media.EXTERNAL_CONTENT_URI ||
intent.data == Video.Media.INTERNAL_CONTENT_URI)
private fun isImageType(intent: Intent) = (intent.type?.startsWith("image/") == true || intent.type == Images.Media.CONTENT_TYPE)
private fun isVideoType(intent: Intent) = (intent.type?.startsWith("video/") == true || intent.type == Video.Media.CONTENT_TYPE)
private fun fillExtraOutput(resultData: Intent): Uri? {
val file = File(resultData.data!!.path!!)
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
val output = intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri
inputStream = FileInputStream(file)
outputStream = contentResolver.openOutputStream(output)
inputStream.copyTo(outputStream!!)
} catch (e: SecurityException) {
showErrorToast(e)
} catch (ignored: FileNotFoundException) {
return getFilePublicUri(file, BuildConfig.APPLICATION_ID)
} finally {
inputStream?.close()
outputStream?.close()
}
return null
}
private fun fillPickedPaths(resultData: Intent, resultIntent: Intent) {
val paths = resultData.extras!!.getStringArrayList(PICKED_PATHS)
val uris = paths!!.map { getFilePublicUri(File(it), BuildConfig.APPLICATION_ID) } as ArrayList
val clipData = ClipData("Attachment", arrayOf("image/*", "video/*"), ClipData.Item(uris.removeAt(0)))
uris.forEach {
clipData.addItem(ClipData.Item(it))
}
resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
resultIntent.clipData = clipData
}
private fun fillIntentPath(resultData: Intent, resultIntent: Intent) {
val data = resultData.data
val path = if (data.toString().startsWith("/")) data.toString() else data!!.path
val uri = getFilePublicUri(File(path!!), BuildConfig.APPLICATION_ID)
val type = path.getMimeType()
resultIntent.setDataAndTypeAndNormalize(uri, type)
resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
private fun itemClicked(path: String) {
handleLockedFolderOpening(path) { success ->
if (success) {
Intent(this, MediaActivity::class.java).apply {
putExtra(SKIP_AUTHENTICATION, true)
putExtra(DIRECTORY, path)
handleMediaIntent(this)
}
}
}
}
private fun handleMediaIntent(intent: Intent) {
hideKeyboard()
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>) {
mIsGettingDirs = false
mShouldStopFetching = false
// if hidden item showing is disabled but all Favorite items are hidden, hide the Favorites folder
if (!config.shouldShowHidden) {
val favoritesFolder = newDirs.firstOrNull { it.areFavorites() }
if (favoritesFolder != null && favoritesFolder.tmb.getFilenameFromPath().startsWith('.')) {
newDirs.remove(favoritesFolder)
}
}
val dirs = getSortedDirectories(newDirs)
if (config.groupDirectSubfolders) {
mDirs = dirs.clone() as ArrayList<Directory>
}
var isPlaceholderVisible = dirs.isEmpty()