1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings;
18 
19 import android.accounts.Account;
20 import android.accounts.AccountManager;
21 import android.accounts.AuthenticatorDescription;
22 import android.app.Activity;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.pm.PackageManager;
26 import android.content.pm.UserInfo;
27 import android.content.res.Resources;
28 import android.graphics.drawable.Drawable;
29 import android.os.Bundle;
30 import android.os.Environment;
31 import android.os.SystemProperties;
32 import android.os.UserHandle;
33 import android.os.UserManager;
34 import android.util.Log;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.ViewGroup;
38 import android.widget.Button;
39 import android.widget.CheckBox;
40 import android.widget.LinearLayout;
41 import android.widget.TextView;
42 
43 import com.android.internal.logging.MetricsProto.MetricsEvent;
44 import com.android.settingslib.RestrictedLockUtils;
45 
46 import java.util.List;
47 
48 import static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
49 
50 /**
51  * Confirm and execute a reset of the device to a clean "just out of the box"
52  * state.  Multiple confirmations are required: first, a general "are you sure
53  * you want to do this?" prompt, followed by a keyguard pattern trace if the user
54  * has defined one, followed by a final strongly-worded "THIS WILL ERASE EVERYTHING
55  * ON THE PHONE" prompt.  If at any time the phone is allowed to go to sleep, is
56  * locked, et cetera, then the confirmation sequence is abandoned.
57  *
58  * This is the initial screen.
59  */
60 public class MasterClear extends OptionsMenuFragment {
61     private static final String TAG = "MasterClear";
62 
63     private static final int KEYGUARD_REQUEST = 55;
64 
65     static final String ERASE_EXTERNAL_EXTRA = "erase_sd";
66 
67     private View mContentView;
68     private Button mInitiateButton;
69     private View mExternalStorageContainer;
70     private CheckBox mExternalStorage;
71 
72     /**
73      * Keyguard validation is run using the standard {@link ConfirmLockPattern}
74      * component as a subactivity
75      * @param request the request code to be returned once confirmation finishes
76      * @return true if confirmation launched
77      */
runKeyguardConfirmation(int request)78     private boolean runKeyguardConfirmation(int request) {
79         Resources res = getActivity().getResources();
80         return new ChooseLockSettingsHelper(getActivity(), this).launchConfirmationActivity(
81                 request, res.getText(R.string.master_clear_title));
82     }
83 
84     @Override
onActivityResult(int requestCode, int resultCode, Intent data)85     public void onActivityResult(int requestCode, int resultCode, Intent data) {
86         super.onActivityResult(requestCode, resultCode, data);
87 
88         if (requestCode != KEYGUARD_REQUEST) {
89             return;
90         }
91 
92         // If the user entered a valid keyguard trace, present the final
93         // confirmation prompt; otherwise, go back to the initial state.
94         if (resultCode == Activity.RESULT_OK) {
95             showFinalConfirmation();
96         } else {
97             establishInitialState();
98         }
99     }
100 
showFinalConfirmation()101     private void showFinalConfirmation() {
102         Bundle args = new Bundle();
103         args.putBoolean(ERASE_EXTERNAL_EXTRA, mExternalStorage.isChecked());
104         ((SettingsActivity) getActivity()).startPreferencePanel(MasterClearConfirm.class.getName(),
105                 args, R.string.master_clear_confirm_title, null, null, 0);
106     }
107 
108     /**
109      * If the user clicks to begin the reset sequence, we next require a
110      * keyguard confirmation if the user has currently enabled one.  If there
111      * is no keyguard available, we simply go to the final confirmation prompt.
112      */
113     private final Button.OnClickListener mInitiateListener = new Button.OnClickListener() {
114 
115         public void onClick(View v) {
116             if (!runKeyguardConfirmation(KEYGUARD_REQUEST)) {
117                 showFinalConfirmation();
118             }
119         }
120     };
121 
122     /**
123      * In its initial state, the activity presents a button for the user to
124      * click in order to initiate a confirmation sequence.  This method is
125      * called from various other points in the code to reset the activity to
126      * this base state.
127      *
128      * <p>Reinflating views from resources is expensive and prevents us from
129      * caching widget pointers, so we use a single-inflate pattern:  we lazy-
130      * inflate each view, caching all of the widget pointers we'll need at the
131      * time, then simply reuse the inflated views directly whenever we need
132      * to change contents.
133      */
establishInitialState()134     private void establishInitialState() {
135         mInitiateButton = (Button) mContentView.findViewById(R.id.initiate_master_clear);
136         mInitiateButton.setOnClickListener(mInitiateListener);
137         mExternalStorageContainer = mContentView.findViewById(R.id.erase_external_container);
138         mExternalStorage = (CheckBox) mContentView.findViewById(R.id.erase_external);
139 
140         /*
141          * If the external storage is emulated, it will be erased with a factory
142          * reset at any rate. There is no need to have a separate option until
143          * we have a factory reset that only erases some directories and not
144          * others. Likewise, if it's non-removable storage, it could potentially have been
145          * encrypted, and will also need to be wiped.
146          */
147         boolean isExtStorageEmulated = Environment.isExternalStorageEmulated();
148         if (isExtStorageEmulated
149                 || (!Environment.isExternalStorageRemovable() && isExtStorageEncrypted())) {
150             mExternalStorageContainer.setVisibility(View.GONE);
151 
152             final View externalOption = mContentView.findViewById(R.id.erase_external_option_text);
153             externalOption.setVisibility(View.GONE);
154 
155             final View externalAlsoErased = mContentView.findViewById(R.id.also_erases_external);
156             externalAlsoErased.setVisibility(View.VISIBLE);
157 
158             // If it's not emulated, it is on a separate partition but it means we're doing
159             // a force wipe due to encryption.
160             mExternalStorage.setChecked(!isExtStorageEmulated);
161         } else {
162             mExternalStorageContainer.setOnClickListener(new View.OnClickListener() {
163 
164                 @Override
165                 public void onClick(View v) {
166                     mExternalStorage.toggle();
167                 }
168             });
169         }
170 
171         final UserManager um = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
172         loadAccountList(um);
173         StringBuffer contentDescription = new StringBuffer();
174         View masterClearContainer = mContentView.findViewById(R.id.master_clear_container);
175         getContentDescription(masterClearContainer, contentDescription);
176         masterClearContainer.setContentDescription(contentDescription);
177     }
178 
getContentDescription(View v, StringBuffer description)179     private void getContentDescription(View v, StringBuffer description) {
180        if (v.getVisibility() != View.VISIBLE) {
181            return;
182        }
183        if (v instanceof ViewGroup) {
184            ViewGroup vGroup = (ViewGroup) v;
185            for (int i = 0; i < vGroup.getChildCount(); i++) {
186                View nextChild = vGroup.getChildAt(i);
187                getContentDescription(nextChild, description);
188            }
189        } else if (v instanceof TextView) {
190            TextView vText = (TextView) v;
191            description.append(vText.getText());
192            description.append(","); // Allow Talkback to pause between sections.
193        }
194     }
195 
isExtStorageEncrypted()196     private boolean isExtStorageEncrypted() {
197         String state = SystemProperties.get("vold.decrypt");
198         return !"".equals(state);
199     }
200 
loadAccountList(final UserManager um)201     private void loadAccountList(final UserManager um) {
202         View accountsLabel = mContentView.findViewById(R.id.accounts_label);
203         LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts);
204         contents.removeAllViews();
205 
206         Context context = getActivity();
207         final List<UserInfo> profiles = um.getProfiles(UserHandle.myUserId());
208         final int profilesSize = profiles.size();
209 
210         AccountManager mgr = AccountManager.get(context);
211 
212         LayoutInflater inflater = (LayoutInflater)context.getSystemService(
213                 Context.LAYOUT_INFLATER_SERVICE);
214 
215         int accountsCount = 0;
216         for (int profileIndex = 0; profileIndex < profilesSize; profileIndex++) {
217             final UserInfo userInfo = profiles.get(profileIndex);
218             final int profileId = userInfo.id;
219             final UserHandle userHandle = new UserHandle(profileId);
220             Account[] accounts = mgr.getAccountsAsUser(profileId);
221             final int N = accounts.length;
222             if (N == 0) {
223                 continue;
224             }
225             accountsCount += N;
226 
227             AuthenticatorDescription[] descs = AccountManager.get(context)
228                     .getAuthenticatorTypesAsUser(profileId);
229             final int M = descs.length;
230 
231             View titleView = Utils.inflateCategoryHeader(inflater, contents);
232             final TextView titleText = (TextView) titleView.findViewById(android.R.id.title);
233             titleText.setText(userInfo.isManagedProfile() ? R.string.category_work
234                     : R.string.category_personal);
235             contents.addView(titleView);
236 
237             for (int i = 0; i < N; i++) {
238                 Account account = accounts[i];
239                 AuthenticatorDescription desc = null;
240                 for (int j = 0; j < M; j++) {
241                     if (account.type.equals(descs[j].type)) {
242                         desc = descs[j];
243                         break;
244                     }
245                 }
246                 if (desc == null) {
247                     Log.w(TAG, "No descriptor for account name=" + account.name
248                             + " type=" + account.type);
249                     continue;
250                 }
251                 Drawable icon = null;
252                 try {
253                     if (desc.iconId != 0) {
254                         Context authContext = context.createPackageContextAsUser(desc.packageName,
255                                 0, userHandle);
256                         icon = context.getPackageManager().getUserBadgedIcon(
257                                 authContext.getDrawable(desc.iconId), userHandle);
258                     }
259                 } catch (PackageManager.NameNotFoundException e) {
260                     Log.w(TAG, "Bad package name for account type " + desc.type);
261                 } catch (Resources.NotFoundException e) {
262                     Log.w(TAG, "Invalid icon id for account type " + desc.type, e);
263                 }
264                 if (icon == null) {
265                     icon = context.getPackageManager().getDefaultActivityIcon();
266                 }
267 
268                 TextView child = (TextView)inflater.inflate(R.layout.master_clear_account,
269                         contents, false);
270                 child.setText(account.name);
271                 child.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
272                 contents.addView(child);
273             }
274         }
275 
276         if (accountsCount > 0) {
277             accountsLabel.setVisibility(View.VISIBLE);
278             contents.setVisibility(View.VISIBLE);
279         }
280         // Checking for all other users and their profiles if any.
281         View otherUsers = mContentView.findViewById(R.id.other_users_present);
282         final boolean hasOtherUsers = (um.getUserCount() - profilesSize) > 0;
283         otherUsers.setVisibility(hasOtherUsers ? View.VISIBLE : View.GONE);
284     }
285 
286     @Override
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)287     public View onCreateView(LayoutInflater inflater, ViewGroup container,
288             Bundle savedInstanceState) {
289         final EnforcedAdmin admin = RestrictedLockUtils.checkIfRestrictionEnforced(
290                 getActivity(), UserManager.DISALLOW_FACTORY_RESET, UserHandle.myUserId());
291         final UserManager um = UserManager.get(getActivity());
292         if (!um.isAdminUser() || RestrictedLockUtils.hasBaseUserRestriction(getActivity(),
293                 UserManager.DISALLOW_FACTORY_RESET, UserHandle.myUserId())) {
294             return inflater.inflate(R.layout.master_clear_disallowed_screen, null);
295         } else if (admin != null) {
296             View view = inflater.inflate(R.layout.admin_support_details_empty_view, null);
297             ShowAdminSupportDetailsDialog.setAdminSupportDetails(getActivity(), view, admin, false);
298             view.setVisibility(View.VISIBLE);
299             return view;
300         }
301 
302         mContentView = inflater.inflate(R.layout.master_clear, null);
303 
304         establishInitialState();
305         return mContentView;
306     }
307 
308     @Override
getMetricsCategory()309     protected int getMetricsCategory() {
310         return MetricsEvent.MASTER_CLEAR;
311     }
312 }
313