-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathMainActivity.java
More file actions
2582 lines (2340 loc) · 99.6 KB
/
MainActivity.java
File metadata and controls
2582 lines (2340 loc) · 99.6 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.activities;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.KITKAT;
import static android.os.Build.VERSION_CODES.KITKAT_WATCH;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.N;
import static com.amaze.filemanager.fileoperations.filesystem.FolderStateKt.WRITABLE_OR_ON_SDCARD;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.COMPRESS;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.COPY;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.DELETE;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.EXTRACT;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.MOVE;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.NEW_FILE;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.NEW_FOLDER;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.RENAME;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.SAVE_FILE;
import static com.amaze.filemanager.fileoperations.filesystem.OperationTypeKt.UNDEFINED;
import static com.amaze.filemanager.filesystem.ftp.FTPClientImpl.ARG_TLS;
import static com.amaze.filemanager.filesystem.ftp.FTPClientImpl.TLS_EXPLICIT;
import static com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTPS_URI_PREFIX;
import static com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTP_URI_PREFIX;
import static com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.SSH_URI_PREFIX;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_ADDRESS;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_DEFAULT_PATH;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_EDIT;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_HAS_PASSWORD;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_KEYPAIR_NAME;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_NAME;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_PASSWORD;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_PORT;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_PROTOCOL;
import static com.amaze.filemanager.ui.dialogs.SftpConnectDialog.ARG_USERNAME;
import static com.amaze.filemanager.ui.fragments.FtpServerFragment.REQUEST_CODE_SAF_FTP;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_BOOKMARKS_ADDED;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_COLORED_NAVIGATION;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_NEED_TO_SET_HOME;
import static com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_VIEW;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.folderselector.FolderChooserDialog;
import com.amaze.filemanager.BuildConfig;
import com.amaze.filemanager.LogHelper;
import com.amaze.filemanager.R;
import com.amaze.filemanager.adapters.data.LayoutElementParcelable;
import com.amaze.filemanager.adapters.data.StorageDirectoryParcelable;
import com.amaze.filemanager.application.AppConfig;
import com.amaze.filemanager.asynchronous.SaveOnDataUtilsChange;
import com.amaze.filemanager.asynchronous.asynctasks.CloudLoaderAsyncTask;
import com.amaze.filemanager.asynchronous.asynctasks.DeleteTask;
import com.amaze.filemanager.asynchronous.asynctasks.TaskKt;
import com.amaze.filemanager.asynchronous.asynctasks.movecopy.MoveFilesTask;
import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil;
import com.amaze.filemanager.asynchronous.services.CopyService;
import com.amaze.filemanager.database.CloudContract;
import com.amaze.filemanager.database.CloudHandler;
import com.amaze.filemanager.database.SortHandler;
import com.amaze.filemanager.database.TabHandler;
import com.amaze.filemanager.database.UtilsHandler;
import com.amaze.filemanager.database.models.OperationData;
import com.amaze.filemanager.database.models.explorer.CloudEntry;
import com.amaze.filemanager.fileoperations.exceptions.CloudPluginException;
import com.amaze.filemanager.fileoperations.filesystem.OpenMode;
import com.amaze.filemanager.fileoperations.filesystem.StorageNaming;
import com.amaze.filemanager.fileoperations.filesystem.usb.SingletonUsbOtg;
import com.amaze.filemanager.fileoperations.filesystem.usb.UsbOtgRepresentation;
import com.amaze.filemanager.filesystem.ExternalSdCardOperation;
import com.amaze.filemanager.filesystem.FileUtil;
import com.amaze.filemanager.filesystem.HybridFile;
import com.amaze.filemanager.filesystem.HybridFileParcelable;
import com.amaze.filemanager.filesystem.MakeFileOperation;
import com.amaze.filemanager.filesystem.PasteHelper;
import com.amaze.filemanager.filesystem.RootHelper;
import com.amaze.filemanager.filesystem.files.FileUtils;
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool;
import com.amaze.filemanager.filesystem.ftp.NetCopyConnectionInfo;
import com.amaze.filemanager.filesystem.ssh.SshClientUtils;
import com.amaze.filemanager.ui.ExtensionsKt;
import com.amaze.filemanager.ui.activities.superclasses.PermissionsActivity;
import com.amaze.filemanager.ui.dialogs.AlertDialog;
import com.amaze.filemanager.ui.dialogs.GeneralDialogCreation;
import com.amaze.filemanager.ui.dialogs.HiddenFilesDialog;
import com.amaze.filemanager.ui.dialogs.HistoryDialog;
import com.amaze.filemanager.ui.dialogs.RenameBookmark;
import com.amaze.filemanager.ui.dialogs.RenameBookmark.BookmarkCallback;
import com.amaze.filemanager.ui.dialogs.SftpConnectDialog;
import com.amaze.filemanager.ui.dialogs.SmbConnectDialog;
import com.amaze.filemanager.ui.dialogs.SmbConnectDialog.SmbConnectionListener;
import com.amaze.filemanager.ui.drag.TabFragmentBottomDragListener;
import com.amaze.filemanager.ui.fragments.AppsListFragment;
import com.amaze.filemanager.ui.fragments.CloudSheetFragment;
import com.amaze.filemanager.ui.fragments.CloudSheetFragment.CloudConnectionCallbacks;
import com.amaze.filemanager.ui.fragments.CompressedExplorerFragment;
import com.amaze.filemanager.ui.fragments.FtpServerFragment;
import com.amaze.filemanager.ui.fragments.MainFragment;
import com.amaze.filemanager.ui.fragments.ProcessViewerFragment;
import com.amaze.filemanager.ui.fragments.TabFragment;
import com.amaze.filemanager.ui.fragments.data.MainFragmentViewModel;
import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants;
import com.amaze.filemanager.ui.strings.StorageNamingHelper;
import com.amaze.filemanager.ui.theme.AppTheme;
import com.amaze.filemanager.ui.views.CustomZoomFocusChange;
import com.amaze.filemanager.ui.views.appbar.AppBar;
import com.amaze.filemanager.ui.views.drawer.Drawer;
import com.amaze.filemanager.utils.AppConstants;
import com.amaze.filemanager.utils.BookSorter;
import com.amaze.filemanager.utils.ContextCompatExtKt;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.GenericExtKt;
import com.amaze.filemanager.utils.MainActivityActionMode;
import com.amaze.filemanager.utils.MainActivityHelper;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.PackageUtils;
import com.amaze.filemanager.utils.PreferenceUtils;
import com.amaze.filemanager.utils.Utils;
import com.cloudrail.si.CloudRail;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import com.leinardi.android.speeddial.FabWithLabelView;
import com.leinardi.android.speeddial.SpeedDialActionItem;
import com.leinardi.android.speeddial.SpeedDialOverlayLayout;
import com.leinardi.android.speeddial.SpeedDialView;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.topjohnwu.superuser.Shell;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.usb.UsbManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.service.quicksettings.TileService;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Toast;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;
import androidx.arch.core.util.Function;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import io.reactivex.Completable;
import io.reactivex.CompletableObserver;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kotlin.collections.ArraysKt;
import kotlin.jvm.functions.Function1;
import kotlin.text.Charsets;
public class MainActivity extends PermissionsActivity
implements SmbConnectionListener,
BookmarkCallback,
CloudConnectionCallbacks,
LoaderManager.LoaderCallbacks<Cursor>,
FolderChooserDialog.FolderCallback,
PermissionsActivity.OnPermissionGranted {
private static final Logger LOG = LoggerFactory.getLogger(MainActivity.class);
public static final Pattern DIR_SEPARATOR = Pattern.compile("/");
public static final String TAG_ASYNC_HELPER = "async_helper";
private DataUtils dataUtils;
public String path = "";
public boolean mReturnIntent = false;
public boolean isCompressedOpen = false;
public boolean mRingtonePickerIntent = false;
public int skinStatusBar;
private SpeedDialView floatingActionButton;
private SpeedDialView fabConfirmSelection;
public MainActivityHelper mainActivityHelper;
public int operation = -1;
public ArrayList<HybridFileParcelable> oparrayList;
public ArrayList<ArrayList<HybridFileParcelable>> oparrayListList;
// oppathe - the path at which certain operation needs to be performed
// oppathe1 - the new path which user wants to create/modify
// oppathList - the paths at which certain operation needs to be performed (pairs with
// oparrayList)
public String oppathe, oppathe1;
public ArrayList<String> oppatheList;
// This holds the Uris to be written at initFabToSave()
private List<Uri> urisToBeSaved;
public static final String PASTEHELPER_BUNDLE = "pasteHelper";
private static final String KEY_DRAWER_SELECTED = "selectitem";
private static final String KEY_OPERATION_PATH = "oppathe";
private static final String KEY_OPERATED_ON_PATH = "oppathe1";
private static final String KEY_OPERATIONS_PATH_LIST = "oparraylist";
private static final String KEY_OPERATION = "operation";
private static final String KEY_SELECTED_LIST_ITEM = "select_list_item";
private AppBar appbar;
private Drawer drawer;
// private HistoryManager history, grid;
private MainActivity mainActivity = this;
private String pathInCompressedArchive;
private boolean openProcesses = false;
private MaterialDialog materialDialog;
private boolean backPressedToExitOnce = false;
private WeakReference<Toast> toast = new WeakReference<>(null);
private Intent intent;
private View indicator_layout;
private AppBarLayout appBarLayout;
private SpeedDialOverlayLayout fabBgView;
private UtilsHandler utilsHandler;
private CloudHandler cloudHandler;
private CloudLoaderAsyncTask cloudLoaderAsyncTask;
/**
* This is for a hack.
*
* @see MainActivity#onLoadFinished(Loader, Cursor)
*/
private Cursor cloudCursorData = null;
public static final int REQUEST_CODE_SAF = 223;
public static final String KEY_INTENT_PROCESS_VIEWER = "openprocesses";
public static final String TAG_INTENT_FILTER_FAILED_OPS = "failedOps";
public static final String TAG_INTENT_FILTER_GENERAL = "general_communications";
public static final String ARGS_KEY_LOADER = "loader_cloud_args_service";
/**
* Broadcast which will be fired after every file operation, will denote list loading Registered
* by {@link MainFragment}
*/
public static final String KEY_INTENT_LOAD_LIST = "loadlist";
/**
* Extras carried by the list loading intent Contains path of parent directory in which operation
* took place, so that we can run media scanner on it
*/
public static final String KEY_INTENT_LOAD_LIST_FILE = "loadlist_file";
/**
* Mime type in intent that apps need to pass when trying to open file manager from a specific
* directory Should be clubbed with {@link Intent#ACTION_VIEW} and send in path to open in intent
* data field
*/
public static final String ARGS_INTENT_ACTION_VIEW_MIME_FOLDER = "resource/folder";
public static final String ARGS_INTENT_ACTION_VIEW_APPLICATION_ALL = "application/*";
public static final String CLOUD_AUTHENTICATOR_GDRIVE = "android.intent.category.BROWSABLE";
public static final String CLOUD_AUTHENTICATOR_REDIRECT_URI = "com.amaze.filemanager:/auth";
// the current visible tab, either 0 or 1
public static int currentTab;
private boolean listItemSelected = false;
private String scrollToFileName = null;
public static final int REQUEST_CODE_CLOUD_LIST_KEYS = 5463;
public static final int REQUEST_CODE_CLOUD_LIST_KEY = 5472;
private PasteHelper pasteHelper;
public MainActivityActionMode mainActivityActionMode;
private static final String DEFAULT_FALLBACK_STORAGE_PATH = "/storage/sdcard0";
private static final String INTERNAL_SHARED_STORAGE = "Internal shared storage";
private static final String INTENT_ACTION_OPEN_QUICK_ACCESS =
"com.amaze.filemanager.openQuickAccess";
private static final String INTENT_ACTION_OPEN_RECENT = "com.amaze.filemanager.openRecent";
private static final String INTENT_ACTION_OPEN_FTP_SERVER = "com.amaze.filemanager.openFTPServer";
private static final String INTENT_ACTION_OPEN_APP_MANAGER =
"com.amaze.filemanager.openAppManager";
/** Called when the activity is first created. */
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_toolbar);
intent = getIntent();
dataUtils = DataUtils.getInstance();
if (savedInstanceState != null) {
listItemSelected = savedInstanceState.getBoolean(KEY_SELECTED_LIST_ITEM, false);
}
initialisePreferences();
initializeInteractiveShell();
dataUtils.registerOnDataChangedListener(new SaveOnDataUtilsChange(drawer));
AppConfig.getInstance().setMainActivityContext(this);
initialiseViews();
utilsHandler = AppConfig.getInstance().getUtilsHandler();
cloudHandler = new CloudHandler(this, AppConfig.getInstance().getExplorerDatabase());
initialiseFab(); // TODO: 7/12/2017 not init when actionIntent != null
mainActivityHelper = new MainActivityHelper(this);
mainActivityActionMode = new MainActivityActionMode(new WeakReference<>(MainActivity.this));
if (CloudSheetFragment.isCloudProviderAvailable(this)) {
try {
LoaderManager.getInstance(this).initLoader(REQUEST_CODE_CLOUD_LIST_KEYS, null, this);
} catch (Exception errorRaised) {
LOG.error("Error initializing cloud connections", errorRaised);
cloudHandler.clearAllCloudConnections();
AlertDialog.show(
this,
R.string.cloud_connection_credentials_cleared_msg,
R.string.cloud_connection_credentials_cleared,
android.R.string.ok,
null,
false);
LoaderManager.getInstance(this).initLoader(REQUEST_CODE_CLOUD_LIST_KEYS, null, this);
}
}
path = intent.getStringExtra("path");
openProcesses = intent.getBooleanExtra(KEY_INTENT_PROCESS_VIEWER, false);
if (intent.getStringArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS) != null) {
ArrayList<HybridFileParcelable> failedOps =
intent.getParcelableArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS);
if (failedOps != null) {
mainActivityHelper.showFailedOperationDialog(failedOps, this);
}
}
checkForExternalIntent(intent);
initialiseFabConfirmSelection();
drawer.setDrawerIndicatorEnabled();
if (!getBoolean(PREFERENCE_BOOKMARKS_ADDED)) {
utilsHandler.addCommonBookmarks();
getPrefs().edit().putBoolean(PREFERENCE_BOOKMARKS_ADDED, true).commit();
}
checkForExternalPermission();
Completable.fromRunnable(
() -> {
dataUtils.setHiddenFiles(utilsHandler.getHiddenFilesConcurrentRadixTree());
dataUtils.setHistory(utilsHandler.getHistoryLinkedList());
dataUtils.setGridfiles(utilsHandler.getGridViewList());
dataUtils.setListfiles(utilsHandler.getListViewList());
dataUtils.setBooks(utilsHandler.getBookmarksList());
ArrayList<String[]> servers = new ArrayList<>();
servers.addAll(utilsHandler.getSmbList());
servers.addAll(utilsHandler.getSftpList());
dataUtils.setServers(servers);
ExtensionsKt.updateAUAlias(
this,
!PackageUtils.Companion.appInstalledOrNot(
AboutActivity.PACKAGE_AMAZE_UTILS, mainActivity.getPackageManager())
&& !getBoolean(
PreferencesConstants.PREFERENCE_DISABLE_PLAYER_INTENT_FILTERS));
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
new CompletableObserver() {
@Override
public void onSubscribe(@NonNull Disposable d) {}
@Override
public void onComplete() {
drawer.refreshDrawer();
invalidateFragmentAndBundle(savedInstanceState, false);
}
@Override
public void onError(@NonNull Throwable e) {
LOG.error("Error setting up DataUtils", e);
drawer.refreshDrawer();
invalidateFragmentAndBundle(savedInstanceState, false);
}
});
initStatusBarResources(findViewById(R.id.drawer_layout));
}
public void invalidateFragmentAndBundle(Bundle savedInstanceState, boolean isCloudRefresh) {
if (savedInstanceState == null) {
if (openProcesses) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(
R.id.content_frame, new ProcessViewerFragment(), KEY_INTENT_PROCESS_VIEWER);
// transaction.addToBackStack(null);
openProcesses = false;
// title.setText(utils.getString(con, R.string.process_viewer));
// Commit the transaction
transaction.commit();
supportInvalidateOptionsMenu();
} else if (intent.getAction() != null
&& (intent.getAction().equals(TileService.ACTION_QS_TILE_PREFERENCES)
|| INTENT_ACTION_OPEN_FTP_SERVER.equals(intent.getAction()))) {
// tile preferences, open ftp fragment
FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
transaction2.replace(R.id.content_frame, new FtpServerFragment());
appBarLayout
.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator(2))
.start();
drawer.deselectEverything();
transaction2.commit();
} else if (intent.getAction() != null
&& INTENT_ACTION_OPEN_APP_MANAGER.equals(intent.getAction())) {
FragmentTransaction transaction3 = getSupportFragmentManager().beginTransaction();
transaction3.replace(R.id.content_frame, new AppsListFragment());
appBarLayout
.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator(2))
.start();
drawer.deselectEverything();
transaction3.commit();
} else {
if (path != null && path.length() > 0) {
HybridFile file = new HybridFile(OpenMode.UNKNOWN, path);
file.generateMode(MainActivity.this);
if (file.isCloudDriveFile() && dataUtils.getAccounts().size() == 0) {
// not ready to serve cloud files
goToMain(null);
} else if (file.isDirectory(MainActivity.this) && !isCloudRefresh) {
goToMain(path);
} else {
if (!isCloudRefresh) {
goToMain(null);
}
if (file.isSmb() || file.isSftp()) {
String authorisedPath =
SshClientUtils.formatPlainServerPathToAuthorised(dataUtils.getServers(), path);
file.setPath(authorisedPath);
LOG.info(
"Opening smb file from deeplink, modify plain path to authorised path {}",
authorisedPath);
}
file.openFile(this, true);
}
} else if (!isCloudRefresh) {
goToMain(null);
}
}
} else {
pasteHelper = savedInstanceState.getParcelable(PASTEHELPER_BUNDLE);
oppathe = savedInstanceState.getString(KEY_OPERATION_PATH);
oppathe1 = savedInstanceState.getString(KEY_OPERATED_ON_PATH);
oparrayList = savedInstanceState.getParcelableArrayList(KEY_OPERATIONS_PATH_LIST);
operation = savedInstanceState.getInt(KEY_OPERATION);
int selectedStorage = savedInstanceState.getInt(KEY_DRAWER_SELECTED, 0);
getDrawer().selectCorrectDrawerItem(selectedStorage);
}
}
@Override
@SuppressLint("CheckResult")
public void onPermissionGranted() {
drawer.refreshDrawer();
TabFragment tabFragment = getTabFragment();
boolean b = getBoolean(PREFERENCE_NEED_TO_SET_HOME);
// reset home and current paths according to new storages
if (b) {
TabHandler tabHandler = TabHandler.getInstance();
tabHandler
.clear()
.subscribe(
() -> {
if (tabFragment != null) {
tabFragment.refactorDrawerStorages(false, false);
Fragment main = tabFragment.getFragmentAtIndex(0);
if (main != null) ((MainFragment) main).updateTabWithDb(tabHandler.findTab(1));
Fragment main1 = tabFragment.getFragmentAtIndex(1);
if (main1 != null) ((MainFragment) main1).updateTabWithDb(tabHandler.findTab(2));
}
getPrefs().edit().putBoolean(PREFERENCE_NEED_TO_SET_HOME, false).commit();
});
} else {
// just refresh list
if (tabFragment != null) {
Fragment main = tabFragment.getFragmentAtIndex(0);
if (main != null) ((MainFragment) main).updateList(false);
Fragment main1 = tabFragment.getFragmentAtIndex(1);
if (main1 != null) ((MainFragment) main1).updateList(false);
}
}
}
private void checkForExternalPermission() {
if (SDK_INT >= Build.VERSION_CODES.M) {
if (!checkStoragePermission()) {
if (SDK_INT >= Build.VERSION_CODES.R) {
requestAllFilesAccess(this);
} else {
requestStoragePermission(this, true);
}
}
if (SDK_INT >= Build.VERSION_CODES.TIRAMISU && !checkNotificationPermission()) {
requestNotificationPermission(true);
}
}
}
/** Checks for the action to take when Amaze receives an intent from external source */
private void checkForExternalIntent(Intent intent) {
final String actionIntent = intent.getAction();
if (actionIntent == null) {
return;
}
final String type = intent.getType();
if (actionIntent.equals(Intent.ACTION_GET_CONTENT)) {
// file picker intent
mReturnIntent = true;
String text =
intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
? getString(R.string.pick_files)
: getString(R.string.pick_a_file);
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
// disable screen rotation just for convenience purpose
// TODO: Support screen rotation when picking file
Utils.disableScreenRotation(this);
} else if (actionIntent.equals(RingtoneManager.ACTION_RINGTONE_PICKER)) {
// ringtone picker intent
mReturnIntent = true;
mRingtonePickerIntent = true;
Toast.makeText(this, getString(R.string.pick_a_file), Toast.LENGTH_LONG).show();
// disable screen rotation just for convenience purpose
// TODO: Support screen rotation when picking file
Utils.disableScreenRotation(this);
} else if (actionIntent.equals(Intent.ACTION_VIEW)) {
// zip viewer intent
Uri uri = intent.getData();
if (type != null
&& (type.equals(ARGS_INTENT_ACTION_VIEW_MIME_FOLDER)
|| type.equals(ARGS_INTENT_ACTION_VIEW_APPLICATION_ALL))) {
// support for syncting or intents from external apps that
// need to start file manager from a specific path
if (uri != null) {
path = Utils.sanitizeInput(FileUtils.fromContentUri(uri).getAbsolutePath());
scrollToFileName = intent.getStringExtra("com.amaze.fileutilities.AFM_LOCATE_FILE_NAME");
} else {
// no data field, open home for the tab in later processing
path = null;
}
} else if (FileUtils.isCompressedFile(Utils.sanitizeInput(uri.toString()))) {
// we don't have folder resource mime type set, supposed to be zip/rar
isCompressedOpen = true;
pathInCompressedArchive = Utils.sanitizeInput(uri.toString());
openCompressed(pathInCompressedArchive);
} else if (uri.getPath().startsWith("/open_file")) {
/**
* Deeplink to open files directly through amaze using following format:
* http://teamamaze.xyz/open_file?path=path-to-file
*/
path = Utils.sanitizeInput(uri.getQueryParameter("path"));
} else if (uri != null && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
// save a single file to filesystem
List<Uri> uris = new ArrayList<>();
uris.add(uri);
showSaveSnackbar(uris);
// disable screen rotation just for convenience purpose
// TODO: Support screen rotation when saving a file
Utils.disableScreenRotation(this);
} else {
LOG.warn(getString(R.string.error_cannot_find_way_open));
}
} else if (actionIntent.equals(Intent.ACTION_SEND)) {
if ("text/plain".equals(type)) {
showSaveSnackbar(null);
} else {
// save a single file to filesystem
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null && uri.getScheme() != null) {
List<Uri> uris = new ArrayList<>();
uris.add(uri);
showSaveSnackbar(uris);
} else {
Toast.makeText(this, R.string.error_unsupported_or_null_uri, Toast.LENGTH_LONG).show();
}
}
// disable screen rotation just for convenience purpose
// TODO: Support screen rotation when saving a file
Utils.disableScreenRotation(this);
} else if (actionIntent.equals(Intent.ACTION_SEND_MULTIPLE) && type != null) {
// save multiple files to filesystem
ArrayList<Uri> arrayList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
showSaveSnackbar(arrayList);
// disable screen rotation just for convenience purpose
// TODO: Support screen rotation when saving a file
Utils.disableScreenRotation(this);
}
}
/** Initializes the floating action button to act as to save data from an external intent */
private void showSaveSnackbar(final List<Uri> uris) {
Utils.showThemedSnackbar(
this,
getString(R.string.select_save_location),
BaseTransientBottomBar.LENGTH_INDEFINITE,
R.string.save,
() -> saveExternalIntent(uris));
}
private void saveExternalIntent(final List<Uri> uris) {
executeWithMainFragment(
mainFragment -> {
if (uris != null && uris.size() > 0) {
if (SDK_INT >= LOLLIPOP) {
File folder = new File(mainFragment.getCurrentPath());
int result = mainActivityHelper.checkFolder(folder, MainActivity.this);
if (result == WRITABLE_OR_ON_SDCARD) {
FileUtil.writeUriToStorage(
MainActivity.this, uris, getContentResolver(), mainFragment.getCurrentPath());
finish();
} else {
// Trigger SAF intent, keep uri until finish
operation = SAVE_FILE;
urisToBeSaved = uris;
mainActivityHelper.checkFolder(folder, MainActivity.this);
}
} else {
FileUtil.writeUriToStorage(
MainActivity.this, uris, getContentResolver(), mainFragment.getCurrentPath());
}
} else {
saveExternalIntentExtras();
}
Toast.makeText(
MainActivity.this,
getResources().getString(R.string.saving)
+ " to "
+ mainFragment.getCurrentPath(),
Toast.LENGTH_LONG)
.show();
finish();
return null;
});
}
private void saveExternalIntentExtras() {
executeWithMainFragment(
mainFragment -> {
Bundle extras = intent.getExtras();
StringBuilder data = new StringBuilder();
if (!Utils.isNullOrEmpty(extras.getString(Intent.EXTRA_SUBJECT))) {
data.append(extras.getString(Intent.EXTRA_SUBJECT));
}
if (!Utils.isNullOrEmpty(extras.getString(Intent.EXTRA_TEXT))) {
data.append(AppConstants.NEW_LINE).append(extras.getString(Intent.EXTRA_TEXT));
}
String fileName = Long.toString(System.currentTimeMillis());
AppConfig.getInstance()
.runInBackground(
() ->
MakeFileOperation.mktextfile(
data.toString(), mainFragment.getCurrentPath(), fileName));
return null;
});
}
public void clearFabActionItems() {
floatingActionButton.removeActionItemById(R.id.menu_new_folder);
floatingActionButton.removeActionItemById(R.id.menu_new_file);
floatingActionButton.removeActionItemById(R.id.menu_new_cloud);
}
/** Initializes an interactive shell, which will stay throughout the app lifecycle. */
private void initializeInteractiveShell() {
if (isRootExplorer()) {
// Enable mount-master flag when invoking su command, to force su run in the global mount
// namespace. See https://github.com/topjohnwu/libsu/issues/75
Shell.setDefaultBuilder(Shell.Builder.create().setFlags(Shell.FLAG_MOUNT_MASTER));
Shell.getShell();
}
}
/**
* @return paths to all available volumes in the system (include emulated)
*/
public synchronized ArrayList<StorageDirectoryParcelable> getStorageDirectories() {
ArrayList<StorageDirectoryParcelable> volumes;
if (SDK_INT >= N) {
volumes = getStorageDirectoriesNew();
} else {
volumes = getStorageDirectoriesLegacy();
}
if (isRootExplorer()) {
volumes.add(
new StorageDirectoryParcelable(
"/",
getResources().getString(R.string.root_directory),
R.drawable.ic_drawer_root_white));
}
return volumes;
}
/**
* @return All available storage volumes (including internal storage, SD-Cards and USB devices)
*/
@TargetApi(N)
public synchronized ArrayList<StorageDirectoryParcelable> getStorageDirectoriesNew() {
// Final set of paths
ArrayList<StorageDirectoryParcelable> volumes = new ArrayList<>();
StorageManager sm = getSystemService(StorageManager.class);
for (StorageVolume volume : sm.getStorageVolumes()) {
if (!volume.getState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)
&& !volume.getState().equalsIgnoreCase(Environment.MEDIA_MOUNTED_READ_ONLY)) {
continue;
}
File path = Utils.getVolumeDirectory(volume);
String name = volume.getDescription(this);
if (INTERNAL_SHARED_STORAGE.equalsIgnoreCase(name)) {
name = getString(R.string.storage_internal);
}
int icon;
if (!volume.isRemovable()) {
icon = R.drawable.ic_phone_android_white_24dp;
} else {
// HACK: There is no reliable way to distinguish USB and SD external storage
// However it is often enough to check for "USB" String
if (name.toUpperCase().contains("USB") || path.getPath().toUpperCase().contains("USB")) {
icon = R.drawable.ic_usb_white_24dp;
} else {
icon = R.drawable.ic_sd_storage_white_24dp;
}
}
volumes.add(new StorageDirectoryParcelable(path.getPath(), name, icon));
}
return volumes;
}
/**
* Returns all available SD-Cards in the system (include emulated)
*
* <p>Warning: Hack! Based on Android source code of version 4.3 (API 18) Because there was no
* standard way to get it before android N
*
* @return All available SD-Cards in the system (include emulated)
*/
public synchronized ArrayList<StorageDirectoryParcelable> getStorageDirectoriesLegacy() {
List<String> rv = new ArrayList<>();
// Primary physical SD-CARD (not emulated)
final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
// All Secondary SD-CARDs (all exclude primary) separated by ":"
final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
// Primary emulated SD-CARD
final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
// Device has physical external storage; use plain paths.
if (TextUtils.isEmpty(rawExternalStorage)) {
// EXTERNAL_STORAGE undefined; falling back to default.
// Check for actual existence of the directory before adding to list
if (new File(DEFAULT_FALLBACK_STORAGE_PATH).exists()) {
rv.add(DEFAULT_FALLBACK_STORAGE_PATH);
} else {
// We know nothing else, use Environment's fallback
rv.add(Environment.getExternalStorageDirectory().getAbsolutePath());
}
} else {
rv.add(rawExternalStorage);
}
} else {
// Device has emulated storage; external storage paths should have
// userId burned into them.
final String rawUserId;
if (SDK_INT < JELLY_BEAN_MR1) {
rawUserId = "";
} else {
final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
final String[] folders = DIR_SEPARATOR.split(path);
final String lastFolder = folders[folders.length - 1];
boolean isDigit = false;
try {
Integer.valueOf(lastFolder);
isDigit = true;
} catch (NumberFormatException ignored) {
}
rawUserId = isDigit ? lastFolder : "";
}
// /storage/emulated/0[1,2,...]
if (TextUtils.isEmpty(rawUserId)) {
rv.add(rawEmulatedStorageTarget);
} else {
rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
}
}
// Add all secondary storages
if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
// All Secondary SD-CARDs splited into array
final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
Collections.addAll(rv, rawSecondaryStorages);
}
if (SDK_INT >= M && checkStoragePermission()) rv.clear();
if (SDK_INT >= KITKAT) {
String strings[] = ExternalSdCardOperation.getExtSdCardPathsForActivity(this);
for (String s : strings) {
File f = new File(s);
if (!rv.contains(s) && FileUtils.canListFiles(f)) rv.add(s);
}
}
File usb = getUsbDrive();
if (usb != null && !rv.contains(usb.getPath())) rv.add(usb.getPath());
if (SDK_INT >= KITKAT) {
if (SingletonUsbOtg.getInstance().isDeviceConnected()) {
rv.add(OTGUtil.PREFIX_OTG + "/");
}
}
// Assign a label and icon to each directory
ArrayList<StorageDirectoryParcelable> volumes = new ArrayList<>();
for (String file : rv) {
File f = new File(file);
@DrawableRes int icon;
if ("/storage/emulated/legacy".equals(file)
|| "/storage/emulated/0".equals(file)
|| "/mnt/sdcard".equals(file)) {
icon = R.drawable.ic_phone_android_white_24dp;
} else if ("/storage/sdcard1".equals(file)) {
icon = R.drawable.ic_sd_storage_white_24dp;
} else if ("/".equals(file)) {
icon = R.drawable.ic_drawer_root_white;
} else {
icon = R.drawable.ic_sd_storage_white_24dp;
}
@StorageNaming.DeviceDescription
int deviceDescription = StorageNaming.getDeviceDescriptionLegacy(f);
String name = StorageNamingHelper.getNameForDeviceDescription(this, f, deviceDescription);
volumes.add(new StorageDirectoryParcelable(file, name, icon));
}
return volumes;
}
@Override
public void onBackPressed() {
if (!drawer.isLocked() && drawer.isOpen()) {
drawer.close();
return;
}
Fragment fragment = getFragmentAtFrame();
if (getAppbar().getSearchView().isShown()) {
// hide search view if visible, with an animation
getAppbar().getSearchView().hideSearchView();
} else if (fragment instanceof TabFragment) {
if (floatingActionButton.isOpen()) {
floatingActionButton.close(true);
} else {
executeWithMainFragment(
mainFragment -> {
mainFragment.goBack();
return null;
});
}
} else if (fragment instanceof CompressedExplorerFragment) {
CompressedExplorerFragment compressedExplorerFragment =
(CompressedExplorerFragment) getFragmentAtFrame();
if (compressedExplorerFragment.mActionMode == null) {
if (compressedExplorerFragment.canGoBack()) {
compressedExplorerFragment.goBack();
} else if (isCompressedOpen) {
isCompressedOpen = false;
finish();
} else {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_out_bottom, R.anim.slide_out_bottom);
fragmentTransaction.remove(compressedExplorerFragment);
fragmentTransaction.commit();
supportInvalidateOptionsMenu();
showFab();
}
} else {
compressedExplorerFragment.mActionMode.finish();
}
} else if (fragment instanceof FtpServerFragment) {
// returning back from FTP server
if (path != null && path.length() > 0) {
HybridFile file = new HybridFile(OpenMode.UNKNOWN, path);
file.generateMode(this);
if (file.isDirectory(this)) goToMain(path);
else {
goToMain(null);
FileUtils.openFile(new File(path), this, getPrefs());
}
} else {
goToMain(null);
}
} else {
goToMain(null);
}
}
public void invalidatePasteSnackbar(boolean showSnackbar) {
if (pasteHelper != null) {
pasteHelper.invalidateSnackbar(this, showSnackbar);
}
}
public void exit() {
if (backPressedToExitOnce) {
NetCopyClientConnectionPool.INSTANCE.shutdown();
finish();
if (isRootExplorer()) {
closeInteractiveShell();