summaryrefslogtreecommitdiff
path: root/src/com/android/documentsui/ProfileTabs.java
blob: 74db6f4bdaf49f76ad634a22607ad3201665548c (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
/*
 * Copyright (C) 2020 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 androidx.core.util.Preconditions.checkNotNull;

import static com.android.documentsui.DevicePolicyResources.Strings.PERSONAL_TAB;
import static com.android.documentsui.DevicePolicyResources.Strings.WORK_TAB;
import static com.android.documentsui.util.FlagUtils.isUseMaterial3FlagEnabled;

import android.app.admin.DevicePolicyManager;
import android.os.Build;
import android.os.UserManager;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.android.documentsui.base.RootInfo;
import com.android.documentsui.base.State;
import com.android.documentsui.base.UserId;
import com.android.modules.utils.build.SdkLevel;

import com.google.android.material.tabs.TabLayout;
import com.google.common.base.Objects;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * A manager class to control UI on a {@link TabLayout} for cross-profile purpose.
 */
public class ProfileTabs implements ProfileTabsAddons {
    private static final float DISABLED_TAB_OPACITY = 0.38f;

    private final View mTabsContainer;
    private final TabLayout mTabs;
    private final State mState;
    private final NavigationViewManager.Environment mEnv;
    private final AbstractActionHandler.CommonAddons mCommonAddons;
    @Nullable
    private final UserIdManager mUserIdManager;
    @Nullable
    private final UserManagerState mUserManagerState;
    private final ConfigStore mConfigStore;
    private List<UserId> mUserIds;
    @Nullable
    private Listener mListener;
    private TabLayout.OnTabSelectedListener mOnTabSelectedListener;
    private View mTabSeparator;

    public ProfileTabs(View tabLayoutContainer, State state, UserIdManager userIdManager,
            NavigationViewManager.Environment env,
            AbstractActionHandler.CommonAddons commonAddons, ConfigStore configStore) {
        this(tabLayoutContainer, state, userIdManager, null, env, commonAddons, configStore);
    }

    public ProfileTabs(View tabLayoutContainer, State state, UserManagerState userManagerState,
            NavigationViewManager.Environment env,
            AbstractActionHandler.CommonAddons commonAddons, ConfigStore configStore) {
        this(tabLayoutContainer, state, null, userManagerState, env, commonAddons, configStore);
    }

    public ProfileTabs(View tabLayoutContainer, State state, @Nullable UserIdManager userIdManager,
            @Nullable UserManagerState userManagerState, NavigationViewManager.Environment env,
            AbstractActionHandler.CommonAddons commonAddons, ConfigStore configStore) {
        mTabsContainer = checkNotNull(tabLayoutContainer);
        mTabs = tabLayoutContainer.findViewById(R.id.tabs);
        mState = checkNotNull(state);
        mEnv = checkNotNull(env);
        mCommonAddons = checkNotNull(commonAddons);
        mConfigStore = configStore;
        if (mConfigStore.isPrivateSpaceInDocsUIEnabled()) {
            mUserIdManager = userIdManager;
            mUserManagerState = checkNotNull(userManagerState);
        } else {
            mUserIdManager = checkNotNull(userIdManager);
            mUserManagerState = userManagerState;
        }
        mTabs.removeAllTabs();
        mUserIds = Collections.singletonList(UserId.CURRENT_USER);
        mTabSeparator = tabLayoutContainer.findViewById(R.id.tab_separator);

        mOnTabSelectedListener = new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (mListener != null) {
                    // find a way to identify user iteraction
                    mListener.onUserSelected((UserId) tab.getTag());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        };
        mTabs.addOnTabSelectedListener(mOnTabSelectedListener);
    }

    /**
     * Update the tab layout based on status of availability of the hidden profile.
     */
    public void updateView() {
        updateTabsIfNeeded();
        RootInfo currentRoot = mCommonAddons.getCurrentRoot();
        if (mTabs.getSelectedTabPosition() == -1
                || !Objects.equal(currentRoot.userId, getSelectedUser())) {
            // Update the layout according to the current root if necessary.
            // Make sure we do not invoke callback. Otherwise, it is likely to cause infinite loop.
            mTabs.removeOnTabSelectedListener(mOnTabSelectedListener);
            mTabs.selectTab(mTabs.getTabAt(mUserIds.indexOf(currentRoot.userId)));
            mTabs.addOnTabSelectedListener(mOnTabSelectedListener);
        }
        mTabsContainer.setVisibility(shouldShow() ? View.VISIBLE : View.GONE);

        // Material next changes apply only for version S or greater
        if (SdkLevel.isAtLeastS()) {
            mTabSeparator.setVisibility(View.GONE);
            int tabContainerHeightInDp = (int) mTabsContainer.getContext().getResources()
                    .getDimension(R.dimen.tab_container_height);
            mTabsContainer.getLayoutParams().height = tabContainerHeightInDp;
            ViewGroup.MarginLayoutParams tabContainerMarginLayoutParams =
                    (ViewGroup.MarginLayoutParams) mTabsContainer.getLayoutParams();
            int tabContainerMarginTop = (int) mTabsContainer.getContext().getResources()
                    .getDimension(R.dimen.profile_tab_margin_top);
            tabContainerMarginLayoutParams.setMargins(0, tabContainerMarginTop, 0, 0);
            mTabsContainer.requestLayout();
            for (int i = 0; i < mTabs.getTabCount(); i++) {

                // Tablayout holds a view that contains the individual tab
                View tab = ((ViewGroup) mTabs.getChildAt(0)).getChildAt(i);

                // Get individual tab to set the style
                ViewGroup.MarginLayoutParams marginLayoutParams =
                        (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
                int tabMarginSide = (int) mTabsContainer.getContext().getResources()
                        .getDimension(R.dimen.profile_tab_margin_side);
                if (isUseMaterial3FlagEnabled()) {
                    final boolean isRtl = mTabs.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
                    // if use_material3 flag is ON, we uses the margin value as the right margin
                    // (left margin for RTL),  except for the last child.
                    if (i != mTabs.getTabCount() - 1) {
                        marginLayoutParams.setMargins(
                                isRtl ? tabMarginSide : 0, 0, isRtl ? 0 : tabMarginSide, 0);
                    }
                } else {
                    marginLayoutParams.setMargins(tabMarginSide, 0, tabMarginSide, 0);
                }
                int tabHeightInDp = (int) mTabsContainer.getContext().getResources()
                        .getDimension(R.dimen.tab_height);
                tab.getLayoutParams().height = tabHeightInDp;
                tab.requestLayout();
                tab.setBackgroundResource(R.drawable.tab_border_rounded);
            }

        }
    }

    public void setListener(@Nullable Listener listener) {
        mListener = listener;
    }

    private void updateTabsIfNeeded() {
        List<UserId> userIds = getUserIds();
        // Add tabs if the userIds is not equals to cached mUserIds.
        // Given that mUserIds was initialized with only the current user, if getUserIds()
        // returns just the current user, we don't need to do anything on the tab layout.
        if (!userIds.equals(mUserIds)) {
            mUserIds = new ArrayList<>();
            mUserIds.addAll(userIds);
            mTabs.removeAllTabs();
            if (mUserIds.size() > 1) {
                if (mConfigStore.isPrivateSpaceInDocsUIEnabled() && SdkLevel.isAtLeastS()) {
                    addTabsPrivateSpaceEnabled();
                } else {
                    addTabsPrivateSpaceDisabled();
                }
            }
        }
    }

    private List<UserId> getUserIds() {
        if (mConfigStore.isPrivateSpaceInDocsUIEnabled() && SdkLevel.isAtLeastS()) {
            assert mUserManagerState != null;
            return mUserManagerState.getUserIds();
        }
        assert mUserIdManager != null;
        return mUserIdManager.getUserIds();
    }

    @RequiresApi(Build.VERSION_CODES.S)
    private void addTabsPrivateSpaceEnabled() {
        // set setSelected to false otherwise it will trigger callback.
        assert mUserManagerState != null;
        Map<UserId, String> userIdToLabelMap = mUserManagerState.getUserIdToLabelMap();
        UserManager userManager = mTabsContainer.getContext().getSystemService(UserManager.class);
        assert userManager != null;
        for (UserId userId : mUserIds) {
            mTabs.addTab(createTab(userIdToLabelMap.get(userId), userId), /* setSelected= */false);
        }
    }

    private void addTabsPrivateSpaceDisabled() {
        // set setSelected to false otherwise it will trigger callback.
        assert mUserIdManager != null;
        mTabs.addTab(createTab(
                getEnterpriseString(PERSONAL_TAB, R.string.personal_tab),
                mUserIdManager.getSystemUser()), /* setSelected= */false);
        mTabs.addTab(createTab(
                getEnterpriseString(WORK_TAB, R.string.work_tab),
                mUserIdManager.getManagedUser()), /* setSelected= */false);
    }

    private String getEnterpriseString(String updatableStringId, int defaultStringId) {
        if (SdkLevel.isAtLeastT()) {
            return getUpdatableEnterpriseString(updatableStringId, defaultStringId);
        } else {
            return mTabsContainer.getContext().getString(defaultStringId);
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private String getUpdatableEnterpriseString(String updatableStringId, int defaultStringId) {
        DevicePolicyManager dpm = mTabsContainer.getContext().getSystemService(
                DevicePolicyManager.class);
        return dpm.getResources().getString(
                updatableStringId,
                () -> mTabsContainer.getContext().getString(defaultStringId));
    }

    /**
     * Returns the user represented by the selected tab. If there is no tab, return the
     * current user.
     */
    public UserId getSelectedUser() {
        if (mTabs.getTabCount() > 1 && mTabs.getSelectedTabPosition() >= 0) {
            return (UserId) mTabs.getTabAt(mTabs.getSelectedTabPosition()).getTag();
        }
        return UserId.CURRENT_USER;
    }

    private boolean shouldShow() {
        // Only show tabs when:
        // 1. state supports cross profile, and
        // 2. more than one tab, and
        // 3. not in search mode, and
        // 4. not in sub-folder, and
        // 5. the root supports cross profile.
        return mState.supportsCrossProfile()
                && mTabs.getTabCount() > 1
                && !mEnv.isSearchExpanded()
                && mState.stack.size() <= 1
                && mState.stack.getRoot() != null && mState.stack.getRoot().supportsCrossProfile();
    }

    private TabLayout.Tab createTab(String text, UserId userId) {
        return mTabs.newTab().setText(text).setTag(userId);
    }

    @Override
    public void setEnabled(boolean enabled) {
        if (mTabs.getChildCount() > 0) {
            View view = mTabs.getChildAt(0);
            if (view instanceof ViewGroup) {
                ViewGroup tabs = (ViewGroup) view;
                for (int i = 0; i < tabs.getChildCount(); i++) {
                    View tabView = tabs.getChildAt(i);
                    tabView.setEnabled(enabled);
                    tabView.setAlpha((enabled || mTabs.getSelectedTabPosition() == i) ? 1f
                            : DISABLED_TAB_OPACITY);
                }
            }
        }
    }

    /**
     * Interface definition for a callback to be invoked.
     */
    interface Listener {
        /**
         * Called when a user tab has been selected.
         */
        void onUserSelected(UserId userId);
    }
}