-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathMainFragment.java
More file actions
1622 lines (1459 loc) · 61.1 KB
/
MainFragment.java
File metadata and controls
1622 lines (1459 loc) · 61.1 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
/*
* Copyright (C) 2014-2024 Arpit Khurana <arpitkh96@gmail.com>, Vishal Nehra <vishalmeham2@gmail.com>,
* Emmanuel Messulam<emmanuelbendavid@gmail.com>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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 <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.ui.fragments;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.JELLY_BEAN;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
import static android.os.Build.VERSION_CODES.Q;
import static com.amaze.filemanager.filesystem.FileProperties.ANDROID_DATA_DIRS;
import static com.amaze.filemanager.filesystem.FileProperties.ANDROID_DEVICE_DATA_DIRS;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_SHOW_DIVIDERS;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_SHOW_GOBACK_BUTTON;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_SHOW_HIDDENFILES;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_SHOW_THUMB;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amaze.filemanager.R;
import com.amaze.filemanager.adapters.RecyclerAdapter;
import com.amaze.filemanager.adapters.data.LayoutElementParcelable;
import com.amaze.filemanager.adapters.holders.ItemViewHolder;
import com.amaze.filemanager.application.AppConfig;
import com.amaze.filemanager.asynchronous.asynctasks.DeleteTask;
import com.amaze.filemanager.asynchronous.asynctasks.LoadFilesListTask;
import com.amaze.filemanager.asynchronous.handlers.FileHandler;
import com.amaze.filemanager.database.SortHandler;
import com.amaze.filemanager.database.models.explorer.Tab;
import com.amaze.filemanager.fileoperations.filesystem.OpenMode;
import com.amaze.filemanager.filesystem.CustomFileObserver;
import com.amaze.filemanager.filesystem.FileProperties;
import com.amaze.filemanager.filesystem.HybridFile;
import com.amaze.filemanager.filesystem.HybridFileParcelable;
import com.amaze.filemanager.filesystem.MediaStoreHack;
import com.amaze.filemanager.filesystem.SafRootHolder;
import com.amaze.filemanager.filesystem.files.CryptUtil;
import com.amaze.filemanager.filesystem.files.EncryptDecryptUtils;
import com.amaze.filemanager.filesystem.files.FileUtils;
import com.amaze.filemanager.filesystem.files.MediaConnectionUtils;
import com.amaze.filemanager.ui.ExtensionsKt;
import com.amaze.filemanager.ui.activities.MainActivity;
import com.amaze.filemanager.ui.activities.MainActivityViewModel;
import com.amaze.filemanager.ui.dialogs.GeneralDialogCreation;
import com.amaze.filemanager.ui.drag.RecyclerAdapterDragListener;
import com.amaze.filemanager.ui.drag.TabFragmentBottomDragListener;
import com.amaze.filemanager.ui.fragments.data.MainFragmentViewModel;
import com.amaze.filemanager.ui.icons.MimeTypes;
import com.amaze.filemanager.ui.provider.UtilitiesProvider;
import com.amaze.filemanager.ui.theme.AppTheme;
import com.amaze.filemanager.ui.views.CustomScrollGridLayoutManager;
import com.amaze.filemanager.ui.views.CustomScrollLinearLayoutManager;
import com.amaze.filemanager.ui.views.DividerItemDecoration;
import com.amaze.filemanager.ui.views.FastScroller;
import com.amaze.filemanager.ui.views.WarnableTextInputValidator;
import com.amaze.filemanager.utils.BottomBarButtonPath;
import com.amaze.filemanager.utils.ContextCompatExtKt;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.GenericExtKt;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.Utils;
import com.google.android.material.appbar.AppBarLayout;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.UriPermission;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import kotlin.collections.ArraysKt;
import kotlin.collections.CollectionsKt;
import kotlin.text.StringsKt;
public class MainFragment extends Fragment
implements BottomBarButtonPath,
ViewTreeObserver.OnGlobalLayoutListener,
AdjustListViewForTv<ItemViewHolder> {
private static final Logger LOG = LoggerFactory.getLogger(MainFragment.class);
private static final String KEY_FRAGMENT_MAIN = "main";
/** Key for boolean in arguments whether to hide the FAB if this {@link MainFragment} is shown */
public static final String BUNDLE_HIDE_FAB = "hideFab";
public SwipeRefreshLayout mSwipeRefreshLayout;
public RecyclerAdapter adapter;
private SharedPreferences sharedPref;
// ATTRIBUTES FOR APPEARANCE AND COLORS
private LinearLayoutManager mLayoutManager;
private GridLayoutManager mLayoutManagerGrid;
private DividerItemDecoration dividerItemDecoration;
private AppBarLayout mToolbarContainer;
private SwipeRefreshLayout nofilesview;
private RecyclerView listView;
private UtilitiesProvider utilsProvider;
private HashMap<String, Bundle> scrolls = new HashMap<>();
private View rootView;
private FastScroller fastScroller;
private CustomFileObserver customFileObserver;
// defines the current visible tab, default either 0 or 1
// private int mCurrentTab;
private MainFragmentViewModel mainFragmentViewModel;
private MainActivityViewModel mainActivityViewModel;
private boolean hideFab = false;
private final ActivityResultLauncher<Intent> handleDocumentUriForRestrictedDirectories =
registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (SDK_INT >= Q) {
if (result.getData() != null && getContext() != null) {
getContext()
.getContentResolver()
.takePersistableUriPermission(
result.getData().getData(),
Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
SafRootHolder.setUriRoot(result.getData().getData());
loadlist(result.getData().getDataString(), false, OpenMode.DOCUMENT_FILE, true);
} else if (getContext() != null) {
AppConfig.toast(requireContext(), getString(R.string.operation_unsuccesful));
}
}
});
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainFragmentViewModel = new ViewModelProvider(this).get(MainFragmentViewModel.class);
mainActivityViewModel =
new ViewModelProvider(requireMainActivity()).get(MainActivityViewModel.class);
utilsProvider = requireMainActivity().getUtilsProvider();
sharedPref = PreferenceManager.getDefaultSharedPreferences(requireActivity());
mainFragmentViewModel.initBundleArguments(getArguments());
mainFragmentViewModel.initIsList();
mainFragmentViewModel.initColumns(sharedPref);
mainFragmentViewModel.initSortModes(
SortHandler.getSortType(getContext(), getCurrentPath()), sharedPref);
mainFragmentViewModel.setAccentColor(requireMainActivity().getAccent());
mainFragmentViewModel.setPrimaryColor(
requireMainActivity().getCurrentColorPreference().getPrimaryFirstTab());
mainFragmentViewModel.setPrimaryTwoColor(
requireMainActivity().getCurrentColorPreference().getPrimarySecondTab());
if (getArguments() != null) {
hideFab = getArguments().getBoolean(BUNDLE_HIDE_FAB, false);
}
}
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.main_frag, container, false);
return rootView;
}
@Override
@SuppressWarnings("PMD.NPathComplexity")
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainFragmentViewModel = new ViewModelProvider(this).get(MainFragmentViewModel.class);
listView = rootView.findViewById(R.id.listView);
mToolbarContainer = requireMainActivity().getAppbar().getAppbarLayout();
fastScroller = rootView.findViewById(R.id.fastscroll);
fastScroller.setPressedHandleColor(mainFragmentViewModel.getAccentColor());
View.OnTouchListener onTouchListener =
(view1, motionEvent) -> {
if (adapter != null && mainFragmentViewModel.getStopAnims()) {
stopAnimation();
mainFragmentViewModel.setStopAnims(false);
}
return false;
};
listView.setOnTouchListener(onTouchListener);
// listView.setOnDragListener(new MainFragmentDragListener());
mToolbarContainer.setOnTouchListener(onTouchListener);
mSwipeRefreshLayout = rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(() -> updateList(true));
// String itemsstring = res.getString(R.string.items);// TODO: 23/5/2017 use or delete
mToolbarContainer.setBackgroundColor(
MainActivity.currentTab == 1
? mainFragmentViewModel.getPrimaryTwoColor()
: mainFragmentViewModel.getPrimaryColor());
// listView.setPadding(listView.getPaddingLeft(), paddingTop, listView.getPaddingRight(),
// listView.getPaddingBottom());
setHasOptionsMenu(false);
initNoFileLayout();
HybridFile f = new HybridFile(OpenMode.UNKNOWN, mainFragmentViewModel.getCurrentPath());
f.generateMode(getActivity());
getMainActivity().getAppbar().getBottomBar().setClickListener();
if (utilsProvider.getAppTheme().equals(AppTheme.LIGHT) && !mainFragmentViewModel.isList()) {
listView.setBackgroundColor(Utils.getColor(getContext(), R.color.grid_background_light));
} else {
listView.setBackgroundDrawable(null);
}
listView.setHasFixedSize(true);
if (mainFragmentViewModel.isList()) {
mLayoutManager = new CustomScrollLinearLayoutManager(getContext());
listView.setLayoutManager(mLayoutManager);
} else {
if (mainFragmentViewModel.getColumns() == null)
mLayoutManagerGrid = new CustomScrollGridLayoutManager(getActivity(), 3);
else
mLayoutManagerGrid =
new CustomScrollGridLayoutManager(getActivity(), mainFragmentViewModel.getColumns());
setGridLayoutSpanSizeLookup(mLayoutManagerGrid);
listView.setLayoutManager(mLayoutManagerGrid);
}
// use a linear layout manager
// View footerView = getActivity().getLayoutInflater().inflate(R.layout.divider, null);// TODO:
// 23/5/2017 use or delete
dividerItemDecoration =
new DividerItemDecoration(requireActivity(), false, getBoolean(PREFERENCE_SHOW_DIVIDERS));
listView.addItemDecoration(dividerItemDecoration);
mSwipeRefreshLayout.setColorSchemeColors(mainFragmentViewModel.getAccentColor());
DefaultItemAnimator animator = new DefaultItemAnimator();
listView.setItemAnimator(animator);
mToolbarContainer.getViewTreeObserver().addOnGlobalLayoutListener(this);
loadViews();
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();
fragmentManager.executePendingTransactions();
fragmentManager.putFragment(outState, KEY_FRAGMENT_MAIN, this);
}
public void stopAnimation() {
if ((!adapter.stoppedAnimation)) {
for (int j = 0; j < listView.getChildCount(); j++) {
View v = listView.getChildAt(j);
if (v != null) v.clearAnimation();
}
}
adapter.stoppedAnimation = true;
}
void setGridLayoutSpanSizeLookup(GridLayoutManager mLayoutManagerGrid) {
mLayoutManagerGrid.setSpanSizeLookup(
new CustomScrollGridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (adapter.getItemViewType(position)) {
case RecyclerAdapter.TYPE_HEADER_FILES:
case RecyclerAdapter.TYPE_HEADER_FOLDERS:
return (mainFragmentViewModel.getColumns() == 0
|| mainFragmentViewModel.getColumns() == -1)
? 3
: mainFragmentViewModel.getColumns();
default:
return 1;
}
}
});
}
void switchToGrid() {
mainFragmentViewModel.setList(false);
if (utilsProvider.getAppTheme().equals(AppTheme.LIGHT)) {
// will always be grid, set alternate white background
listView.setBackgroundColor(Utils.getColor(getContext(), R.color.grid_background_light));
}
if (mLayoutManagerGrid == null)
if (mainFragmentViewModel.getColumns() == -1 || mainFragmentViewModel.getColumns() == 0)
mLayoutManagerGrid = new CustomScrollGridLayoutManager(getActivity(), 3);
else
mLayoutManagerGrid =
new CustomScrollGridLayoutManager(getActivity(), mainFragmentViewModel.getColumns());
setGridLayoutSpanSizeLookup(mLayoutManagerGrid);
listView.setLayoutManager(mLayoutManagerGrid);
listView.clearOnScrollListeners();
mainFragmentViewModel.setAdapterListItems(null);
mainFragmentViewModel.setIconList(null);
adapter = null;
}
void switchToList() {
mainFragmentViewModel.setList(true);
if (utilsProvider.getAppTheme().equals(AppTheme.LIGHT)) {
listView.setBackgroundDrawable(null);
}
if (mLayoutManager == null) mLayoutManager = new CustomScrollLinearLayoutManager(getActivity());
listView.setLayoutManager(mLayoutManager);
listView.clearOnScrollListeners();
mainFragmentViewModel.setAdapterListItems(null);
mainFragmentViewModel.setIconList(null);
adapter = null;
}
public void switchView() {
boolean isPathLayoutGrid =
DataUtils.getInstance()
.getListOrGridForPath(mainFragmentViewModel.getCurrentPath(), DataUtils.LIST)
== DataUtils.GRID;
reloadListElements(false, isPathLayoutGrid);
}
void loadViews() {
if (!isAdded() || getView() == null) return;
if (mainFragmentViewModel.getCurrentPath() != null) {
if (mainFragmentViewModel.getListElements().size() == 0) {
loadlist(
mainFragmentViewModel.getCurrentPath(),
true,
mainFragmentViewModel.getOpenMode(),
false);
} else {
reloadListElements(true, !mainFragmentViewModel.isList());
}
} else {
loadlist(mainFragmentViewModel.getHome(), true, mainFragmentViewModel.getOpenMode(), false);
}
}
private BroadcastReceiver intentLoadListReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// load the list on a load broadcast
// local file system don't need an explicit load, we've set an observer to
// take actions on creation/moving/deletion/modification of file on current path
if (getCurrentPath() != null) {
mainActivityViewModel.evictPathFromListCache(getCurrentPath());
}
updateList(false);
}
};
private BroadcastReceiver decryptReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (mainFragmentViewModel.isEncryptOpen()
&& mainFragmentViewModel.getEncryptBaseFile() != null) {
FileUtils.openFile(
mainFragmentViewModel.getEncryptBaseFile().getFile(),
requireMainActivity(),
sharedPref);
mainFragmentViewModel.setEncryptOpen(false);
}
}
};
public void home() {
loadlist((mainFragmentViewModel.getHome()), false, OpenMode.FILE, false);
}
/**
* method called when list item is clicked in the adapter
*
* @param isBackButton is it the back button aka '..'
* @param position the position
* @param layoutElementParcelable the list item
* @param imageView the check icon that is to be animated
*/
public void onListItemClicked(
boolean isBackButton,
int position,
LayoutElementParcelable layoutElementParcelable,
AppCompatImageView imageView) {
if (requireMainActivity().getListItemSelected()) {
if (isBackButton) {
requireMainActivity().setListItemSelected(false);
if (requireMainActivity().getActionModeHelper().getActionMode() != null) {
requireMainActivity().getActionModeHelper().getActionMode().finish();
}
requireMainActivity().getActionModeHelper().setActionMode(null);
} else {
// the first {goback} item if back navigation is enabled
registerListItemChecked(position, imageView);
}
} else {
if (isBackButton) {
goBackItemClick();
} else {
// hiding search view if visible
if (requireMainActivity().getAppbar().getSearchView().isEnabled()) {
requireMainActivity().getAppbar().getSearchView().hideSearchView();
}
String path =
!layoutElementParcelable.hasSymlink()
? layoutElementParcelable.desc
: layoutElementParcelable.symlink;
if (layoutElementParcelable.isDirectory) {
if (layoutElementParcelable.getMode() == OpenMode.TRASH_BIN) {
// don't open file hierarchy for trash bin
adapter.toggleChecked(position, imageView);
} else {
computeScroll();
loadlist(path, false, mainFragmentViewModel.getOpenMode(), false);
}
} else if (layoutElementParcelable.desc.endsWith(CryptUtil.CRYPT_EXTENSION)
|| layoutElementParcelable.desc.endsWith(CryptUtil.AESCRYPT_EXTENSION)) {
// decrypt the file
mainFragmentViewModel.setEncryptOpen(true);
mainFragmentViewModel.initEncryptBaseFile(
getActivity().getExternalCacheDir().getPath()
+ "/"
+ layoutElementParcelable
.generateBaseFile()
.getName(getMainActivity())
.replace(CryptUtil.CRYPT_EXTENSION, "")
.replace(CryptUtil.AESCRYPT_EXTENSION, ""));
EncryptDecryptUtils.decryptFile(
requireContext(),
requireMainActivity(),
this,
mainFragmentViewModel.getOpenMode(),
layoutElementParcelable.generateBaseFile(),
getActivity().getExternalCacheDir().getPath(),
utilsProvider,
true);
} else {
if (getMainActivity().mReturnIntent) {
// are we here to return an intent to another app
returnIntentResults(
new HybridFileParcelable[] {layoutElementParcelable.generateBaseFile()});
} else {
layoutElementParcelable.generateBaseFile().openFile(getMainActivity(), false);
DataUtils.getInstance().addHistoryFile(layoutElementParcelable.desc);
}
}
}
}
}
public void registerListItemChecked(int position, AppCompatImageView imageView) {
MainActivity mainActivity = requireMainActivity();
if (mainActivity.mReturnIntent
&& !mainActivity.getIntent().getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)) {
// Only one item should be checked
ArrayList<Integer> checkedItemsIndex = adapter.getCheckedItemsIndex();
if (checkedItemsIndex.contains(position)) {
// The clicked item was the only item checked so it can be unchecked
adapter.toggleChecked(position, imageView);
} else {
// The clicked item was not checked so we have to uncheck all currently checked items
for (Integer index : checkedItemsIndex) {
adapter.toggleChecked(index, imageView);
}
// Now we check the clicked item
adapter.toggleChecked(position, imageView);
}
} else adapter.toggleChecked(position, imageView);
}
public void updateTabWithDb(Tab tab) {
mainFragmentViewModel.setCurrentPath(tab.path);
mainFragmentViewModel.setHome(tab.home);
loadlist(mainFragmentViewModel.getCurrentPath(), false, OpenMode.UNKNOWN, false);
}
/**
* Returns the intent with uri corresponding to specific {@link HybridFileParcelable} back to
* external app
*/
public void returnIntentResults(HybridFileParcelable[] baseFiles) {
requireMainActivity().mReturnIntent = false;
HashMap<HybridFileParcelable, Uri> resultUris = new HashMap<>();
ArrayList<String> failedPaths = new ArrayList<>();
for (HybridFileParcelable baseFile : baseFiles) {
@Nullable Uri resultUri = Utils.getUriForBaseFile(requireActivity(), baseFile);
if (resultUri != null) {
resultUris.put(baseFile, resultUri);
LOG.debug(
resultUri + "\t" + MimeTypes.getMimeType(baseFile.getPath(), baseFile.isDirectory()));
} else {
failedPaths.add(baseFile.getPath());
}
}
if (!resultUris.isEmpty()) {
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (resultUris.size() == 1) {
intent.setAction(Intent.ACTION_SEND);
Map.Entry<HybridFileParcelable, Uri> result = resultUris.entrySet().iterator().next();
Uri resultUri = result.getValue();
HybridFileParcelable resultBaseFile = result.getKey();
if (requireMainActivity().mRingtonePickerIntent) {
// Query MediaStore to get the proper content URI for the selected audio file
Uri mediaFileUri =
MediaStoreHack.getUriForMusicMediaFrom(resultBaseFile.getPath(), requireContext());
if (mediaFileUri != null) {
String filename = resultBaseFile.getName();
Uri properUri =
mediaFileUri
.buildUpon()
.appendQueryParameter("canonical", "1")
.appendQueryParameter(
"title", StringsKt.substringBeforeLast(filename, ".", filename))
.build();
// Set the proper content URI as result
String mimeType = MimeTypes.getMimeType(resultBaseFile.getPath(), false);
intent.setDataAndType(properUri, mimeType);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, properUri);
} else {
Toast.makeText(requireContext(), R.string.error_mediastore_query_uri, Toast.LENGTH_LONG)
.show();
requireActivity().setResult(FragmentActivity.RESULT_CANCELED);
requireActivity().finish();
return;
}
} else {
LOG.debug("pickup file");
intent.setDataAndType(resultUri, MimeTypes.getExtension(resultBaseFile.getPath()));
}
} else {
LOG.debug("pickup multiple files");
// Build ClipData
ArrayList<ClipData.Item> uriDataClipItems = new ArrayList<>();
HashSet<String> mimeTypes = new HashSet<>();
for (Map.Entry<HybridFileParcelable, Uri> result : resultUris.entrySet()) {
HybridFileParcelable baseFile = result.getKey();
Uri uri = result.getValue();
mimeTypes.add(MimeTypes.getMimeType(baseFile.getPath(), baseFile.isDirectory()));
uriDataClipItems.add(new ClipData.Item(uri));
}
ClipData clipData =
new ClipData(
ClipDescription.MIMETYPE_TEXT_URILIST,
mimeTypes.toArray(new String[0]),
uriDataClipItems.remove(0));
for (ClipData.Item item : uriDataClipItems) {
clipData.addItem(item);
}
intent.setClipData(clipData);
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(
Intent.EXTRA_STREAM, new ArrayList<>(resultUris.values()));
}
requireActivity().setResult(FragmentActivity.RESULT_OK, intent);
}
if (!failedPaths.isEmpty()) {
LOG.warn("Unable to get URIs from baseFiles {}", failedPaths);
}
requireActivity().finish();
}
LoadFilesListTask loadFilesListTask;
/**
* This loads a path into the MainFragment.
*
* @param providedPath the path to be loaded
* @param back if we're coming back from any directory and want the scroll to be restored
* @param providedOpenMode the mode in which the directory should be opened
* @param forceReload whether use cached list or force reload the list items
*/
public void loadlist(
final String providedPath,
final boolean back,
final OpenMode providedOpenMode,
boolean forceReload) {
if (mainFragmentViewModel == null) {
LOG.warn("Viewmodel not available to load the data");
return;
}
if (getMainActivity() != null
&& getMainActivity().getActionModeHelper() != null
&& getMainActivity().getActionModeHelper().getActionMode() != null) {
getMainActivity().getActionModeHelper().getActionMode().finish();
}
mSwipeRefreshLayout.setRefreshing(true);
if (loadFilesListTask != null && loadFilesListTask.getStatus() == AsyncTask.Status.RUNNING) {
LOG.warn("Existing load list task running, cancel current");
loadFilesListTask.cancel(true);
}
OpenMode openMode = providedOpenMode;
String actualPath = FileProperties.remapPathForApi30OrAbove(providedPath, false);
if (SDK_INT >= Q && ArraysKt.any(ANDROID_DATA_DIRS, providedPath::contains)) {
openMode = loadPathInQ(actualPath, providedPath, providedOpenMode);
}
// Monkeypatch :( to fix problems with unexpected non content URI path while openMode is still
// OpenMode.DOCUMENT_FILE
else if (actualPath.startsWith("/")
&& (OpenMode.DOCUMENT_FILE.equals(openMode) || OpenMode.ANDROID_DATA.equals(openMode))) {
openMode = OpenMode.FILE;
}
loadFilesListTask =
new LoadFilesListTask(
getActivity(),
actualPath,
this,
openMode,
getBoolean(PREFERENCE_SHOW_THUMB),
getBoolean(PREFERENCE_SHOW_HIDDENFILES),
forceReload,
(data) -> {
mSwipeRefreshLayout.setRefreshing(false);
if (data != null && data.second != null) {
boolean isPathLayoutGrid =
DataUtils.getInstance().getListOrGridForPath(providedPath, DataUtils.LIST)
== DataUtils.GRID;
setListElements(data.second, back, providedPath, data.first, isPathLayoutGrid);
} else {
LOG.warn("Load list operation cancelled");
}
});
loadFilesListTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@RequiresApi(api = Q)
private OpenMode loadPathInQ(String actualPath, String providedPath, OpenMode providedMode) {
if (GenericExtKt.containsPath(ANDROID_DEVICE_DATA_DIRS, providedPath)
&& !OpenMode.ANDROID_DATA.equals(providedMode)) {
return OpenMode.ANDROID_DATA;
} else if (actualPath.startsWith("/")) {
return OpenMode.FILE;
} else if (actualPath.equals(providedPath)) {
return providedMode;
} else {
boolean hasAccessToSpecialFolder = false;
List<UriPermission> uriPermissions =
requireContext().getContentResolver().getPersistedUriPermissions();
if (uriPermissions != null && uriPermissions.size() > 0) {
for (UriPermission p : uriPermissions) {
if (p.isReadPermission() && actualPath.startsWith(p.getUri().toString())) {
hasAccessToSpecialFolder = true;
SafRootHolder.setUriRoot(p.getUri());
break;
}
}
}
if (!hasAccessToSpecialFolder) {
Intent intent =
new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
.putExtra(
DocumentsContract.EXTRA_INITIAL_URI,
Uri.parse(FileProperties.remapPathForApi30OrAbove(providedPath, true)));
MaterialDialog d =
GeneralDialogCreation.showBasicDialog(
requireMainActivity(),
R.string.android_data_prompt_saf_access,
R.string.android_data_prompt_saf_access_title,
android.R.string.ok,
android.R.string.cancel);
d.getActionButton(DialogAction.POSITIVE)
.setOnClickListener(
v -> {
ExtensionsKt.runIfDocumentsUIExists(
intent,
requireMainActivity(),
() -> handleDocumentUriForRestrictedDirectories.launch(intent));
d.dismiss();
});
d.show();
// At this point LoadFilesListTask will be triggered.
// No harm even give OpenMode.FILE here, it loads blank when it doesn't; and after the
// UriPermission is granted loadlist will be called again
return OpenMode.FILE;
} else {
return OpenMode.DOCUMENT_FILE;
}
}
}
void initNoFileLayout() {
nofilesview = rootView.findViewById(R.id.nofilelayout);
nofilesview.setColorSchemeColors(mainFragmentViewModel.getAccentColor());
nofilesview.setOnRefreshListener(
() -> {
loadlist(
(mainFragmentViewModel.getCurrentPath()),
false,
mainFragmentViewModel.getOpenMode(),
false);
nofilesview.setRefreshing(false);
});
nofilesview
.findViewById(R.id.no_files_relative)
.setOnKeyListener(
(v, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
requireMainActivity().getFAB().requestFocus();
} else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
requireMainActivity().onBackPressed();
} else {
return false;
}
}
return true;
});
if (utilsProvider.getAppTheme().equals(AppTheme.LIGHT)) {
((AppCompatImageView) nofilesview.findViewById(R.id.image))
.setColorFilter(Color.parseColor("#666666"));
} else if (utilsProvider.getAppTheme().equals(AppTheme.BLACK)) {
nofilesview.setBackgroundColor(Utils.getColor(getContext(), android.R.color.black));
((AppCompatTextView) nofilesview.findViewById(R.id.nofiletext)).setTextColor(Color.WHITE);
} else {
nofilesview.setBackgroundColor(Utils.getColor(getContext(), R.color.holo_dark_background));
((AppCompatTextView) nofilesview.findViewById(R.id.nofiletext)).setTextColor(Color.WHITE);
}
}
/**
* Loading adapter after getting a list of elements
*
* @param bitmap the list of objects for the adapter
* @param back if we're coming back from any directory and want the scroll to be restored
* @param path the path for the adapter
* @param openMode the type of file being created
* @param results is the list of elements a result from search
* @param grid whether to set grid view or list view
*/
public void setListElements(
List<LayoutElementParcelable> bitmap,
boolean back,
String path,
final OpenMode openMode,
boolean grid) {
if (bitmap != null) {
mainFragmentViewModel.setListElements(bitmap);
mainFragmentViewModel.setCurrentPath(path);
mainFragmentViewModel.setOpenMode(openMode);
reloadListElements(back, grid);
} else {
// list loading cancelled
// TODO: Add support for cancelling list loading
loadlist(mainFragmentViewModel.getHome(), true, OpenMode.FILE, false);
}
}
public void reloadListElements(boolean back, boolean grid) {
if (!isAdded() || getView() == null) return;
if (listView != null) {
listView.removeCallbacks(null);
}
// Initialize views if they're null
if (mSwipeRefreshLayout == null || listView == null) {
initViews();
if (mSwipeRefreshLayout == null || listView == null) {
LOG.warn("Failed to initialize views in reloadListElements");
return;
}
}
if (mainFragmentViewModel.getListElements().size() == 0) {
if (nofilesview != null) nofilesview.setVisibility(View.VISIBLE);
if (listView != null) listView.setVisibility(View.GONE);
if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setEnabled(false);
} else {
if (nofilesview != null) nofilesview.setVisibility(View.GONE);
if (listView != null) listView.setVisibility(View.VISIBLE);
if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setEnabled(true);
}
boolean isOtg = (OTGUtil.PREFIX_OTG + "/").equals(mainFragmentViewModel.getCurrentPath());
if (getBoolean(PREFERENCE_SHOW_GOBACK_BUTTON)
&& !"/".equals(mainFragmentViewModel.getCurrentPath())
&& (mainFragmentViewModel.getOpenMode() == OpenMode.FILE
|| mainFragmentViewModel.getOpenMode() == OpenMode.ROOT
|| (mainFragmentViewModel.getIsCloudOpenMode()
&& !mainFragmentViewModel.getIsOnCloudRoot()))
&& !isOtg
&& (mainFragmentViewModel.getListElements().size() == 0
|| !mainFragmentViewModel
.getListElements()
.get(0)
.size
.equals(getString(R.string.goback)))) {
mainFragmentViewModel.getListElements().add(0, getBackElement());
}
if (grid && mainFragmentViewModel.isList()) {
switchToGrid();
} else if (!grid && !mainFragmentViewModel.isList()) {
switchToList();
}
if (adapter == null) {
final List<LayoutElementParcelable> listElements = mainFragmentViewModel.getListElements();
adapter =
new RecyclerAdapter(
requireMainActivity(),
this,
utilsProvider,
sharedPref,
listView,
listElements,
requireContext(),
grid);
} else {
adapter.setItems(listView, mainFragmentViewModel.getListElements());
}
mainFragmentViewModel.setStopAnims(true);
if (mainFragmentViewModel.getOpenMode() != OpenMode.CUSTOM
&& mainFragmentViewModel.getOpenMode() != OpenMode.TRASH_BIN) {
DataUtils.getInstance().addHistoryFile(mainFragmentViewModel.getCurrentPath());
}
listView.setAdapter(adapter);
if (!mainFragmentViewModel.getAddHeader()) {
listView.removeItemDecoration(dividerItemDecoration);
mainFragmentViewModel.setAddHeader(true);
}
if (mainFragmentViewModel.getAddHeader() && mainFragmentViewModel.isList()) {
dividerItemDecoration =
new DividerItemDecoration(
requireMainActivity(), true, getBoolean(PREFERENCE_SHOW_DIVIDERS));
listView.addItemDecoration(dividerItemDecoration);
mainFragmentViewModel.setAddHeader(false);
}
if (back && scrolls.containsKey(mainFragmentViewModel.getCurrentPath())) {
Bundle b = scrolls.get(mainFragmentViewModel.getCurrentPath());
int index = b.getInt("index"), top = b.getInt("top");
if (mainFragmentViewModel.isList()) {
mLayoutManager.scrollToPositionWithOffset(index, top);
} else {
mLayoutManagerGrid.scrollToPositionWithOffset(index, top);
}
}
requireMainActivity().updatePaths(mainFragmentViewModel.getNo());
requireMainActivity().showFab();
requireMainActivity().getAppbar().getAppbarLayout().setExpanded(true);
listView.stopScroll();
fastScroller.setRecyclerView(
listView,
mainFragmentViewModel.isList()
? 1
: (mainFragmentViewModel.getColumns() == 0 || mainFragmentViewModel.getColumns() == -1)
? 3
: mainFragmentViewModel.getColumns());
mToolbarContainer.addOnOffsetChangedListener(
(appBarLayout, verticalOffset) -> {
fastScroller.updateHandlePosition(verticalOffset, 112);
});
fastScroller.registerOnTouchListener(
() -> {
if (mainFragmentViewModel.getStopAnims() && adapter != null) {
stopAnimation();
mainFragmentViewModel.setStopAnims(false);
}
});
startFileObserver();
listView.post(
() -> {
if (!isAdded()) return;
String fileName = requireMainActivity().getScrollToFileName();
if (fileName != null)
mainFragmentViewModel
.getScrollPosition(fileName)
.observe(
getViewLifecycleOwner(),
scrollPosition -> {
if (scrollPosition != -1)
listView.scrollToPosition(
Math.min(scrollPosition + 4, adapter.getItemCount() - 1));
adapter.notifyItemChanged(scrollPosition);
});
});
}
private LayoutElementParcelable getBackElement() {
if (mainFragmentViewModel.getBack() == null) {
mainFragmentViewModel.setBack(
new LayoutElementParcelable(
requireContext(),
true,
getString(R.string.goback),
getBoolean(PREFERENCE_SHOW_THUMB)));
}
return mainFragmentViewModel.getBack();
}
/**
* Method will resume any decryption tasks like registering decryption receiver or deleting any
* pending opened files in application cache
*/
private void resumeDecryptOperations() {
if (SDK_INT >= JELLY_BEAN_MR2) {
ContextCompatExtKt.registerReceiverCompat(