summaryrefslogtreecommitdiff
path: root/src/com/android/documentsui/BaseActivity.java
blob: 8a5779a694e0452a17f87268f600a415b5083e1b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.documentsui;

import static com.android.documentsui.base.Shared.EXTRA_BENCHMARK;
import static com.android.documentsui.base.SharedMinimal.DEBUG;
import static com.android.documentsui.base.State.MODE_GRID;
import static com.android.documentsui.util.FlagUtils.isUseMaterial3FlagEnabled;
import static com.android.documentsui.util.FlagUtils.isUsePeekPreviewFlagEnabled;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.MessageQueue.IdleHandler;
import android.preference.PreferenceManager;
import android.provider.DocumentsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.TextView;

import androidx.annotation.CallSuper;
import androidx.annotation.LayoutRes;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.android.documentsui.AbstractActionHandler.CommonAddons;
import com.android.documentsui.Injector.Injected;
import com.android.documentsui.NavigationViewManager.Breadcrumb;
import com.android.documentsui.base.DocumentInfo;
import com.android.documentsui.base.DocumentStack;
import com.android.documentsui.base.EventHandler;
import com.android.documentsui.base.RootInfo;
import com.android.documentsui.base.Shared;
import com.android.documentsui.base.State;
import com.android.documentsui.base.State.ViewMode;
import com.android.documentsui.base.UserId;
import com.android.documentsui.dirlist.AnimationView;
import com.android.documentsui.dirlist.AppsRowManager;
import com.android.documentsui.dirlist.DirectoryFragment;
import com.android.documentsui.peek.PeekViewManager;
import com.android.documentsui.prefs.LocalPreferences;
import com.android.documentsui.prefs.PreferencesMonitor;
import com.android.documentsui.queries.CommandInterceptor;
import com.android.documentsui.queries.SearchChipData;
import com.android.documentsui.queries.SearchFragment;
import com.android.documentsui.queries.SearchViewManager;
import com.android.documentsui.queries.SearchViewManager.SearchManagerListener;
import com.android.documentsui.roots.ProvidersCache;
import com.android.documentsui.sidebar.RootsFragment;
import com.android.documentsui.sorting.SortController;
import com.android.documentsui.sorting.SortModel;
import com.android.modules.utils.build.SdkLevel;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.color.DynamicColors;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Nullable;

public abstract class BaseActivity
        extends AppCompatActivity implements CommonAddons, NavigationViewManager.Environment {

    private static final String BENCHMARK_TESTING_PACKAGE = "com.android.documentsui.appperftests";
    private static final String TAG = "BaseActivity";

    protected SearchViewManager mSearchManager;
    protected AppsRowManager mAppsRowManager;
    protected @Nullable PeekViewManager mPeekViewManager;
    protected UserIdManager mUserIdManager;
    protected UserManagerState mUserManagerState;
    protected State mState;

    @Injected
    protected Injector<?> mInjector;

    protected ProvidersCache mProviders;
    protected DocumentsAccess mDocs;
    protected DrawerController mDrawer;

    protected NavigationViewManager mNavigator;
    protected SortController mSortController;
    protected ConfigStore mConfigStore;

    private final List<EventListener> mEventListeners = new ArrayList<>();
    private final String mTag;

    @LayoutRes
    private int mLayoutId;

    private RootsMonitor<BaseActivity> mRootsMonitor;

    private long mStartTime;
    private boolean mHasQueryContentFromIntent;

    private PreferencesMonitor mPreferencesMonitor;

    private final DocumentStack mInitialStack = new DocumentStack();
    private UserId mLastSelectedUser = null;

    protected void setInitialStack(DocumentStack stack) {
        if (mInitialStack.isInitialized()) {
            if (DEBUG) {
                Log.d(TAG, "Initial stack already initialised. " + mInitialStack.isInitialized());
            }
            return;
        }
        mInitialStack.reset(stack);
    }

    public DocumentStack getInitialStack() {
        return mInitialStack;
    }

    public UserId getLastSelectedUser() {
        return mLastSelectedUser;
    }

    public BaseActivity(@LayoutRes int layoutId, String tag) {
        mLayoutId = layoutId;
        mTag = tag;
    }

    protected abstract void refreshDirectory(int anim);

    /** Allows sub-classes to include information in a newly created State instance. */
    protected abstract void includeState(State initialState);

    protected abstract void onDirectoryCreated(DocumentInfo doc);

    public abstract Injector<?> getInjector();

    @VisibleForTesting
    protected void initConfigStore() {
        mConfigStore = DocumentsApplication.getConfigStore();
    }

    @VisibleForTesting
    public void setConfigStore(ConfigStore configStore) {
        mConfigStore = configStore;
    }

    @CallSuper
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Record the time when onCreate is invoked for metric.
        mStartTime = new Date().getTime();

        if (SdkLevel.isAtLeastS()) {
            getWindow().setHideOverlayWindows(true);
        }

        // ToDo Create tool to check resource version before applyStyle for the theme
        // If version code is not match, we should reset overlay package to default,
        // in case Activity continuously encounter resource not found exception.
        getTheme().applyStyle(R.style.DocumentsDefaultTheme, false);

        if (isUseMaterial3FlagEnabled() && SdkLevel.isAtLeastS()) {
            DynamicColors.applyToActivityIfAvailable(this);
        }

        super.onCreate(savedInstanceState);

        final Intent intent = getIntent();

        addListenerForLaunchCompletion();

        setContentView(mLayoutId);

        setContainer();

        initConfigStore();

        mInjector = getInjector();
        mState = getState(savedInstanceState);
        mDrawer = DrawerController.create(this, mInjector.config);
        Metrics.logActivityLaunch(mState, intent);

        if (isUseMaterial3FlagEnabled()) {
            View navRailRoots = findViewById(R.id.nav_rail_container_roots);
            if (navRailRoots != null) {
                // Bind event listener for the burger menu on nav rail.
                MaterialButton burgerMenu = findViewById(R.id.nav_rail_burger_menu);
                burgerMenu.setOnClickListener(v -> mDrawer.setOpen(true));
                burgerMenu.setOnFocusChangeListener(this::onBurgerMenuFocusChange);
            }
        }

        mProviders = DocumentsApplication.getProvidersCache(this);
        mDocs = DocumentsAccess.create(this, mState);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Breadcrumb breadcrumb = findViewById(R.id.horizontal_breadcrumb);
        assert (breadcrumb != null);
        View profileTabsContainer = findViewById(R.id.tabs_container);
        assert (profileTabsContainer != null);

        mNavigator = getNavigationViewManager(breadcrumb, profileTabsContainer);
        AppBarLayout appBarLayout = findViewById(R.id.app_bar);
        if (appBarLayout != null) {
            appBarLayout.addOnOffsetChangedListener(mNavigator);
        }

        SearchManagerListener searchListener = new SearchManagerListener() {
            /**
             * Called when search results changed. Refreshes the content of the directory. It
             * doesn't refresh elements on the action bar. e.g. The current directory name displayed
             * on the action bar won't get updated.
             */
            @Override
            public void onSearchChanged(@Nullable String query) {
                if (mSearchManager.isSearching()) {
                    Metrics.logSearchMode(query != null, mSearchManager.hasCheckedChip());
                    if (mInjector.pickResult != null) {
                        mInjector.pickResult.increaseActionCount();
                    }
                }

                mInjector.actions.loadDocumentsForCurrentStack();

                expandAppBar();
                DirectoryFragment dir = getDirectoryFragment();
                if (dir != null) {
                    dir.scrollToTop();
                }
            }

            @Override
            public void onSearchFinished() {
                // Restores menu icons state
                invalidateOptionsMenu();
            }

            @Override
            public void onSearchViewChanged(boolean opened) {
                mNavigator.update();
                // We also need to update AppsRowManager because we may want to show/hide the
                // appsRow in cross-profile search according to the searching conditions.
                mAppsRowManager.updateView(BaseActivity.this);
            }

            @Override
            public void onSearchChipStateChanged(View v) {
                final Checkable chip = (Checkable) v;
                if (chip.isChecked()) {
                    final SearchChipData item = (SearchChipData) v.getTag();
                    Metrics.logUserAction(MetricConsts.USER_ACTION_SEARCH_CHIP);
                    Metrics.logSearchType(item.getChipType());
                }
                // We also need to update AppsRowManager because we may want to show/hide the
                // appsRow in cross-profile search according to the searching conditions.
                mAppsRowManager.updateView(BaseActivity.this);
            }

            @Override
            public void onSearchViewFocusChanged(boolean hasFocus) {
                final boolean isInitialSearch
                        = !TextUtils.isEmpty(mSearchManager.getCurrentSearch())
                        && TextUtils.isEmpty(mSearchManager.getSearchViewText());
                if (hasFocus) {
                    if (!isInitialSearch) {
                        SearchFragment.showFragment(getSupportFragmentManager(),
                                mSearchManager.getSearchViewText());
                    }
                } else {
                    SearchFragment.dismissFragment(getSupportFragmentManager());
                }
            }

            @Override
            public void onSearchViewClearClicked() {
                if (SearchFragment.get(getSupportFragmentManager()) == null) {
                    SearchFragment.showFragment(getSupportFragmentManager(),
                            mSearchManager.getSearchViewText());
                }
            }
        };

        // "Commands" are meta input for controlling system behavior.
        // We piggy back on search input as it is the only text input
        // area in the app. But the functionality is independent
        // of "regular" search query processing.
        final CommandInterceptor cmdInterceptor = new CommandInterceptor(mInjector.features);
        cmdInterceptor.add(new CommandInterceptor.DumpRootsCacheHandler(this));

        // A tiny decorator that adds support for enabling CommandInterceptor
        // based on query input. It's sorta like CommandInterceptor, but its metaaahhh.
        EventHandler<String> queryInterceptor =
                CommandInterceptor.createDebugModeFlipper(
                        mInjector.features,
                        mInjector.debugHelper::toggleDebugMode,
                        cmdInterceptor);

        ViewGroup chipGroup = findViewById(R.id.search_chip_group);

        mUserIdManager = DocumentsApplication.getUserIdManager(this);
        mUserManagerState = DocumentsApplication.getUserManagerState(this);
        // If private space feature flag is enabled, we should store the intent that launched docsUi
        // so that we can use this intent to get CrossProfileResolveInfo when ever we want to,
        // for example when ACTION_PROFILE_AVAILABLE intent is received
        if (mUserManagerState != null && SdkLevel.isAtLeastS()) {
            mUserManagerState.setCurrentStateIntent(intent);
        }
        mSearchManager = new SearchViewManager(searchListener, queryInterceptor,
                chipGroup, savedInstanceState);
        // initialize the chip sets by accept mime types
        mSearchManager.initChipSets(mState.acceptMimes);
        // update the chip items by the mime types of the root
        mSearchManager.updateChips(getCurrentRoot().derivedMimeTypes);
        // parse the query content from intent when launch the
        // activity at the first time
        if (savedInstanceState == null) {
            mHasQueryContentFromIntent = mSearchManager.parseQueryContentFromIntent(getIntent(),
                    mState.action);
        }

        mNavigator.setSearchBarClickListener(v -> {
            mSearchManager.onSearchBarClicked();
            mNavigator.update();
        });

        mNavigator.setProfileTabsListener(userId -> {
            // There are several possible cases that may trigger this callback.
            // 1. A user click on tab layout.
            // 2. A user click on tab layout, when filter is checked. (searching = true)
            // 3. A user click on a open a dir of a different user in search (stack size > 1)
            // 4. After tab layout is initialized.

            if (!mState.stack.isInitialized()) {
                return;
            }

            // Reload the roots when the selected user is changed.
            // After reloading, we have visually same roots in the drawer. But they are
            // different by holding different userId. Next time when user select a root, it can
            // bring the user to correct root doc.
            final RootsFragment roots = RootsFragment.get(getSupportFragmentManager());
            if (roots != null) {
                roots.onSelectedUserChanged();
            }
            if (isUseMaterial3FlagEnabled()) {
                final RootsFragment navRailRoots =
                        RootsFragment.getNavRail(getSupportFragmentManager());
                if (navRailRoots != null) {
                    navRailRoots.onSelectedUserChanged();
                }
            }


            if (mState.stack.size() <= 1) {
                // We do not load cross-profile root if the stack contains two documents. The
                // stack may contain >1 docs when the user select a folder of the other user in
                // search. In that case, we don't want to reload the root. The whole stack
                // and the root will be updated in openFolderInSearchResult.

                // When a user filters files by search chips on the root doc, we will be in
                // searching mode and with stack size 1 (0 if rootDoc cannot be loaded).
                // The activity will clear search on root picked. If we don't clear the search,
                // user may see the search result screen show up briefly and then get cleared.
                mSearchManager.cancelSearch();
                // When a profile with user property SHOW_IN_QUIET_MODE_HIDDEN is currently
                // selected, and it becomes unavailable, we reset the roots to recents.
                // We do not reset it to recents when pick activity is due to ACTION_CREATE_DOCUMENT
                mInjector.actions.loadCrossProfileRoot(getCurrentRoot(), userId);
            }
        });

        mSortController = SortController.create(this, mState.derivedMode, mState.sortModel);
        if (isUseMaterial3FlagEnabled()) {
            View previewIconPlaceholder = findViewById(R.id.preview_icon_placeholder);
            if (previewIconPlaceholder != null) {
                previewIconPlaceholder.setVisibility(
                        mState.shouldShowPreview() ? View.VISIBLE : View.GONE);
            }
        }

        mPreferencesMonitor = new PreferencesMonitor(
                getApplicationContext().getPackageName(),
                PreferenceManager.getDefaultSharedPreferences(this),
                this::onPreferenceChanged);
        mPreferencesMonitor.start();

        // Base classes must update result in their onCreate.
        setResult(AppCompatActivity.RESULT_CANCELED);
        updateRecentsSetting();

        if (isUsePeekPreviewFlagEnabled()) {
            mPeekViewManager = new PeekViewManager(this);
            mPeekViewManager.initFragment(getSupportFragmentManager());
        }
    }

    private NavigationViewManager getNavigationViewManager(Breadcrumb breadcrumb,
            View profileTabsContainer) {
        if (mConfigStore.isPrivateSpaceInDocsUIEnabled()) {
            return new NavigationViewManager(
                    this,
                    mDrawer,
                    mState,
                    this,
                    breadcrumb,
                    profileTabsContainer,
                    DocumentsApplication.getUserManagerState(this),
                    mConfigStore,
                    mInjector);
        }
        return new NavigationViewManager(
                this,
                mDrawer,
                mState,
                this,
                breadcrumb,
                profileTabsContainer,
                DocumentsApplication.getUserIdManager(this),
                mConfigStore,
                mInjector);
    }

    public void onPreferenceChanged(String pref) {
        // For now, we only work with prefs that we backup. This
        // just limits the scope of what we expect to come flowing
        // through here until we know we want more and fancier options.
        assert (LocalPreferences.shouldBackup(pref));
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        Runnable finishActionMode =
                (isUseMaterial3FlagEnabled())
                        ? mNavigator::closeSelectionBar
                        : mInjector.actionModeController::finishActionMode;

        mRootsMonitor =
                new RootsMonitor<>(
                        this,
                        mInjector.actions,
                        mProviders,
                        mDocs,
                        mState,
                        mSearchManager,
                        finishActionMode);

        mRootsMonitor.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mLastSelectedUser = getSelectedUser();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isUseMaterial3FlagEnabled()) {
            // In Material3 the menu is now inflated in the `NavigationViewMenu`. This is currently
            // to allow for us to inflate between the action_menu and the activity menu. Once the
            // Material 3 flag is removed, the menus will be merged and we can rely on this single
            // inflation point.
            return super.onCreateOptionsMenu(menu);
        }
        boolean showMenu = super.onCreateOptionsMenu(menu);

        getMenuInflater().inflate(R.menu.activity, menu);
        mNavigator.update();
        boolean fullBarSearch = getResources().getBoolean(R.bool.full_bar_search_view);
        boolean showSearchBar = getResources().getBoolean(R.bool.show_search_bar);
        mSearchManager.install(menu, fullBarSearch, showSearchBar);

        // Remove the subMenu when material3 is launched b/379776735.
        final ActionMenuView subMenuView = findViewById(R.id.sub_menu);
        // If size is 0, it means the menu has not inflated and it should only do once.
        if (subMenuView != null && subMenuView.getMenu().size() == 0) {
            subMenuView.setOnMenuItemClickListener(this::onOptionsItemSelected);
            getMenuInflater().inflate(R.menu.sub_menu, subMenuView.getMenu());
        }

        return showMenu;
    }

    @Override
    @CallSuper
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        // Remove the subMenu when material3 is launched b/379776735.
        if (isUseMaterial3FlagEnabled()) {
            if (mNavigator != null) {
                mNavigator.updateActionMenu();
            }
        } else {
            mSearchManager.showMenu(mState.stack);
            final ActionMenuView subMenuView = findViewById(R.id.sub_menu);
            mInjector.menuManager.updateSubMenu(subMenuView.getMenu());
        }

        return true;
    }

    @Override
    protected void onDestroy() {
        mRootsMonitor.stop();
        mPreferencesMonitor.stop();
        mSortController.destroy();
        DocumentsApplication.invalidateUserManagerState(this);
        super.onDestroy();
    }

    private State getState(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            State state = savedInstanceState.<State>getParcelable(Shared.EXTRA_STATE);
            if (DEBUG) {
                Log.d(mTag, "Recovered existing state object: " + state);
            }
            return state;
        }

        State state = new State();

        final Intent intent = getIntent();

        state.sortModel = SortModel.createModel();
        state.localOnly = intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false);
        state.excludedAuthorities = getExcludedAuthorities();
        state.restrictScopeStorage = Shared.shouldRestrictStorageAccessFramework(this);
        state.showHiddenFiles = LocalPreferences.getShowHiddenFiles(
                getApplicationContext(),
                getApplicationContext()
                        .getResources()
                        .getBoolean(R.bool.show_hidden_files_by_default));
        state.configStore = mConfigStore;

        includeState(state);

        if (DEBUG) {
            Log.d(mTag, "Created new state object: " + state);
        }

        return state;
    }

    private void setContainer() {
        View root = findViewById(R.id.coordinator_layout);
        root.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        root.setOnApplyWindowInsetsListener(
                (v, insets) -> {
                    root.setPadding(
                            insets.getSystemWindowInsetLeft(),
                            insets.getSystemWindowInsetTop(),
                            insets.getSystemWindowInsetRight(),
                            0);

                    // When use_material3 flag is ON and FEATURE_FREEFORM_WINDOW_MANAGEMENT is
                    // enabled, then there should not be any additional bottom gap in full screen
                    // mode. Otherwise need to take into account the system window insets such as
                    // the bottom swipe up navigation gesture.
                    if (!isUseMaterial3FlagEnabled()
                            || !getApplicationContext()
                            .getPackageManager()
                            .hasSystemFeature(
                                    PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT)) {
                        View saveContainer = findViewById(R.id.container_save);
                        saveContainer.setPadding(0, 0, 0, insets.getSystemWindowInsetBottom());

                        View rootsContainer = findViewById(R.id.container_roots);
                        rootsContainer.setPadding(0, 0, 0, insets.getSystemWindowInsetBottom());
                    }

                    return insets.consumeSystemWindowInsets();
                });

        getWindow().setNavigationBarDividerColor(Color.TRANSPARENT);
        if (Build.VERSION.SDK_INT >= 29) {
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            getWindow().setNavigationBarContrastEnforced(true);
        } else {
            getWindow().setNavigationBarColor(getColor(R.color.nav_bar_translucent));
        }
    }

    @Override
    public void setRootsDrawerOpen(boolean open) {
        mNavigator.revealRootsDrawer(open);
    }

    @Override
    public void setRootsDrawerLocked(boolean locked) {
        mDrawer.setLocked(locked);
        mNavigator.update();
    }

    @Override
    public void onRootPicked(RootInfo root) {
        // Clicking on the current root removes search
        mSearchManager.cancelSearch();

        // Skip refreshing if root nor directory didn't change
        if (root.equals(getCurrentRoot()) && mState.stack.size() <= 1) {
            return;
        }

        if (isUseMaterial3FlagEnabled()) {
            mNavigator.closeSelectionBar();
        } else {
            mInjector.actionModeController.finishActionMode();
        }
        mSortController.onViewModeChanged(mState.derivedMode);

        // Set summary header's visibility. Only recents and downloads root may have summary in
        // their docs.
        mState.sortModel.setDimensionVisibility(
                SortModel.SORT_DIMENSION_ID_SUMMARY,
                root.isRecents() || root.isDownloads() ? View.VISIBLE : View.INVISIBLE);

        // Clear entire backstack and start in new root
        mState.stack.changeRoot(root);

        // Recents is always in memory, so we just load it directly.
        // Otherwise we delegate loading data from disk to a task
        // to ensure a responsive ui.
        if (mProviders.isRecentsRoot(root)) {
            refreshCurrentRootAndDirectory(AnimationView.ANIM_NONE);
        } else {
            mInjector.actions.getRootDocument(
                    root,
                    TimeoutTask.DEFAULT_TIMEOUT,
                    doc -> mInjector.actions.openRootDocument(doc));
        }

        expandAppBar();
        updateHeaderTitle();
    }

    protected ProfileTabsAddons getProfileTabsAddon() {
        return mNavigator.getProfileTabsAddons();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        final int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        } else if (id == R.id.option_menu_create_dir) {
            getInjector().actions.showCreateDirectoryDialog();
            return true;
        } else if (id == R.id.option_menu_search) {
            // SearchViewManager listens for this directly.
            return false;
        } else if (id == R.id.option_menu_select_all) {
            getInjector().actions.selectAllFiles();
            return true;
        } else if (id == R.id.option_menu_debug) {
            getInjector().actions.showDebugMessage();
            return true;
        } else if (id == R.id.option_menu_sort) {
            getInjector().actions.showSortDialog();
            return true;
        } else if (id == R.id.option_menu_launcher) {
            getInjector().actions.switchLauncherIcon();
            return true;
        } else if (id == R.id.option_menu_show_hidden_files) {
            onClickedShowHiddenFiles();
            return true;
        } else if (id == R.id.sub_menu_grid) {
            setViewMode(MODE_GRID);
            return true;
        } else if (id == R.id.sub_menu_list) {
            setViewMode(State.MODE_LIST);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected final @Nullable DirectoryFragment getDirectoryFragment() {
        return DirectoryFragment.get(getSupportFragmentManager());
    }

    /**
     * Returns true if a directory can be created in the current location.
     */
    protected boolean canCreateDirectory() {
        final RootInfo root = getCurrentRoot();
        final DocumentInfo cwd = getCurrentDirectory();
        return cwd != null
                && cwd.isCreateSupported()
                && !mSearchManager.isSearching()
                && !root.isRecents();
    }

    /**
     * Returns true if a directory can be inspected.
     */
    protected boolean canInspectDirectory() {
        return false;
    }

    // TODO: make navigator listen to state
    @Override
    public final void updateNavigator() {
        mNavigator.update();
    }

    public final NavigationViewManager getNavigator() {
        return mNavigator;
    }

    @Override
    public void restoreRootAndDirectory() {
        // We're trying to restore stuff in document stack from saved instance. If we didn't have a
        // chance to spawn a fragment before we need to do it now. However if we spawned a fragment
        // already, system will automatically restore the fragment for us so we don't need to do
        // that manually this time.
        if (DirectoryFragment.get(getSupportFragmentManager()) == null) {
            refreshCurrentRootAndDirectory(AnimationView.ANIM_NONE);
        }
    }

    /**
     * Refreshes the content of the director and the menu/action bar.
     * The current directory name and selection will get updated.
     */
    @Override
    public final void refreshCurrentRootAndDirectory(int anim) {
        mSearchManager.cancelSearch();

        // only set the query content in the first launch
        if (mHasQueryContentFromIntent) {
            mHasQueryContentFromIntent = false;
            mSearchManager.setCurrentSearch(mSearchManager.getQueryContentFromIntent());
        }

        mState.derivedMode = LocalPreferences.getViewMode(this, mState.stack.getRoot(), MODE_GRID);

        mNavigator.update();

        refreshDirectory(anim);

        final RootsFragment roots = RootsFragment.get(getSupportFragmentManager());
        if (roots != null) {
            roots.onCurrentRootChanged();
        }
        if (isUseMaterial3FlagEnabled()) {
            final RootsFragment navRailRoots =
                    RootsFragment.getNavRail(getSupportFragmentManager());
            if (navRailRoots != null) {
                navRailRoots.onCurrentRootChanged();
            }
        }

        String appName = getString(R.string.files_label);
        String currentTitle = getTitle() != null ? getTitle().toString() : "";
        if (currentTitle.equals(appName)) {
            // First launch, TalkBack announces app name.
            getWindow().getDecorView().announceForAccessibility(appName);
        }

        String newTitle = mState.stack.getTitle();
        if (newTitle != null) {
            // Causes talkback to announce the activity's new title
            setTitle(newTitle);
        }

        invalidateOptionsMenu();
        mSortController.onViewModeChanged(mState.derivedMode);
        mSearchManager.updateChips(getCurrentRoot().derivedMimeTypes);
        mAppsRowManager.updateView(this);
    }

    private final List<String> getExcludedAuthorities() {
        List<String> authorities = new ArrayList<>();
        if (getIntent().getBooleanExtra(DocumentsContract.EXTRA_EXCLUDE_SELF, false)) {
            // Exclude roots provided by the calling package.
            String packageName = Shared.getCallingPackageName(this);
            try {
                PackageInfo pkgInfo = getPackageManager().getPackageInfo(packageName,
                        PackageManager.GET_PROVIDERS);
                for (ProviderInfo provider : pkgInfo.providers) {
                    authorities.add(provider.authority);
                }
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(mTag, "Calling package name does not resolve: " + packageName);
            }
        }
        return authorities;
    }

    public static BaseActivity get(Fragment fragment) {
        return (BaseActivity) fragment.getActivity();
    }

    public State getDisplayState() {
        return mState;
    }

    /**
     * Updates hidden files visibility based on user action.
     */
    private void onClickedShowHiddenFiles() {
        boolean showHiddenFiles = !mState.showHiddenFiles;
        Context context = getApplicationContext();

        Metrics.logUserAction(showHiddenFiles
                ? MetricConsts.USER_ACTION_SHOW_HIDDEN_FILES
                : MetricConsts.USER_ACTION_HIDE_HIDDEN_FILES);
        LocalPreferences.setShowHiddenFiles(context, showHiddenFiles);
        mState.showHiddenFiles = showHiddenFiles;

        // Calls this to trigger either MultiRootDocumentsLoader or DirectoryLoader reloading.
        mInjector.actions.loadDocumentsForCurrentStack();
    }

    /**
     * Set mode based on explicit user action.
     */
    void setViewMode(@ViewMode int mode) {
        if (mode == State.MODE_GRID) {
            Metrics.logUserAction(MetricConsts.USER_ACTION_GRID);
        } else if (mode == State.MODE_LIST) {
            Metrics.logUserAction(MetricConsts.USER_ACTION_LIST);
        }

        LocalPreferences.setViewMode(this, getCurrentRoot(), mode);
        mState.derivedMode = mode;

        // Remove the subMenu when material3 is launched b/379776735.
        if (isUseMaterial3FlagEnabled()) {
            mInjector.menuManager.updateSubMenu(null);
        } else {
            final ActionMenuView subMenuView = findViewById(R.id.sub_menu);
            mInjector.menuManager.updateSubMenu(subMenuView.getMenu());
        }

        DirectoryFragment dir = getDirectoryFragment();
        if (dir != null) {
            dir.onViewModeChanged();
        }

        mSortController.onViewModeChanged(mode);
    }

    /**
     * Reload documnets by current stack in certain situation.
     */
    public void reloadDocumentsIfNeeded() {
        if (isInRecents() || mSearchManager.isSearching()) {
            // Both using MultiRootDocumentsLoader which have not ContentObserver.
            mInjector.actions.loadDocumentsForCurrentStack();
        }
    }

    public void expandAppBar() {
        final AppBarLayout appBarLayout = findViewById(R.id.app_bar);
        if (appBarLayout != null) {
            appBarLayout.setExpanded(true);
        }
    }

    /**
     * Updates headerContainer by setting its visibility
     *
     * @param shouldHideHeader whether to hide header container or not
     */
    public void updateHeader(boolean shouldHideHeader) {
        // Remove headContainer when material3 is launched. b/379776735.
        View headerContainer = findViewById(R.id.header_container);
        if (headerContainer == null) {
            updateHeaderTitle();
            return;
        }
        if (shouldHideHeader) {
            headerContainer.setVisibility(View.GONE);
        } else {
            headerContainer.setVisibility(View.VISIBLE);
            updateHeaderTitle();
        }
    }

    public void updateHeaderTitle() {
        if (!mState.stack.isInitialized()) {
            //stack has not initialized, the header will update after the stack finishes loading
            return;
        }

        final RootInfo root = mState.stack.getRoot();
        final String rootTitle = root.title;
        String result;

        switch (root.derivedType) {
            case RootInfo.TYPE_RECENTS:
                result = getHeaderRecentTitle();
                break;
            case RootInfo.TYPE_IMAGES:
            case RootInfo.TYPE_VIDEO:
            case RootInfo.TYPE_AUDIO:
                result = rootTitle;
                break;
            case RootInfo.TYPE_DOWNLOADS:
                result = getHeaderDownloadsTitle();
                break;
            case RootInfo.TYPE_LOCAL:
            case RootInfo.TYPE_MTP:
            case RootInfo.TYPE_SD:
            case RootInfo.TYPE_USB:
                result = getHeaderStorageTitle(rootTitle);
                break;
            default:
                final String summary = root.summary;
                result = getHeaderDefaultTitle(rootTitle, summary);
                break;
        }

        // Remove the headerTitle when material3 is launched b/379776735.
        TextView headerTitle = findViewById(R.id.header_title);
        if (headerTitle != null) {
            headerTitle.setText(result);
        }
    }

    private String getHeaderRecentTitle() {
        // If stack size larger than 1, it means user global search than enter a folder, but search
        // is not expanded on that time.
        boolean isGlobalSearch = mSearchManager.isSearching() || mState.stack.size() > 1;
        if (mState.isPhotoPicking()) {
            final int resId = isGlobalSearch
                    ? R.string.root_info_header_image_global_search
                    : R.string.root_info_header_image_recent;
            return getString(resId);
        } else {
            final int resId = isGlobalSearch
                    ? R.string.root_info_header_global_search
                    : R.string.root_info_header_recent;
            return getString(resId);
        }
    }

    private String getHeaderDownloadsTitle() {
        return getString(mState.isPhotoPicking()
                ? R.string.root_info_header_image_downloads : R.string.root_info_header_downloads);
    }

    private String getHeaderStorageTitle(String rootTitle) {
        if (mState.stack.size() > 1) {
            final int resId = mState.isPhotoPicking()
                    ? R.string.root_info_header_image_folder : R.string.root_info_header_folder;
            return getString(resId, getCurrentTitle());
        } else {
            final int resId = mState.isPhotoPicking()
                    ? R.string.root_info_header_image_storage : R.string.root_info_header_storage;
            return getString(resId, rootTitle);
        }
    }

    private String getHeaderDefaultTitle(String rootTitle, String summary) {
        if (TextUtils.isEmpty(summary)) {
            final int resId = mState.isPhotoPicking()
                    ? R.string.root_info_header_image_app : R.string.root_info_header_app;
            return getString(resId, rootTitle);
        } else {
            final int resId = mState.isPhotoPicking()
                    ? R.string.root_info_header_image_app_with_summary
                    : R.string.root_info_header_app_with_summary;
            return getString(resId, rootTitle, summary);
        }
    }

    /**
     * Get title string equal to the string action bar displayed.
     *
     * @return current directory title name
     */
    public String getCurrentTitle() {
        if (!mState.stack.isInitialized()) {
            return null;
        }

        if (mState.stack.size() > 1) {
            return getCurrentDirectory().displayName;
        } else {
            return getCurrentRoot().title;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);
        state.putParcelable(Shared.EXTRA_STATE, mState);
        mSearchManager.onSaveInstanceState(state);
    }

    @Override
    public boolean isSearchExpanded() {
        return mSearchManager.isExpanded();
    }

    @Override
    public UserId getSelectedUser() {
        return mNavigator.getSelectedUser();
    }

    public RootInfo getCurrentRoot() {
        RootInfo root = mState.stack.getRoot();
        if (root != null) {
            return root;
        } else {
            return mProviders.getRecentsRoot(getSelectedUser());
        }
    }

    @Override
    public DocumentInfo getCurrentDirectory() {
        return mState.stack.peek();
    }

    @Override
    public boolean isInRecents() {
        return mState.stack.isRecents();
    }

    @VisibleForTesting
    public void addEventListener(EventListener listener) {
        mEventListeners.add(listener);
    }

    @VisibleForTesting
    public void removeEventListener(EventListener listener) {
        mEventListeners.remove(listener);
    }

    @VisibleForTesting
    public void notifyDirectoryLoaded(Uri uri) {
        for (EventListener listener : mEventListeners) {
            listener.onDirectoryLoaded(uri);
        }
    }

    @VisibleForTesting
    @Override
    public void notifyDirectoryNavigated(Uri uri) {
        for (EventListener listener : mEventListeners) {
            listener.onDirectoryNavigated(uri);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            mInjector.debugHelper.debugCheck(event.getDownTime(), event.getKeyCode());
        }

        DocumentsApplication.getDragAndDropManager(this).onKeyEvent(event);

        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mInjector.actions.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Pops the top entry off the directory stack, and returns the user to the previous directory.
     * If the directory stack only contains one item, this method does nothing.
     *
     * @return Whether the stack was popped.
     */
    protected boolean popDir() {
        if (mState.stack.size() > 1) {
            final DirectoryFragment fragment = getDirectoryFragment();
            if (fragment != null) {
                fragment.stopScroll();
            }

            mState.stack.pop();
            refreshCurrentRootAndDirectory(AnimationView.ANIM_LEAVE);
            return true;
        }
        return false;
    }

    protected boolean focusSidebar() {
        RootsFragment rf = RootsFragment.get(getSupportFragmentManager());
        assert (rf != null);
        return rf.requestFocus();
    }

    /**
     * Closes the activity when it's idle.
     */
    private void addListenerForLaunchCompletion() {
        addEventListener(new EventListener() {
            @Override
            public void onDirectoryNavigated(Uri uri) {
            }

            @Override
            public void onDirectoryLoaded(Uri uri) {
                removeEventListener(this);
                getMainLooper().getQueue().addIdleHandler(new IdleHandler() {
                    @Override
                    public boolean queueIdle() {
                        // If startup benchmark is requested by an allowedlist testing package, then
                        // close the activity once idle, and notify the testing activity.
                        if (getIntent().getBooleanExtra(EXTRA_BENCHMARK, false) &&
                                BENCHMARK_TESTING_PACKAGE.equals(getCallingPackage())) {
                            setResult(RESULT_OK);
                            finish();
                        }

                        Metrics.logStartupMs((int) (new Date().getTime() - mStartTime));

                        // Remove the idle handler.
                        return false;
                    }
                });
            }
        });
    }

    @VisibleForTesting
    protected interface EventListener {
        /**
         * @param uri Uri navigated to. If recents, then null.
         */
        void onDirectoryNavigated(@Nullable Uri uri);

        /**
         * @param uri Uri of the loaded directory. If recents, then null.
         */
        void onDirectoryLoaded(@Nullable Uri uri);
    }

    /**
     * Updates the Recents preview settings based on presence of hidden profiles. Used not to leak
     * Private profile existence when it was locked after the app was moved to the Recents.
     */
    public void updateRecentsSetting() {
        if (!SdkLevel.isAtLeastV()) {
            return;
        }

        if (mUserManagerState == null) {
            Log.e(TAG, "Can't update Recents screenshot setting: User manager state is null.");
            return;
        }

        if (DEBUG) {
            Log.d(
                    TAG,
                    "Set recents screenshot to "
                            + (!mUserManagerState.areHiddenInQuietModeProfilesPresent() ? "enabled"
                            : "disabled"));
        }
        setRecentsScreenshotEnabled(!mUserManagerState.areHiddenInQuietModeProfilesPresent());
    }

    /**
     * When the burger menu is focused, adding a focus ring indicator using Stroke.
     * TODO(b/381957932): Remove this once Material Button supports focus ring.
     */
    private void onBurgerMenuFocusChange(View v, boolean hasFocus) {
        MaterialButton burgerMenu = (MaterialButton) v;
        if (hasFocus) {
            final int focusRingWidth = getResources()
                    .getDimensionPixelSize(R.dimen.focus_ring_width);
            burgerMenu.setStrokeWidth(focusRingWidth);
        } else {
            burgerMenu.setStrokeWidth(0);
        }
    }
}