-
-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathItemsAdapter.kt
More file actions
1343 lines (1210 loc) · 51.7 KB
/
ItemsAdapter.kt
File metadata and controls
1343 lines (1210 loc) · 51.7 KB
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.filemanager.adapters
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Drawable
import android.graphics.drawable.Icon
import android.graphics.drawable.LayerDrawable
import android.net.Uri
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewbinding.ViewBinding
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller
import com.stericson.RootTools.RootTools
import net.lingala.zip4j.exception.ZipException
import net.lingala.zip4j.io.inputstream.ZipInputStream
import net.lingala.zip4j.io.outputstream.ZipOutputStream
import net.lingala.zip4j.model.LocalFileHeader
import net.lingala.zip4j.model.ZipParameters
import net.lingala.zip4j.model.enums.EncryptionMethod
import org.fossify.commons.adapters.MyRecyclerViewAdapter
import org.fossify.commons.dialogs.ConfirmationDialog
import org.fossify.commons.dialogs.FilePickerDialog
import org.fossify.commons.dialogs.PropertiesDialog
import org.fossify.commons.dialogs.RadioGroupDialog
import org.fossify.commons.dialogs.RenameDialog
import org.fossify.commons.dialogs.RenameItemDialog
import org.fossify.commons.dialogs.RenameItemsDialog
import org.fossify.commons.extensions.applyColorFilter
import org.fossify.commons.extensions.beGone
import org.fossify.commons.extensions.beVisible
import org.fossify.commons.extensions.beVisibleIf
import org.fossify.commons.extensions.convertToBitmap
import org.fossify.commons.extensions.copyToClipboard
import org.fossify.commons.extensions.createDirectorySync
import org.fossify.commons.extensions.deleteFile
import org.fossify.commons.extensions.deleteFileBg
import org.fossify.commons.extensions.deleteFolderBg
import org.fossify.commons.extensions.formatDate
import org.fossify.commons.extensions.formatSize
import org.fossify.commons.extensions.getAndroidSAFFileItems
import org.fossify.commons.extensions.getAndroidSAFUri
import org.fossify.commons.extensions.getColoredDrawableWithColor
import org.fossify.commons.extensions.getDefaultCopyDestinationPath
import org.fossify.commons.extensions.getDocumentFile
import org.fossify.commons.extensions.getDoesFilePathExist
import org.fossify.commons.extensions.getFileInputStreamSync
import org.fossify.commons.extensions.getFileOutputStreamSync
import org.fossify.commons.extensions.getFilenameFromPath
import org.fossify.commons.extensions.getIsPathDirectory
import org.fossify.commons.extensions.getMimeType
import org.fossify.commons.extensions.getParentPath
import org.fossify.commons.extensions.getTextSize
import org.fossify.commons.extensions.getTimeFormat
import org.fossify.commons.extensions.handleDeletePasswordProtection
import org.fossify.commons.extensions.hasOTGConnected
import org.fossify.commons.extensions.highlightTextPart
import org.fossify.commons.extensions.isPathOnOTG
import org.fossify.commons.extensions.isRestrictedSAFOnlyRoot
import org.fossify.commons.extensions.relativizeWith
import org.fossify.commons.extensions.setupViewBackground
import org.fossify.commons.extensions.showErrorToast
import org.fossify.commons.extensions.toFileDirItem
import org.fossify.commons.extensions.toast
import org.fossify.commons.helpers.CONFLICT_OVERWRITE
import org.fossify.commons.helpers.CONFLICT_SKIP
import org.fossify.commons.helpers.VIEW_TYPE_LIST
import org.fossify.commons.helpers.ensureBackgroundThread
import org.fossify.commons.helpers.getFilePlaceholderDrawables
import org.fossify.commons.models.FileDirItem
import org.fossify.commons.models.RadioItem
import org.fossify.commons.views.MyRecyclerView
import org.fossify.filemanager.R
import org.fossify.filemanager.activities.SimpleActivity
import org.fossify.filemanager.activities.SplashActivity
import org.fossify.filemanager.databinding.ItemDirGridBinding
import org.fossify.filemanager.databinding.ItemEmptyBinding
import org.fossify.filemanager.databinding.ItemFileDirListBinding
import org.fossify.filemanager.databinding.ItemFileGridBinding
import org.fossify.filemanager.databinding.ItemSectionBinding
import org.fossify.filemanager.dialogs.CompressAsDialog
import org.fossify.filemanager.extensions.config
import org.fossify.filemanager.extensions.isPathOnRoot
import org.fossify.filemanager.extensions.isZipFile
import org.fossify.filemanager.extensions.setAs
import org.fossify.filemanager.extensions.setLastModified
import org.fossify.filemanager.extensions.sharePaths
import org.fossify.filemanager.extensions.toggleItemVisibility
import org.fossify.filemanager.extensions.tryOpenPathIntent
import org.fossify.filemanager.helpers.OPEN_AS_AUDIO
import org.fossify.filemanager.helpers.OPEN_AS_IMAGE
import org.fossify.filemanager.helpers.OPEN_AS_OTHER
import org.fossify.filemanager.helpers.OPEN_AS_TEXT
import org.fossify.filemanager.helpers.OPEN_AS_VIDEO
import org.fossify.filemanager.helpers.RootHelpers
import org.fossify.filemanager.interfaces.ItemOperationsListener
import org.fossify.filemanager.models.ListItem
import java.io.BufferedInputStream
import java.io.Closeable
import java.io.File
import java.util.LinkedList
import java.util.Locale
class ItemsAdapter(
activity: SimpleActivity,
var listItems: MutableList<ListItem>,
private val listener: ItemOperationsListener?,
recyclerView: MyRecyclerView,
private val isPickMultipleIntent: Boolean,
private val swipeRefreshLayout: SwipeRefreshLayout?,
canHaveIndividualViewType: Boolean = true,
itemClick: (Any) -> Unit,
) : MyRecyclerViewAdapter(activity, recyclerView, itemClick),
RecyclerViewFastScroller.OnPopupTextUpdate {
private lateinit var fileDrawable: Drawable
private lateinit var folderDrawable: Drawable
private var fileDrawables = HashMap<String, Drawable>()
private var currentItemsHash = listItems.hashCode()
private var textToHighlight = ""
private val hasOTGConnected = activity.hasOTGConnected()
private var fontSize = 0f
private var smallerFontSize = 0f
private var dateFormat = ""
private var timeFormat = ""
private val config = activity.config
private val viewType = if (canHaveIndividualViewType) {
config.getFolderViewType(
path = listItems.firstOrNull { !it.isSectionTitle }?.mPath?.getParentPath().orEmpty()
)
} else {
config.viewType
}
private val isListViewType = viewType == VIEW_TYPE_LIST
private var displayFilenamesInGrid = config.displayFilenames
companion object {
private const val TYPE_FILE = 1
private const val TYPE_DIR = 2
private const val TYPE_SECTION = 3
private const val TYPE_GRID_TYPE_DIVIDER = 4
}
init {
setupDragListener(true)
initDrawables()
updateFontSizes()
dateFormat = config.dateFormat
timeFormat = activity.getTimeFormat()
}
override fun getActionMenuId() = R.menu.cab
override fun prepareActionMode(menu: Menu) {
menu.apply {
findItem(R.id.cab_decompress).isVisible =
getSelectedFileDirItems().map { it.path }.any { it.isZipFile() }
findItem(R.id.cab_confirm_selection).isVisible = isPickMultipleIntent
findItem(R.id.cab_copy_path).isVisible = isOneItemSelected()
findItem(R.id.cab_open_with).isVisible = isOneFileSelected()
findItem(R.id.cab_open_as).isVisible = isOneFileSelected()
findItem(R.id.cab_set_as).isVisible = isOneFileSelected()
findItem(R.id.cab_create_shortcut).isVisible = isOneItemSelected()
checkHideBtnVisibility(this)
}
}
override fun actionItemPressed(id: Int) {
if (selectedKeys.isEmpty()) {
return
}
when (id) {
R.id.cab_confirm_selection -> confirmSelection()
R.id.cab_rename -> displayRenameDialog()
R.id.cab_properties -> showProperties()
R.id.cab_share -> shareFiles()
R.id.cab_hide -> toggleFileVisibility(true)
R.id.cab_unhide -> toggleFileVisibility(false)
R.id.cab_create_shortcut -> createShortcut()
R.id.cab_copy_path -> copyPath()
R.id.cab_set_as -> setAs()
R.id.cab_open_with -> openWith()
R.id.cab_open_as -> openAs()
R.id.cab_copy_to -> copyMoveTo(true)
R.id.cab_move_to -> tryMoveFiles()
R.id.cab_compress -> compressSelection()
R.id.cab_decompress -> decompressSelection()
R.id.cab_select_all -> selectAll()
R.id.cab_delete -> if (config.skipDeleteConfirmation) deleteFiles() else askConfirmDelete()
}
}
override fun getSelectableItemCount(): Int {
return listItems.filter { !it.isSectionTitle && !it.isGridTypeDivider }.size
}
override fun getIsItemSelectable(position: Int): Boolean {
return !listItems[position].isSectionTitle && !listItems[position].isGridTypeDivider
}
override fun getItemSelectionKey(position: Int): Int? {
return listItems.getOrNull(position)?.path?.hashCode()
}
override fun getItemKeyPosition(key: Int): Int {
return listItems.indexOfFirst { it.path.hashCode() == key }
}
override fun onActionModeCreated() {
swipeRefreshLayout?.isRefreshing = false
swipeRefreshLayout?.isEnabled = false
}
override fun onActionModeDestroyed() {
swipeRefreshLayout?.isEnabled = config.enablePullToRefresh
}
override fun getItemViewType(position: Int): Int {
return when {
listItems[position].isGridTypeDivider -> TYPE_GRID_TYPE_DIVIDER
listItems[position].isSectionTitle -> TYPE_SECTION
listItems[position].mIsDirectory -> TYPE_DIR
else -> TYPE_FILE
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = Binding.getByItemViewType(viewType, isListViewType)
.inflate(layoutInflater, parent, false)
return createViewHolder(binding.root)
}
override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) {
val fileDirItem = listItems[position]
holder.bindView(
any = fileDirItem,
allowSingleClick = true,
allowLongClick = !fileDirItem.isSectionTitle
) { itemView, layoutPosition ->
val viewType = getItemViewType(position)
setupView(
binding = Binding.getByItemViewType(viewType, isListViewType).bind(itemView),
listItem = fileDirItem
)
}
bindViewHolder(holder)
}
override fun getItemCount() = listItems.size
private fun getItemWithKey(key: Int): FileDirItem? {
return listItems.firstOrNull { it.path.hashCode() == key }
}
private fun isOneFileSelected(): Boolean {
return isOneItemSelected() && getItemWithKey(selectedKeys.first())?.isDirectory == false
}
private fun checkHideBtnVisibility(menu: Menu) {
var hiddenCnt = 0
var unhiddenCnt = 0
getSelectedFileDirItems().map { it.name }.forEach {
if (it.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() {
if (selectedKeys.isNotEmpty()) {
val paths = getSelectedFileDirItems()
.asSequence()
.filter { !it.isDirectory }.map { it.path }
.toMutableList() as ArrayList<String>
if (paths.isEmpty()) {
finishActMode()
} else {
listener?.selectedPaths(paths)
}
}
}
private fun displayRenameDialog() {
val fileDirItems = getSelectedFileDirItems()
val paths = fileDirItems.asSequence().map { it.path }.toMutableList() as ArrayList<String>
when {
paths.size == 1 -> {
val oldPath = paths.first()
RenameItemDialog(activity, oldPath) {
config.moveFavorite(oldPath, it)
activity.runOnUiThread {
listener?.refreshFragment()
finishActMode()
}
}
}
fileDirItems.any { it.isDirectory } -> RenameItemsDialog(activity, paths) {
activity.runOnUiThread {
listener?.refreshFragment()
finishActMode()
}
}
else -> RenameDialog(activity, paths, false) {
activity.runOnUiThread {
listener?.refreshFragment()
finishActMode()
}
}
}
}
private fun showProperties() {
if (selectedKeys.size <= 1) {
PropertiesDialog(activity, getFirstSelectedItemPath(), config.shouldShowHidden())
} else {
val paths = getSelectedFileDirItems().map { it.path }
PropertiesDialog(activity, paths, config.shouldShowHidden())
}
}
private fun shareFiles() {
val selectedItems = getSelectedFileDirItems()
val paths = ArrayList<String>(selectedItems.size)
selectedItems.forEach {
addFileUris(it.path, paths)
}
activity.sharePaths(paths)
}
private fun toggleFileVisibility(hide: Boolean) {
ensureBackgroundThread {
getSelectedFileDirItems().forEach {
activity.toggleItemVisibility(it.path, hide)
}
activity.runOnUiThread {
listener?.refreshFragment()
finishActMode()
}
}
}
@SuppressLint("NewApi")
private fun createShortcut() {
val manager = activity.getSystemService(ShortcutManager::class.java)
if (manager.isRequestPinShortcutSupported) {
val path = getFirstSelectedItemPath()
val drawable = resources.getDrawable(R.drawable.shortcut_folder).mutate()
getShortcutImage(path, drawable) {
val intent = Intent(activity, SplashActivity::class.java)
intent.action = Intent.ACTION_VIEW
intent.flags =
intent.flags or
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TASK or
Intent.FLAG_ACTIVITY_NO_HISTORY
intent.data = Uri.fromFile(File(path))
val shortcut = ShortcutInfo.Builder(activity, path)
.setShortLabel(path.getFilenameFromPath())
.setIcon(Icon.createWithBitmap(drawable.convertToBitmap()))
.setIntent(intent)
.build()
manager.requestPinShortcut(shortcut, null)
}
}
}
private fun getShortcutImage(path: String, drawable: Drawable, callback: () -> Unit) {
val appIconColor = baseConfig.appIconColor
(drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_folder_background)
.applyColorFilter(appIconColor)
if (activity.getIsPathDirectory(path)) {
callback()
} else {
ensureBackgroundThread {
val options = RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.fitCenter()
val size = activity.resources.getDimension(R.dimen.shortcut_size).toInt()
val builder = Glide.with(activity)
.asDrawable()
.load(getImagePathToLoad(path))
.apply(options)
.centerCrop()
.into(size, size)
try {
val bitmap = builder.get()
drawable.findDrawableByLayerId(R.id.shortcut_folder_background)
.applyColorFilter(0)
drawable.setDrawableByLayerId(R.id.shortcut_folder_image, bitmap)
} catch (e: Exception) {
val fileIcon = fileDrawables
.getOrElse(
key = path.substringAfterLast(".").lowercase(Locale.getDefault()),
defaultValue = { fileDrawable }
)
drawable.setDrawableByLayerId(R.id.shortcut_folder_image, fileIcon)
}
activity.runOnUiThread {
callback()
}
}
}
}
@SuppressLint("NewApi")
private fun addFileUris(path: String, paths: ArrayList<String>) {
if (activity.getIsPathDirectory(path)) {
val shouldShowHidden = config.shouldShowHidden()
when {
activity.isRestrictedSAFOnlyRoot(path) -> {
activity.getAndroidSAFFileItems(path, shouldShowHidden, false) { files ->
files.forEach {
addFileUris(activity.getAndroidSAFUri(it.path).toString(), paths)
}
}
}
activity.isPathOnOTG(path) -> {
activity.getDocumentFile(path)?.listFiles()
?.filter { if (shouldShowHidden) true else !it.name!!.startsWith(".") }
?.forEach {
addFileUris(it.uri.toString(), paths)
}
}
else -> {
File(path).listFiles()
?.filter { if (shouldShowHidden) true else !it.name.startsWith('.') }
?.forEach {
addFileUris(it.absolutePath, paths)
}
}
}
} else {
paths.add(path)
}
}
private fun copyPath() {
activity.copyToClipboard(getFirstSelectedItemPath())
finishActMode()
}
private fun setAs() {
activity.setAs(getFirstSelectedItemPath())
}
private fun openWith() {
activity.tryOpenPathIntent(getFirstSelectedItemPath(), true)
}
private fun openAs() {
val res = activity.resources
val items = arrayListOf(
RadioItem(OPEN_AS_TEXT, res.getString(R.string.text_file)),
RadioItem(OPEN_AS_IMAGE, res.getString(R.string.image_file)),
RadioItem(OPEN_AS_AUDIO, res.getString(R.string.audio_file)),
RadioItem(OPEN_AS_VIDEO, res.getString(R.string.video_file)),
RadioItem(OPEN_AS_OTHER, res.getString(R.string.other_file))
)
RadioGroupDialog(activity, items) {
activity.tryOpenPathIntent(getFirstSelectedItemPath(), false, it as Int)
}
}
private fun tryMoveFiles() {
activity.handleDeletePasswordProtection {
copyMoveTo(false)
}
}
private fun copyMoveTo(isCopyOperation: Boolean) {
val files = getSelectedFileDirItems()
val firstFile = files[0]
val source = firstFile.getParentPath()
FilePickerDialog(
activity = activity,
currPath = activity.getDefaultCopyDestinationPath(config.shouldShowHidden(), source),
pickFile = false,
showHidden = config.shouldShowHidden(),
showFAB = true,
canAddShowHiddenButton = true,
showFavoritesButton = true
) { destination ->
config.lastCopyPath = destination
if (activity.isPathOnRoot(destination) || activity.isPathOnRoot(firstFile.path)) {
copyMoveRootItems(files, destination, isCopyOperation)
} else {
activity.copyMoveFilesTo(
fileDirItems = files,
source = source,
destination = destination,
isCopyOperation = isCopyOperation,
copyPhotoVideoOnly = false,
copyHidden = config.shouldShowHidden()
) {
if (!isCopyOperation) {
cleanupAfterMove(files)
} else {
refreshUI()
}
}
}
}
}
private fun cleanupAfterMove(files: List<FileDirItem>) {
ensureBackgroundThread {
val foldersToCheck = HashSet<String>()
files.forEach { fileItem ->
val path = fileItem.path
if (activity.getDoesFilePathExist(path)) {
activity.deleteFile(fileItem, true) {
val parentPath = path.getParentPath()
if (parentPath.isNotEmpty()) {
foldersToCheck.add(parentPath)
}
}
}
}
foldersToCheck.forEach { folderPath ->
deleteEmptyFoldersRecursively(folderPath)
}
refreshUI()
}
}
private fun deleteEmptyFoldersRecursively(folderPath: String) {
if (!activity.getDoesFilePathExist(folderPath) || !activity.getIsPathDirectory(folderPath)) {
return
}
val folder = File(folderPath)
val contents = folder.listFiles() ?: return
if (contents.isEmpty()) {
val parentPath = folderPath.getParentPath()
val folderItem = folder.toFileDirItem(activity)
activity.deleteFile(folderItem, true) {
if (parentPath.isNotEmpty()) {
deleteEmptyFoldersRecursively(parentPath)
}
}
}
}
private fun refreshUI() {
activity.runOnUiThread {
listener?.refreshFragment()
finishActMode()
}
}
private fun copyMoveRootItems(
files: ArrayList<FileDirItem>,
destinationPath: String,
isCopyOperation: Boolean
) {
activity.toast(R.string.copying)
ensureBackgroundThread {
val fileCnt = files.size
RootHelpers(activity).copyMoveFiles(files, destinationPath, isCopyOperation) {
when (it) {
fileCnt -> activity.toast(R.string.copying_success)
0 -> activity.toast(R.string.copy_failed)
else -> activity.toast(R.string.copying_success_partial)
}
activity.runOnUiThread {
listener?.refreshFragment()
finishActMode()
}
}
}
}
private fun compressSelection() {
val firstPath = getFirstSelectedItemPath()
if (activity.isPathOnOTG(firstPath)) {
activity.toast(R.string.unknown_error_occurred)
return
}
CompressAsDialog(activity, firstPath) { destination, password ->
activity.handleAndroidSAFDialog(firstPath) { granted ->
if (!granted) {
return@handleAndroidSAFDialog
}
activity.handleSAFDialog(firstPath) {
if (!it) {
return@handleSAFDialog
}
activity.toast(R.string.compressing)
val paths = getSelectedFileDirItems().map { it.path }
ensureBackgroundThread {
if (compressPaths(paths, destination, password)) {
activity.runOnUiThread {
activity.toast(R.string.compression_successful)
listener?.refreshFragment()
finishActMode()
}
} else {
activity.toast(R.string.compressing_failed)
}
}
}
}
}
}
private fun decompressSelection() {
val firstPath = getFirstSelectedItemPath()
if (activity.isPathOnOTG(firstPath)) {
activity.toast(R.string.unknown_error_occurred)
return
}
activity.handleSAFDialog(firstPath) {
if (!it) {
return@handleSAFDialog
}
val paths = getSelectedFileDirItems()
.asSequence()
.map { it.path }
.filter { it.isZipFile() }
.toList()
ensureBackgroundThread {
tryDecompressingPaths(paths) { success ->
activity.runOnUiThread {
if (success) {
activity.toast(R.string.decompression_successful)
listener?.refreshFragment()
finishActMode()
} else {
activity.toast(R.string.decompressing_failed)
}
}
}
}
}
}
private fun tryDecompressingPaths(
sourcePaths: List<String>,
callback: (success: Boolean) -> Unit
) {
sourcePaths.forEach { path ->
ZipInputStream(BufferedInputStream(activity.getFileInputStreamSync(path))).use { zipInputStream ->
try {
val fileDirItems = ArrayList<FileDirItem>()
var entry = zipInputStream.nextEntry
while (entry != null) {
val currPath = if (entry.isDirectory) {
path
} else {
"${path.getParentPath().trimEnd('/')}/${entry.fileName}"
}
val fileDirItem = FileDirItem(
path = currPath,
name = entry.fileName,
isDirectory = entry.isDirectory,
children = 0,
size = entry.uncompressedSize
)
fileDirItems.add(fileDirItem)
entry = zipInputStream.nextEntry
}
val destinationPath = fileDirItems.first().getParentPath().trimEnd('/')
activity.runOnUiThread {
activity.checkConflicts(fileDirItems, destinationPath, 0, LinkedHashMap()) {
ensureBackgroundThread {
decompressPaths(sourcePaths, it, callback)
}
}
}
} catch (zipException: ZipException) {
if (zipException.type == ZipException.Type.WRONG_PASSWORD) {
activity.showErrorToast(activity.getString(R.string.invalid_password))
} else {
activity.showErrorToast(zipException)
}
} catch (exception: Exception) {
activity.showErrorToast(exception)
}
}
}
}
private fun decompressPaths(
paths: List<String>,
conflictResolutions: LinkedHashMap<String, Int>,
callback: (success: Boolean) -> Unit
) {
paths.forEach { path ->
val zipInputStream =
ZipInputStream(BufferedInputStream(activity.getFileInputStreamSync(path)))
zipInputStream.use {
try {
var entry = zipInputStream.nextEntry
val zipFileName = path.getFilenameFromPath()
val newFolderName = zipFileName.subSequence(0, zipFileName.length - 4)
while (entry != null) {
val parentPath = path.getParentPath()
val newPath = "$parentPath/$newFolderName/${entry.fileName.trimEnd('/')}"
val resolution = getConflictResolution(conflictResolutions, newPath)
val doesPathExist = activity.getDoesFilePathExist(newPath)
if (doesPathExist && resolution == CONFLICT_OVERWRITE) {
val fileDirItem = FileDirItem(
path = newPath,
name = newPath.getFilenameFromPath(),
isDirectory = entry.isDirectory
)
if (activity.getIsPathDirectory(path)) {
activity.deleteFolderBg(fileDirItem, false) {
if (it) {
extractEntry(newPath, entry, zipInputStream)
} else {
callback(false)
}
}
} else {
activity.deleteFileBg(fileDirItem, false, false) {
if (it) {
extractEntry(newPath, entry, zipInputStream)
} else {
callback(false)
}
}
}
} else if (!doesPathExist) {
extractEntry(newPath, entry, zipInputStream)
}
entry = zipInputStream.nextEntry
}
callback(true)
} catch (e: Exception) {
activity.showErrorToast(e)
callback(false)
}
}
}
}
private fun extractEntry(
newPath: String,
entry: LocalFileHeader,
zipInputStream: ZipInputStream
) {
if (entry.isDirectory) {
if (!activity.createDirectorySync(newPath) && !activity.getDoesFilePathExist(newPath)) {
val error =
String.format(activity.getString(R.string.could_not_create_file), newPath)
activity.showErrorToast(error)
}
} else {
val fos = activity.getFileOutputStreamSync(newPath, newPath.getMimeType())
if (fos != null) {
zipInputStream.copyTo(fos)
File(newPath).setLastModified(entry)
}
}
}
private fun getConflictResolution(
conflictResolutions: LinkedHashMap<String, Int>,
path: String
): Int {
return if (conflictResolutions.size == 1 && conflictResolutions.containsKey("")) {
conflictResolutions[""]!!
} else if (conflictResolutions.containsKey(path)) {
conflictResolutions[path]!!
} else {
CONFLICT_SKIP
}
}
@SuppressLint("NewApi")
private fun compressPaths(
sourcePaths: List<String>,
targetPath: String,
password: String? = null
): Boolean {
val queue = LinkedList<String>()
val fos = activity.getFileOutputStreamSync(targetPath, "application/zip") ?: return false
val zout =
password?.let { ZipOutputStream(fos, password.toCharArray()) } ?: ZipOutputStream(fos)
var res: Closeable = fos
fun zipEntry(name: String, lastModified: Long) = ZipParameters().also {
it.fileNameInZip = name
it.lastModifiedFileTime = lastModified
if (password != null) {
it.isEncryptFiles = true
it.encryptionMethod = EncryptionMethod.AES
}
}
try {
sourcePaths.forEach { currentPath ->
var name: String
var mainFilePath = currentPath
val base = "${mainFilePath.getParentPath()}/"
res = zout
queue.push(mainFilePath)
if (activity.getIsPathDirectory(mainFilePath)) {
name = "${mainFilePath.getFilenameFromPath()}/"
val dirModified = File(mainFilePath).lastModified()
zout.putNextEntry(
ZipParameters().also {
it.fileNameInZip = name
it.lastModifiedFileTime = dirModified
}
)
}
while (!queue.isEmpty()) {
mainFilePath = queue.pop()
if (activity.getIsPathDirectory(mainFilePath)) {
if (activity.isRestrictedSAFOnlyRoot(mainFilePath)) {
activity.getAndroidSAFFileItems(mainFilePath, true) { files ->
for (file in files) {
name = file.path.relativizeWith(base)
if (activity.getIsPathDirectory(file.path)) {
queue.push(file.path)
name = "${name.trimEnd('/')}/"
zout.putNextEntry(zipEntry(name, file.modified))
} else {
zout.putNextEntry(zipEntry(name, file.modified))
activity.getFileInputStreamSync(file.path)!!.copyTo(zout)
zout.closeEntry()
}
}
}
} else {
val mainFile = File(mainFilePath)
for (file in mainFile.listFiles()) {
name = file.path.relativizeWith(base)
if (activity.getIsPathDirectory(file.absolutePath)) {
queue.push(file.absolutePath)
name = "${name.trimEnd('/')}/"
zout.putNextEntry(zipEntry(name, file.lastModified()))
} else {
zout.putNextEntry(zipEntry(name, file.lastModified()))
activity.getFileInputStreamSync(file.path)!!.copyTo(zout)
zout.closeEntry()
}
}
}
} else {
name =
if (base == currentPath) {
currentPath.getFilenameFromPath()
} else {
mainFilePath.relativizeWith(base)
}
val fileModified = File(mainFilePath).lastModified()
zout.putNextEntry(zipEntry(name, fileModified))
activity.getFileInputStreamSync(mainFilePath)!!.copyTo(zout)
zout.closeEntry()
}
}
}
} catch (exception: Exception) {
activity.showErrorToast(exception)
return false
} finally {
res.close()
}
return true
}
private fun askConfirmDelete() {
activity.handleDeletePasswordProtection {
val itemsCnt = selectedKeys.size
val items = if (itemsCnt == 1) {
"\"${getFirstSelectedItemPath().getFilenameFromPath()}\""
} else {
resources.getQuantityString(R.plurals.delete_items, itemsCnt, itemsCnt)
}
val question = String.format(resources.getString(R.string.deletion_confirmation), items)
ConfirmationDialog(activity, question) {
deleteFiles()
}
}
}
private fun deleteFiles() {
if (selectedKeys.isEmpty()) {
return
}
val SAFPath = getFirstSelectedItemPath()
if (activity.isPathOnRoot(SAFPath) && !RootTools.isRootAvailable()) {
activity.toast(R.string.rooted_device_only)
return
}
activity.handleSAFDialog(SAFPath) { granted ->
if (!granted) {
return@handleSAFDialog
}
val files = ArrayList<FileDirItem>(selectedKeys.size)
val positions = ArrayList<Int>()
ensureBackgroundThread {
selectedKeys.forEach { key ->
config.removeFavorite(getItemWithKey(key)?.path ?: "")
val position = listItems.indexOfFirst { it.path.hashCode() == key }
if (position != -1) {
positions.add(position)
files.add(listItems[position])
}
}
positions.sortDescending()
activity.runOnUiThread {
removeSelectedItems(positions)
listener?.deleteFiles(files)
positions.forEach {
listItems.removeAt(it)
}
}
}
}
}
private fun getFirstSelectedItemPath() = getSelectedFileDirItems().first().path
private fun getSelectedFileDirItems(): ArrayList<FileDirItem> {
return listItems.filter {
selectedKeys.contains(it.path.hashCode())
} as ArrayList<FileDirItem>
}
fun updateItems(newItems: ArrayList<ListItem>, highlightText: String = "") {
if (newItems.hashCode() != currentItemsHash) {
currentItemsHash = newItems.hashCode()
textToHighlight = highlightText
listItems = newItems.clone() as ArrayList<ListItem>
notifyDataSetChanged()
finishActMode()
} else if (textToHighlight != highlightText) {
textToHighlight = highlightText
notifyDataSetChanged()
}
}
fun updateFontSizes() {
fontSize = activity.getTextSize()
smallerFontSize = fontSize * 0.8f
notifyDataSetChanged()
}
fun updateDateTimeFormat() {
dateFormat = config.dateFormat