• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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.tv.settings.system.development;
18 
19 import android.Manifest;
20 import android.app.Activity;
21 import android.app.ActivityManager;
22 import android.app.AppOpsManager;
23 import android.app.admin.DevicePolicyManager;
24 import android.app.backup.IBackupManager;
25 import android.bluetooth.BluetoothAdapter;
26 import android.content.BroadcastReceiver;
27 import android.content.ComponentName;
28 import android.content.ContentResolver;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.IntentFilter;
32 import android.content.pm.ApplicationInfo;
33 import android.content.pm.PackageManager;
34 import android.content.pm.ResolveInfo;
35 import android.hardware.usb.UsbManager;
36 import android.net.wifi.WifiManager;
37 import android.os.BatteryManager;
38 import android.os.Build;
39 import android.os.Bundle;
40 import android.os.IBinder;
41 import android.os.Parcel;
42 import android.os.RemoteException;
43 import android.os.ServiceManager;
44 import android.os.StrictMode;
45 import android.os.SystemProperties;
46 import android.os.UserManager;
47 import android.provider.Settings;
48 import android.service.persistentdata.PersistentDataBlockManager;
49 import android.support.v14.preference.SwitchPreference;
50 import android.support.v7.preference.ListPreference;
51 import android.support.v7.preference.Preference;
52 import android.support.v7.preference.PreferenceGroup;
53 import android.support.v7.preference.PreferenceScreen;
54 import android.text.TextUtils;
55 import android.util.Log;
56 import android.view.IWindowManager;
57 import android.view.LayoutInflater;
58 import android.view.ThreadedRenderer;
59 import android.view.View;
60 import android.view.ViewGroup;
61 import android.view.accessibility.AccessibilityManager;
62 import android.widget.Toast;
63 
64 import com.android.internal.app.LocalePicker;
65 import com.android.internal.logging.nano.MetricsProto;
66 import com.android.settingslib.core.ConfirmationDialogController;
67 import com.android.settingslib.development.DevelopmentSettingsEnabler;
68 import com.android.settingslib.development.SystemPropPoker;
69 import com.android.tv.settings.R;
70 import com.android.tv.settings.SettingsPreferenceFragment;
71 
72 import java.util.ArrayList;
73 import java.util.HashSet;
74 import java.util.List;
75 
76 /**
77  * Displays preferences for application developers.
78  */
79 public class DevelopmentFragment extends SettingsPreferenceFragment
80         implements Preference.OnPreferenceChangeListener,
81         EnableDevelopmentDialog.Callback, OemUnlockDialog.Callback, AdbDialog.Callback {
82     private static final String TAG = "DevelopmentSettings";
83 
84     private static final String ENABLE_DEVELOPER = "development_settings_enable";
85     private static final String ENABLE_ADB = "enable_adb";
86     private static final String CLEAR_ADB_KEYS = "clear_adb_keys";
87     private static final String ENABLE_TERMINAL = "enable_terminal";
88     private static final String KEEP_SCREEN_ON = "keep_screen_on";
89     private static final String BT_HCI_SNOOP_LOG = "bt_hci_snoop_log";
90     private static final String BTSNOOP_ENABLE_PROPERTY = "persist.bluetooth.btsnoopenable";
91     private static final String ENABLE_OEM_UNLOCK = "oem_unlock_enable";
92     private static final String HDCP_CHECKING_KEY = "hdcp_checking";
93     private static final String HDCP_CHECKING_PROPERTY = "persist.sys.hdcp_checking";
94     private static final String LOCAL_BACKUP_PASSWORD = "local_backup_password";
95     private static final String HARDWARE_UI_PROPERTY = "persist.sys.ui.hw";
96     private static final String MSAA_PROPERTY = "debug.egl.force_msaa";
97     private static final String BUGREPORT = "bugreport";
98     private static final String BUGREPORT_IN_POWER_KEY = "bugreport_in_power";
99     private static final String OPENGL_TRACES_PROPERTY = "debug.egl.trace";
100     private static final String RUNNING_APPS = "running_apps";
101 
102     private static final String DEBUG_APP_KEY = "debug_app";
103     private static final String WAIT_FOR_DEBUGGER_KEY = "wait_for_debugger";
104     private static final String MOCK_LOCATION_APP_KEY = "mock_location_app";
105     private static final String VERIFY_APPS_OVER_USB_KEY = "verify_apps_over_usb";
106     private static final String DEBUG_VIEW_ATTRIBUTES =  "debug_view_attributes";
107     private static final String FORCE_ALLOW_ON_EXTERNAL_KEY = "force_allow_on_external";
108     private static final String STRICT_MODE_KEY = "strict_mode";
109     private static final String POINTER_LOCATION_KEY = "pointer_location";
110     private static final String SHOW_TOUCHES_KEY = "show_touches";
111     private static final String SHOW_SCREEN_UPDATES_KEY = "show_screen_updates";
112     private static final String DISABLE_OVERLAYS_KEY = "disable_overlays";
113     private static final String SIMULATE_COLOR_SPACE = "simulate_color_space";
114     private static final String USB_AUDIO_KEY = "usb_audio";
115     private static final String FORCE_HARDWARE_UI_KEY = "force_hw_ui";
116     private static final String FORCE_MSAA_KEY = "force_msaa";
117     private static final String TRACK_FRAME_TIME_KEY = "track_frame_time";
118     private static final String SHOW_NON_RECTANGULAR_CLIP_KEY = "show_non_rect_clip";
119     private static final String SHOW_HW_SCREEN_UPDATES_KEY = "show_hw_screen_udpates";
120     private static final String SHOW_HW_LAYERS_UPDATES_KEY = "show_hw_layers_udpates";
121     private static final String DEBUG_HW_OVERDRAW_KEY = "debug_hw_overdraw";
122     private static final String DEBUG_LAYOUT_KEY = "debug_layout";
123     private static final String FORCE_RTL_LAYOUT_KEY = "force_rtl_layout_all_locales";
124     private static final String WINDOW_ANIMATION_SCALE_KEY = "window_animation_scale";
125     private static final String TRANSITION_ANIMATION_SCALE_KEY = "transition_animation_scale";
126     private static final String ANIMATOR_DURATION_SCALE_KEY = "animator_duration_scale";
127     private static final String OVERLAY_DISPLAY_DEVICES_KEY = "overlay_display_devices";
128     private static final String DEBUG_DEBUGGING_CATEGORY_KEY = "debug_debugging_category";
129 
130     private static final String WIFI_DISPLAY_CERTIFICATION_KEY = "wifi_display_certification";
131     private static final String WIFI_VERBOSE_LOGGING_KEY = "wifi_verbose_logging";
132     private static final String USB_CONFIGURATION_KEY = "select_usb_configuration";
133     private static final String MOBILE_DATA_ALWAYS_ON = "mobile_data_always_on";
134     private static final String KEY_COLOR_MODE = "color_mode";
135     private static final String FORCE_RESIZABLE_KEY = "force_resizable_activities";
136 
137     private static final String INACTIVE_APPS_KEY = "inactive_apps";
138 
139     private static final String OPENGL_TRACES_KEY = "enable_opengl_traces";
140 
141     private static final String IMMEDIATELY_DESTROY_ACTIVITIES_KEY
142             = "immediately_destroy_activities";
143     private static final String APP_PROCESS_LIMIT_KEY = "app_process_limit";
144 
145     private static final String SHOW_ALL_ANRS_KEY = "show_all_anrs";
146 
147     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
148 
149     private static final String TERMINAL_APP_PACKAGE = "com.android.terminal";
150 
151     private static final String KEY_CONVERT_FBE = "convert_to_file_encryption";
152 
153     private static final int RESULT_DEBUG_APP = 1000;
154     private static final int RESULT_MOCK_LOCATION_APP = 1001;
155 
156     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
157 
158     private static String DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES = "262144"; // 256K
159 
160     private static final int[] MOCK_LOCATION_APP_OPS = new int[] {AppOpsManager.OP_MOCK_LOCATION};
161 
162     private static final String STATE_SHOWING_DIALOG_KEY = "showing_dialog_key";
163 
164     private String mPendingDialogKey;
165 
166     private IWindowManager mWindowManager;
167     private IBackupManager mBackupManager;
168     private DevicePolicyManager mDpm;
169     private UserManager mUm;
170     private WifiManager mWifiManager;
171     private ContentResolver mContentResolver;
172 
173     private boolean mLastEnabledState;
174     private boolean mHaveDebugSettings;
175 
176     private SwitchPreference mEnableDeveloper;
177     private SwitchPreference mEnableAdb;
178     private Preference mClearAdbKeys;
179     private SwitchPreference mEnableTerminal;
180     private Preference mBugreport;
181     private SwitchPreference mKeepScreenOn;
182     private SwitchPreference mBtHciSnoopLog;
183     private SwitchPreference mEnableOemUnlock;
184     private SwitchPreference mDebugViewAttributes;
185     private SwitchPreference mForceAllowOnExternal;
186 
187     private PreferenceScreen mPassword;
188     private String mDebugApp;
189     private Preference mDebugAppPref;
190 
191     private String mMockLocationApp;
192     private Preference mMockLocationAppPref;
193 
194     private SwitchPreference mWaitForDebugger;
195     private SwitchPreference mVerifyAppsOverUsb;
196     private SwitchPreference mWifiDisplayCertification;
197     private SwitchPreference mWifiVerboseLogging;
198     private SwitchPreference mMobileDataAlwaysOn;
199 
200     private SwitchPreference mStrictMode;
201     private SwitchPreference mPointerLocation;
202     private SwitchPreference mShowTouches;
203     private SwitchPreference mShowScreenUpdates;
204     private SwitchPreference mDisableOverlays;
205     private SwitchPreference mForceHardwareUi;
206     private SwitchPreference mForceMsaa;
207     private SwitchPreference mShowHwScreenUpdates;
208     private SwitchPreference mShowHwLayersUpdates;
209     private SwitchPreference mDebugLayout;
210     private SwitchPreference mForceRtlLayout;
211     private ListPreference mDebugHwOverdraw;
212     private LogdSizePreferenceController mLogdSizeController;
213     private LogpersistPreferenceController mLogpersistController;
214     private ListPreference mUsbConfiguration;
215     private ListPreference mTrackFrameTime;
216     private ListPreference mShowNonRectClip;
217     private ListPreference mWindowAnimationScale;
218     private ListPreference mTransitionAnimationScale;
219     private ListPreference mAnimatorDurationScale;
220     private ListPreference mOverlayDisplayDevices;
221     private ListPreference mOpenGLTraces;
222 
223     private ListPreference mSimulateColorSpace;
224 
225     private SwitchPreference mUSBAudio;
226     private SwitchPreference mImmediatelyDestroyActivities;
227 
228     private ListPreference mAppProcessLimit;
229 
230     private SwitchPreference mShowAllANRs;
231 
232     private ColorModePreference mColorModePreference;
233 
234     private SwitchPreference mForceResizable;
235 
236     private final ArrayList<Preference> mAllPrefs = new ArrayList<>();
237 
238     private final ArrayList<SwitchPreference> mResetSwitchPrefs
239             = new ArrayList<>();
240 
241     private final HashSet<Preference> mDisabledPrefs = new HashSet<>();
242 
243     private boolean mUnavailable;
244 
newInstance()245     public static DevelopmentFragment newInstance() {
246         return new DevelopmentFragment();
247     }
248 
249     @Override
getMetricsCategory()250     public int getMetricsCategory() {
251         return MetricsProto.MetricsEvent.DEVELOPMENT;
252     }
253 
254     @Override
onCreate(Bundle icicle)255     public void onCreate(Bundle icicle) {
256 
257         if (icicle != null) {
258             // Don't show this in onCreate since we might be on the back stack
259             mPendingDialogKey = icicle.getString(STATE_SHOWING_DIALOG_KEY);
260         }
261 
262         mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
263         mBackupManager = IBackupManager.Stub.asInterface(
264                 ServiceManager.getService(Context.BACKUP_SERVICE));
265         mDpm = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
266         mUm = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
267 
268         mWifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
269 
270         mContentResolver = getActivity().getContentResolver();
271 
272         super.onCreate(icicle);
273     }
274 
275     @Override
onCreatePreferences(Bundle savedInstanceState, String rootKey)276     public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
277         mLogdSizeController = new LogdSizePreferenceController(getActivity());
278         mLogpersistController = new LogpersistPreferenceController(getActivity(), getLifecycle());
279 
280         if (!mUm.isAdminUser()
281                 || mUm.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES)
282                 || Settings.Global.getInt(mContentResolver,
283                 Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
284             // Block access to developer options if the user is not the owner, if user policy
285             // restricts it, or if the device has not been provisioned
286             mUnavailable = true;
287             addPreferencesFromResource(R.xml.development_prefs_not_available);
288             return;
289         }
290 
291         addPreferencesFromResource(R.xml.development_prefs);
292         final PreferenceScreen preferenceScreen = getPreferenceScreen();
293 
294         // Don't add to prefs lists or it'll disable itself when switched off
295         mEnableDeveloper = (SwitchPreference) findPreference(ENABLE_DEVELOPER);
296 
297         final PreferenceGroup debugDebuggingCategory = (PreferenceGroup)
298                 findPreference(DEBUG_DEBUGGING_CATEGORY_KEY);
299         mEnableAdb = findAndInitSwitchPref(ENABLE_ADB);
300         mClearAdbKeys = findPreference(CLEAR_ADB_KEYS);
301         if (!SystemProperties.getBoolean("ro.adb.secure", false)) {
302             if (debugDebuggingCategory != null) {
303                 debugDebuggingCategory.removePreference(mClearAdbKeys);
304             }
305         }
306         mAllPrefs.add(mClearAdbKeys);
307         mEnableTerminal = findAndInitSwitchPref(ENABLE_TERMINAL);
308         if (!isPackageInstalled(getActivity(), TERMINAL_APP_PACKAGE)) {
309             if (debugDebuggingCategory != null) {
310                 debugDebuggingCategory.removePreference(mEnableTerminal);
311             }
312             mEnableTerminal = null;
313         }
314 
315         mBugreport = findPreference(BUGREPORT);
316         mLogdSizeController.displayPreference(preferenceScreen);
317         mLogpersistController.displayPreference(preferenceScreen);
318 
319         mKeepScreenOn = findAndInitSwitchPref(KEEP_SCREEN_ON);
320         mBtHciSnoopLog = findAndInitSwitchPref(BT_HCI_SNOOP_LOG);
321         mEnableOemUnlock = findAndInitSwitchPref(ENABLE_OEM_UNLOCK);
322         if (!showEnableOemUnlockPreference()) {
323             removePreference(mEnableOemUnlock);
324             mEnableOemUnlock = null;
325         }
326 
327         // TODO: implement UI for TV
328         removePreference(RUNNING_APPS);
329 
330         mDebugViewAttributes = findAndInitSwitchPref(DEBUG_VIEW_ATTRIBUTES);
331         mForceAllowOnExternal = findAndInitSwitchPref(FORCE_ALLOW_ON_EXTERNAL_KEY);
332         mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD);
333         // We don't have a backup password activity on TV
334         mPassword.setVisible(false);
335         mAllPrefs.add(mPassword);
336 
337         if (!mUm.isAdminUser()) {
338             disableForUser(mEnableAdb);
339             disableForUser(mClearAdbKeys);
340             disableForUser(mEnableTerminal);
341             disableForUser(mPassword);
342         }
343 
344         mDebugAppPref = findPreference(DEBUG_APP_KEY);
345         mAllPrefs.add(mDebugAppPref);
346         mWaitForDebugger = findAndInitSwitchPref(WAIT_FOR_DEBUGGER_KEY);
347 
348         mMockLocationAppPref = findPreference(MOCK_LOCATION_APP_KEY);
349         mAllPrefs.add(mMockLocationAppPref);
350 
351         mVerifyAppsOverUsb = findAndInitSwitchPref(VERIFY_APPS_OVER_USB_KEY);
352         if (!showVerifierSetting()) {
353             if (debugDebuggingCategory != null) {
354                 debugDebuggingCategory.removePreference(mVerifyAppsOverUsb);
355             } else {
356                 mVerifyAppsOverUsb.setEnabled(false);
357             }
358         }
359         mStrictMode = findAndInitSwitchPref(STRICT_MODE_KEY);
360         mPointerLocation = findAndInitSwitchPref(POINTER_LOCATION_KEY);
361         mShowTouches = findAndInitSwitchPref(SHOW_TOUCHES_KEY);
362         mShowScreenUpdates = findAndInitSwitchPref(SHOW_SCREEN_UPDATES_KEY);
363         mDisableOverlays = findAndInitSwitchPref(DISABLE_OVERLAYS_KEY);
364         mForceHardwareUi = findAndInitSwitchPref(FORCE_HARDWARE_UI_KEY);
365         mForceMsaa = findAndInitSwitchPref(FORCE_MSAA_KEY);
366         mTrackFrameTime = addListPreference(TRACK_FRAME_TIME_KEY);
367         mShowNonRectClip = addListPreference(SHOW_NON_RECTANGULAR_CLIP_KEY);
368         mShowHwScreenUpdates = findAndInitSwitchPref(SHOW_HW_SCREEN_UPDATES_KEY);
369         mShowHwLayersUpdates = findAndInitSwitchPref(SHOW_HW_LAYERS_UPDATES_KEY);
370         mDebugLayout = findAndInitSwitchPref(DEBUG_LAYOUT_KEY);
371         mForceRtlLayout = findAndInitSwitchPref(FORCE_RTL_LAYOUT_KEY);
372         mDebugHwOverdraw = addListPreference(DEBUG_HW_OVERDRAW_KEY);
373         mWifiDisplayCertification = findAndInitSwitchPref(WIFI_DISPLAY_CERTIFICATION_KEY);
374         mWifiVerboseLogging = findAndInitSwitchPref(WIFI_VERBOSE_LOGGING_KEY);
375         mMobileDataAlwaysOn = findAndInitSwitchPref(MOBILE_DATA_ALWAYS_ON);
376         mUsbConfiguration = addListPreference(USB_CONFIGURATION_KEY);
377 
378         mWindowAnimationScale = addListPreference(WINDOW_ANIMATION_SCALE_KEY);
379         mTransitionAnimationScale = addListPreference(TRANSITION_ANIMATION_SCALE_KEY);
380         mAnimatorDurationScale = addListPreference(ANIMATOR_DURATION_SCALE_KEY);
381         mOverlayDisplayDevices = addListPreference(OVERLAY_DISPLAY_DEVICES_KEY);
382         mOpenGLTraces = addListPreference(OPENGL_TRACES_KEY);
383         mSimulateColorSpace = addListPreference(SIMULATE_COLOR_SPACE);
384         mUSBAudio = findAndInitSwitchPref(USB_AUDIO_KEY);
385         mForceResizable = findAndInitSwitchPref(FORCE_RESIZABLE_KEY);
386 
387         mImmediatelyDestroyActivities = (SwitchPreference) findPreference(
388                 IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
389         mAllPrefs.add(mImmediatelyDestroyActivities);
390         mResetSwitchPrefs.add(mImmediatelyDestroyActivities);
391 
392         mAppProcessLimit = addListPreference(APP_PROCESS_LIMIT_KEY);
393 
394         mShowAllANRs = (SwitchPreference) findPreference(
395                 SHOW_ALL_ANRS_KEY);
396         mAllPrefs.add(mShowAllANRs);
397         mResetSwitchPrefs.add(mShowAllANRs);
398 
399         Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY);
400         if (hdcpChecking != null) {
401             mAllPrefs.add(hdcpChecking);
402             removePreferenceForProduction(hdcpChecking);
403         }
404 
405         // TODO: implement UI for TV
406         removePreference(KEY_CONVERT_FBE);
407 /*
408         PreferenceScreen convertFbePreference =
409                 (PreferenceScreen) findPreference(KEY_CONVERT_FBE);
410 
411         try {
412             IBinder service = ServiceManager.getService("mount");
413             IMountService mountService = IMountService.Stub.asInterface(service);
414             if (!mountService.isConvertibleToFBE()) {
415                 removePreference(KEY_CONVERT_FBE);
416             } else if ("file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
417                 convertFbePreference.setEnabled(false);
418                 convertFbePreference.setSummary(getResources()
419                         .getString(R.string.convert_to_file_encryption_done));
420             }
421         } catch(RemoteException e) {
422             removePreference(KEY_CONVERT_FBE);
423         }
424 */
425 
426         mColorModePreference = (ColorModePreference) findPreference(KEY_COLOR_MODE);
427         mColorModePreference.updateCurrentAndSupported();
428         if (mColorModePreference.getColorModeCount() < 2) {
429             removePreference(KEY_COLOR_MODE);
430             mColorModePreference = null;
431         }
432     }
433 
removePreference(String key)434     private void removePreference(String key) {
435         final Preference preference = findPreference(key);
436         if (preference != null) {
437             getPreferenceScreen().removePreference(preference);
438         }
439     }
440 
addListPreference(String prefKey)441     private ListPreference addListPreference(String prefKey) {
442         ListPreference pref = (ListPreference) findPreference(prefKey);
443         mAllPrefs.add(pref);
444         pref.setOnPreferenceChangeListener(this);
445         return pref;
446     }
447 
disableForUser(Preference pref)448     private void disableForUser(Preference pref) {
449         if (pref != null) {
450             pref.setEnabled(false);
451             mDisabledPrefs.add(pref);
452         }
453     }
454 
findAndInitSwitchPref(String key)455     private SwitchPreference findAndInitSwitchPref(String key) {
456         SwitchPreference pref = (SwitchPreference) findPreference(key);
457         if (pref == null) {
458             throw new IllegalArgumentException("Cannot find preference with key = " + key);
459         }
460         mAllPrefs.add(pref);
461         mResetSwitchPrefs.add(pref);
462         return pref;
463     }
464 
465     @Override
onActivityCreated(Bundle savedInstanceState)466     public void onActivityCreated(Bundle savedInstanceState) {
467         super.onActivityCreated(savedInstanceState);
468 
469         if (mUnavailable) {
470             if (mEnableDeveloper != null) {
471                 mEnableDeveloper.setEnabled(false);
472             }
473         }
474     }
475 
removePreferenceForProduction(Preference preference)476     private boolean removePreferenceForProduction(Preference preference) {
477         if ("user".equals(Build.TYPE)) {
478             removePreference(preference);
479             return true;
480         }
481         return false;
482     }
483 
removePreference(Preference preference)484     private void removePreference(Preference preference) {
485         getPreferenceScreen().removePreference(preference);
486         mAllPrefs.remove(preference);
487         mResetSwitchPrefs.remove(preference);
488     }
489 
setPrefsEnabledState(boolean enabled)490     private void setPrefsEnabledState(boolean enabled) {
491         for (final Preference pref : mAllPrefs) {
492             pref.setEnabled(enabled && !mDisabledPrefs.contains(pref));
493         }
494         mLogdSizeController.enablePreference(enabled);
495         mLogpersistController.enablePreference(enabled);
496         updateAllOptions();
497     }
498 
499     @Override
onResume()500     public void onResume() {
501         super.onResume();
502 
503         if (mUnavailable) {
504             return;
505         }
506 
507         if (mDpm.getMaximumTimeToLock(null) > 0) {
508             // A DeviceAdmin has specified a maximum time until the device
509             // will lock...  in this case we can't allow the user to turn
510             // on "stay awake when plugged in" because that would defeat the
511             // restriction.
512             mDisabledPrefs.add(mKeepScreenOn);
513         } else {
514             mDisabledPrefs.remove(mKeepScreenOn);
515         }
516 
517         mLastEnabledState = DevelopmentSettingsEnabler.isDevelopmentSettingsEnabled(getContext());
518         mEnableDeveloper.setChecked(mLastEnabledState);
519         setPrefsEnabledState(mLastEnabledState);
520 
521         if (mHaveDebugSettings && !mLastEnabledState) {
522             // Overall debugging is disabled, but there are some debug
523             // settings that are enabled.  This is an invalid state.  Switch
524             // to debug settings being enabled, so the user knows there is
525             // stuff enabled and can turn it all off if they want.
526             DevelopmentSettingsEnabler.setDevelopmentSettingsEnabled(getContext(), true);
527             mLastEnabledState = true;
528             mEnableDeveloper.setChecked(mLastEnabledState);
529             setPrefsEnabledState(mLastEnabledState);
530         }
531 
532         if (mColorModePreference != null) {
533             mColorModePreference.startListening();
534             mColorModePreference.updateCurrentAndSupported();
535         }
536 
537         if (mPendingDialogKey != null) {
538             recreateDialogForKey(mPendingDialogKey);
539             mPendingDialogKey = null;
540         }
541     }
542 
543     @Override
onPause()544     public void onPause() {
545         super.onPause();
546         if (mColorModePreference != null) {
547             mColorModePreference.stopListening();
548         }
549     }
550 
551     @Override
onSaveInstanceState(Bundle outState)552     public void onSaveInstanceState(Bundle outState) {
553         super.onSaveInstanceState(outState);
554         outState.putString(STATE_SHOWING_DIALOG_KEY, getKeyForShowingDialog());
555     }
556 
557     @Override
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)558     public View onCreateView(LayoutInflater inflater, ViewGroup container,
559             Bundle savedInstanceState) {
560         IntentFilter filter = new IntentFilter();
561         filter.addAction(UsbManager.ACTION_USB_STATE);
562         if (getActivity().registerReceiver(mUsbReceiver, filter) == null) {
563             updateUsbConfigurationValues();
564         }
565         return super.onCreateView(inflater, container, savedInstanceState);
566     }
567 
568     @Override
onDestroyView()569     public void onDestroyView() {
570         super.onDestroyView();
571 
572         getActivity().unregisterReceiver(mUsbReceiver);
573     }
574 
575     @Override
onDestroy()576     public void onDestroy() {
577         super.onDestroy();
578         dismissDialogs();
579     }
580 
updateSwitchPreference(SwitchPreference switchPreference, boolean value)581     void updateSwitchPreference(SwitchPreference switchPreference, boolean value) {
582         switchPreference.setChecked(value);
583         mHaveDebugSettings |= value;
584     }
585 
updateAllOptions()586     private void updateAllOptions() {
587         final Context context = getActivity();
588         final ContentResolver cr = context.getContentResolver();
589         mHaveDebugSettings = false;
590         updateSwitchPreference(mEnableAdb, Settings.Global.getInt(cr,
591                 Settings.Global.ADB_ENABLED, 0) != 0);
592         if (mEnableTerminal != null) {
593             updateSwitchPreference(mEnableTerminal,
594                     context.getPackageManager().getApplicationEnabledSetting(TERMINAL_APP_PACKAGE)
595                             == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
596         }
597         updateSwitchPreference(mKeepScreenOn, Settings.Global.getInt(cr,
598                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0) != 0);
599         updateSwitchPreference(mBtHciSnoopLog,
600                 SystemProperties.getBoolean(BTSNOOP_ENABLE_PROPERTY, false));
601         if (mEnableOemUnlock != null) {
602             updateSwitchPreference(mEnableOemUnlock, isOemUnlockEnabled(getActivity()));
603             mEnableOemUnlock.setEnabled(isOemUnlockAllowed());
604         }
605         updateSwitchPreference(mDebugViewAttributes, Settings.Global.getInt(cr,
606                 Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0);
607         updateSwitchPreference(mForceAllowOnExternal, Settings.Global.getInt(cr,
608                 Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0);
609         updateHdcpValues();
610         updatePasswordSummary();
611         updateDebuggerOptions();
612         updateMockLocation();
613         updateStrictModeVisualOptions();
614         updatePointerLocationOptions();
615         updateShowTouchesOptions();
616         updateFlingerOptions();
617         updateHardwareUiOptions();
618         updateMsaaOptions();
619         updateTrackFrameTimeOptions();
620         updateShowNonRectClipOptions();
621         updateShowHwScreenUpdatesOptions();
622         updateShowHwLayersUpdatesOptions();
623         updateDebugHwOverdrawOptions();
624         updateDebugLayoutOptions();
625         updateAnimationScaleOptions();
626         updateOverlayDisplayDevicesOptions();
627         updateOpenGLTracesOptions();
628         updateImmediatelyDestroyActivitiesOptions();
629         updateAppProcessLimitOptions();
630         updateShowAllANRsOptions();
631         updateVerifyAppsOverUsbOptions();
632         updateBugreportOptions();
633         updateForceRtlOptions();
634         mLogdSizeController.updateLogdSizeValues();
635         mLogpersistController.updateLogpersistValues();
636         updateWifiDisplayCertificationOptions();
637         updateWifiVerboseLoggingOptions();
638         updateMobileDataAlwaysOnOptions();
639         updateSimulateColorSpace();
640         updateUSBAudioOptions();
641         updateForceResizableOptions();
642     }
643 
resetDangerousOptions()644     private void resetDangerousOptions() {
645         SystemPropPoker.getInstance().blockPokes();
646         for (final SwitchPreference cb : mResetSwitchPrefs) {
647             if (cb.isChecked()) {
648                 cb.setChecked(false);
649                 onPreferenceTreeClick(cb);
650             }
651         }
652         resetDebuggerOptions();
653         mLogpersistController.writeLogpersistOption(null, true);
654         mLogdSizeController.writeLogdSizeOption(null);
655         writeAnimationScaleOption(0, mWindowAnimationScale, null);
656         writeAnimationScaleOption(1, mTransitionAnimationScale, null);
657         writeAnimationScaleOption(2, mAnimatorDurationScale, null);
658         // Only poke the color space setting if we control it.
659         if (usingDevelopmentColorSpace()) {
660             writeSimulateColorSpace(-1);
661         }
662         writeOverlayDisplayDevicesOptions(null);
663         writeAppProcessLimitOptions(null);
664         mHaveDebugSettings = false;
665         updateAllOptions();
666         SystemPropPoker.getInstance().unblockPokes();
667         SystemPropPoker.getInstance().poke();
668     }
669 
updateHdcpValues()670     private void updateHdcpValues() {
671         ListPreference hdcpChecking = (ListPreference) findPreference(HDCP_CHECKING_KEY);
672         if (hdcpChecking != null) {
673             String currentValue = SystemProperties.get(HDCP_CHECKING_PROPERTY);
674             String[] values = getResources().getStringArray(R.array.hdcp_checking_values);
675             String[] summaries = getResources().getStringArray(R.array.hdcp_checking_summaries);
676             int index = 1; // Defaults to drm-only. Needs to match with R.array.hdcp_checking_values
677             for (int i = 0; i < values.length; i++) {
678                 if (currentValue.equals(values[i])) {
679                     index = i;
680                     break;
681                 }
682             }
683             hdcpChecking.setValue(values[index]);
684             hdcpChecking.setSummary(summaries[index]);
685             hdcpChecking.setOnPreferenceChangeListener(this);
686         }
687     }
688 
updatePasswordSummary()689     private void updatePasswordSummary() {
690         try {
691             if (mBackupManager.hasBackupPassword()) {
692                 mPassword.setSummary(R.string.local_backup_password_summary_change);
693             } else {
694                 mPassword.setSummary(R.string.local_backup_password_summary_none);
695             }
696         } catch (RemoteException e) {
697             // ignore
698         }
699     }
700 
writeBtHciSnoopLogOptions()701     private void writeBtHciSnoopLogOptions() {
702         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
703         SystemProperties.set(BTSNOOP_ENABLE_PROPERTY,
704                 Boolean.toString(mBtHciSnoopLog.isChecked()));
705     }
706 
writeDebuggerOptions()707     private void writeDebuggerOptions() {
708         try {
709             ActivityManager.getService().setDebugApp(
710                     mDebugApp, mWaitForDebugger.isChecked(), true);
711         } catch (RemoteException ex) {
712             // ignore
713         }
714     }
715 
writeMockLocation()716     private void writeMockLocation() {
717         AppOpsManager appOpsManager =
718                 (AppOpsManager) getActivity().getSystemService(Context.APP_OPS_SERVICE);
719 
720         // Disable the app op of the previous mock location app if such.
721         List<AppOpsManager.PackageOps> packageOps =
722                 appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
723         if (packageOps != null) {
724             // Should be one but in case we are in a bad state due to use of command line tools.
725             for (AppOpsManager.PackageOps packageOp : packageOps) {
726                 if (packageOp.getOps().get(0).getMode() != AppOpsManager.MODE_ERRORED) {
727                     String oldMockLocationApp = packageOp.getPackageName();
728                     try {
729                         ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
730                                 oldMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
731                         appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
732                                 oldMockLocationApp, AppOpsManager.MODE_ERRORED);
733                     } catch (PackageManager.NameNotFoundException e) {
734                         /* ignore */
735                     }
736                 }
737             }
738         }
739 
740         // Enable the app op of the new mock location app if such.
741         if (!TextUtils.isEmpty(mMockLocationApp)) {
742             try {
743                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
744                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
745                 appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
746                         mMockLocationApp, AppOpsManager.MODE_ALLOWED);
747             } catch (PackageManager.NameNotFoundException e) {
748                 /* ignore */
749             }
750         }
751     }
752 
resetDebuggerOptions()753     private static void resetDebuggerOptions() {
754         try {
755             ActivityManager.getService().setDebugApp(
756                     null, false, true);
757         } catch (RemoteException ex) {
758             // ignore
759         }
760     }
761 
updateDebuggerOptions()762     private void updateDebuggerOptions() {
763         mDebugApp = Settings.Global.getString(mContentResolver, Settings.Global.DEBUG_APP);
764         updateSwitchPreference(mWaitForDebugger, Settings.Global.getInt(mContentResolver,
765                 Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0);
766         if (mDebugApp != null && mDebugApp.length() > 0) {
767             String label;
768             try {
769                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mDebugApp,
770                         PackageManager.GET_DISABLED_COMPONENTS);
771                 CharSequence lab = getActivity().getPackageManager().getApplicationLabel(ai);
772                 label = lab != null ? lab.toString() : mDebugApp;
773             } catch (PackageManager.NameNotFoundException e) {
774                 label = mDebugApp;
775             }
776             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_set, label));
777             mWaitForDebugger.setEnabled(true);
778             mHaveDebugSettings = true;
779         } else {
780             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_not_set));
781             mWaitForDebugger.setEnabled(false);
782         }
783     }
784 
updateMockLocation()785     private void updateMockLocation() {
786         AppOpsManager appOpsManager =
787                 (AppOpsManager) getActivity().getSystemService(Context.APP_OPS_SERVICE);
788 
789         List<AppOpsManager.PackageOps> packageOps =
790                 appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
791         if (packageOps != null) {
792             for (AppOpsManager.PackageOps packageOp : packageOps) {
793                 if (packageOp.getOps().get(0).getMode() == AppOpsManager.MODE_ALLOWED) {
794                     mMockLocationApp = packageOps.get(0).getPackageName();
795                     break;
796                 }
797             }
798         }
799 
800         if (!TextUtils.isEmpty(mMockLocationApp)) {
801             String label = mMockLocationApp;
802             try {
803                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
804                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
805                 CharSequence appLabel = getActivity().getPackageManager().getApplicationLabel(ai);
806                 if (appLabel != null) {
807                     label = appLabel.toString();
808                 }
809             } catch (PackageManager.NameNotFoundException e) {
810                 /* ignore */
811             }
812 
813             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_set, label));
814             mHaveDebugSettings = true;
815         } else {
816             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_not_set));
817         }
818     }
819 
updateVerifyAppsOverUsbOptions()820     private void updateVerifyAppsOverUsbOptions() {
821         updateSwitchPreference(mVerifyAppsOverUsb,
822                 Settings.Global.getInt(mContentResolver,
823                 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0);
824         mVerifyAppsOverUsb.setEnabled(enableVerifierSetting());
825     }
826 
writeVerifyAppsOverUsbOptions()827     private void writeVerifyAppsOverUsbOptions() {
828         Settings.Global.putInt(mContentResolver, Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
829                 mVerifyAppsOverUsb.isChecked() ? 1 : 0);
830     }
831 
enableVerifierSetting()832     private boolean enableVerifierSetting() {
833         if (Settings.Global.getInt(mContentResolver, Settings.Global.ADB_ENABLED, 0) == 0) {
834             return false;
835         }
836         if (Settings.Global.getInt(mContentResolver,
837                 Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 0) {
838             return false;
839         } else {
840             final PackageManager pm = getActivity().getPackageManager();
841             final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
842             verification.setType(PACKAGE_MIME_TYPE);
843             verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
844             final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(verification, 0);
845             if (receivers.size() == 0) {
846                 return false;
847             }
848         }
849         return true;
850     }
851 
showVerifierSetting()852     private boolean showVerifierSetting() {
853         return Settings.Global.getInt(mContentResolver,
854                 Settings.Global.PACKAGE_VERIFIER_SETTING_VISIBLE, 1) > 0;
855     }
856 
showEnableOemUnlockPreference()857     private static boolean showEnableOemUnlockPreference() {
858         return !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
859     }
860 
isOemUnlockAllowed()861     private boolean isOemUnlockAllowed() {
862         return !mUm.hasUserRestriction(UserManager.DISALLOW_OEM_UNLOCK);
863     }
864 
updateBugreportOptions()865     private void updateBugreportOptions() {
866         boolean enabled = "1".equals(SystemProperties.get("ro.debuggable"))
867                 || mEnableDeveloper.isChecked();
868         mBugreport.setEnabled(enabled);
869         final ComponentName componentName = new ComponentName("com.android.shell",
870                 "com.android.shell.BugreportStorageProvider");
871         getActivity().getPackageManager().setComponentEnabledSetting(componentName,
872                 enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
873                         : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
874                 0);
875     }
876 
captureBugReport()877     private void captureBugReport() {
878         Toast.makeText(getActivity(), R.string.capturing_bugreport, Toast.LENGTH_SHORT).show();
879         try {
880             ActivityManager.getService()
881                     .requestBugReport(ActivityManager.BUGREPORT_OPTION_FULL);
882         } catch (RemoteException e) {
883             Log.e(TAG, "Error taking bugreport", e);
884         }
885     }
886 
887     // Returns the current state of the system property that controls
888     // strictmode flashes.  One of:
889     //    0: not explicitly set one way or another
890     //    1: on
891     //    2: off
currentStrictModeActiveIndex()892     private static int currentStrictModeActiveIndex() {
893         if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) {
894             return 0;
895         }
896         boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false);
897         return enabled ? 1 : 2;
898     }
899 
writeStrictModeVisualOptions()900     private void writeStrictModeVisualOptions() {
901         try {
902             mWindowManager.setStrictModeVisualIndicatorPreference(mStrictMode.isChecked()
903                     ? "1" : "");
904         } catch (RemoteException e) {
905             // ignore
906         }
907     }
908 
updateStrictModeVisualOptions()909     private void updateStrictModeVisualOptions() {
910         updateSwitchPreference(mStrictMode, currentStrictModeActiveIndex() == 1);
911     }
912 
writePointerLocationOptions()913     private void writePointerLocationOptions() {
914         Settings.System.putInt(mContentResolver,
915                 Settings.System.POINTER_LOCATION, mPointerLocation.isChecked() ? 1 : 0);
916     }
917 
updatePointerLocationOptions()918     private void updatePointerLocationOptions() {
919         updateSwitchPreference(mPointerLocation,
920                 Settings.System.getInt(mContentResolver, Settings.System.POINTER_LOCATION, 0) != 0);
921     }
922 
writeShowTouchesOptions()923     private void writeShowTouchesOptions() {
924         Settings.System.putInt(mContentResolver,
925                 Settings.System.SHOW_TOUCHES, mShowTouches.isChecked() ? 1 : 0);
926     }
927 
updateShowTouchesOptions()928     private void updateShowTouchesOptions() {
929         updateSwitchPreference(mShowTouches,
930                 Settings.System.getInt(mContentResolver, Settings.System.SHOW_TOUCHES, 0) != 0);
931     }
932 
updateFlingerOptions()933     private void updateFlingerOptions() {
934         // magic communication with surface flinger.
935         try {
936             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
937             if (flinger != null) {
938                 Parcel data = Parcel.obtain();
939                 Parcel reply = Parcel.obtain();
940                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
941                 flinger.transact(1010, data, reply, 0);
942                 @SuppressWarnings("unused")
943                 int showCpu = reply.readInt();
944                 @SuppressWarnings("unused")
945                 int enableGL = reply.readInt();
946                 int showUpdates = reply.readInt();
947                 updateSwitchPreference(mShowScreenUpdates, showUpdates != 0);
948                 @SuppressWarnings("unused")
949                 int showBackground = reply.readInt();
950                 int disableOverlays = reply.readInt();
951                 updateSwitchPreference(mDisableOverlays, disableOverlays != 0);
952                 reply.recycle();
953                 data.recycle();
954             }
955         } catch (RemoteException ex) {
956             // ignore
957         }
958     }
959 
writeShowUpdatesOption()960     private void writeShowUpdatesOption() {
961         try {
962             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
963             if (flinger != null) {
964                 Parcel data = Parcel.obtain();
965                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
966                 final int showUpdates = mShowScreenUpdates.isChecked() ? 1 : 0;
967                 data.writeInt(showUpdates);
968                 flinger.transact(1002, data, null, 0);
969                 data.recycle();
970 
971                 updateFlingerOptions();
972             }
973         } catch (RemoteException ex) {
974             // ignore
975         }
976     }
977 
writeDisableOverlaysOption()978     private void writeDisableOverlaysOption() {
979         try {
980             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
981             if (flinger != null) {
982                 Parcel data = Parcel.obtain();
983                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
984                 final int disableOverlays = mDisableOverlays.isChecked() ? 1 : 0;
985                 data.writeInt(disableOverlays);
986                 flinger.transact(1008, data, null, 0);
987                 data.recycle();
988 
989                 updateFlingerOptions();
990             }
991         } catch (RemoteException ex) {
992             // ignore
993         }
994     }
995 
updateHardwareUiOptions()996     private void updateHardwareUiOptions() {
997         updateSwitchPreference(mForceHardwareUi,
998                 SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false));
999     }
1000 
writeHardwareUiOptions()1001     private void writeHardwareUiOptions() {
1002         SystemProperties.set(HARDWARE_UI_PROPERTY, mForceHardwareUi.isChecked() ? "true" : "false");
1003         SystemPropPoker.getInstance().poke();
1004     }
1005 
updateMsaaOptions()1006     private void updateMsaaOptions() {
1007         updateSwitchPreference(mForceMsaa, SystemProperties.getBoolean(MSAA_PROPERTY, false));
1008     }
1009 
writeMsaaOptions()1010     private void writeMsaaOptions() {
1011         SystemProperties.set(MSAA_PROPERTY, mForceMsaa.isChecked() ? "true" : "false");
1012         SystemPropPoker.getInstance().poke();
1013     }
1014 
updateTrackFrameTimeOptions()1015     private void updateTrackFrameTimeOptions() {
1016         String value = SystemProperties.get(ThreadedRenderer.PROFILE_PROPERTY);
1017         if (value == null) {
1018             value = "";
1019         }
1020 
1021         CharSequence[] values = mTrackFrameTime.getEntryValues();
1022         for (int i = 0; i < values.length; i++) {
1023             if (value.contentEquals(values[i])) {
1024                 mTrackFrameTime.setValueIndex(i);
1025                 mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[i]);
1026                 return;
1027             }
1028         }
1029         mTrackFrameTime.setValueIndex(0);
1030         mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[0]);
1031     }
1032 
writeTrackFrameTimeOptions(Object newValue)1033     private void writeTrackFrameTimeOptions(Object newValue) {
1034         SystemProperties.set(ThreadedRenderer.PROFILE_PROPERTY,
1035                 newValue == null ? "" : newValue.toString());
1036         SystemPropPoker.getInstance().poke();
1037         updateTrackFrameTimeOptions();
1038     }
1039 
updateShowNonRectClipOptions()1040     private void updateShowNonRectClipOptions() {
1041         String value = SystemProperties.get(
1042                 ThreadedRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY);
1043         if (value == null) {
1044             value = "hide";
1045         }
1046 
1047         CharSequence[] values = mShowNonRectClip.getEntryValues();
1048         for (int i = 0; i < values.length; i++) {
1049             if (value.contentEquals(values[i])) {
1050                 mShowNonRectClip.setValueIndex(i);
1051                 mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[i]);
1052                 return;
1053             }
1054         }
1055         mShowNonRectClip.setValueIndex(0);
1056         mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[0]);
1057     }
1058 
writeShowNonRectClipOptions(Object newValue)1059     private void writeShowNonRectClipOptions(Object newValue) {
1060         SystemProperties.set(ThreadedRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY,
1061                 newValue == null ? "" : newValue.toString());
1062         SystemPropPoker.getInstance().poke();
1063         updateShowNonRectClipOptions();
1064     }
1065 
updateShowHwScreenUpdatesOptions()1066     private void updateShowHwScreenUpdatesOptions() {
1067         updateSwitchPreference(mShowHwScreenUpdates,
1068                 SystemProperties.getBoolean(ThreadedRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, false));
1069     }
1070 
writeShowHwScreenUpdatesOptions()1071     private void writeShowHwScreenUpdatesOptions() {
1072         SystemProperties.set(ThreadedRenderer.DEBUG_DIRTY_REGIONS_PROPERTY,
1073                 mShowHwScreenUpdates.isChecked() ? "true" : null);
1074         SystemPropPoker.getInstance().poke();
1075     }
1076 
updateShowHwLayersUpdatesOptions()1077     private void updateShowHwLayersUpdatesOptions() {
1078         updateSwitchPreference(mShowHwLayersUpdates, SystemProperties.getBoolean(
1079                 ThreadedRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY, false));
1080     }
1081 
writeShowHwLayersUpdatesOptions()1082     private void writeShowHwLayersUpdatesOptions() {
1083         SystemProperties.set(ThreadedRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY,
1084                 mShowHwLayersUpdates.isChecked() ? "true" : null);
1085         SystemPropPoker.getInstance().poke();
1086     }
1087 
updateDebugHwOverdrawOptions()1088     private void updateDebugHwOverdrawOptions() {
1089         String value = SystemProperties.get(ThreadedRenderer.DEBUG_OVERDRAW_PROPERTY);
1090         if (value == null) {
1091             value = "";
1092         }
1093 
1094         CharSequence[] values = mDebugHwOverdraw.getEntryValues();
1095         for (int i = 0; i < values.length; i++) {
1096             if (value.contentEquals(values[i])) {
1097                 mDebugHwOverdraw.setValueIndex(i);
1098                 mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[i]);
1099                 return;
1100             }
1101         }
1102         mDebugHwOverdraw.setValueIndex(0);
1103         mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[0]);
1104     }
1105 
writeDebugHwOverdrawOptions(Object newValue)1106     private void writeDebugHwOverdrawOptions(Object newValue) {
1107         SystemProperties.set(ThreadedRenderer.DEBUG_OVERDRAW_PROPERTY,
1108                 newValue == null ? "" : newValue.toString());
1109         SystemPropPoker.getInstance().poke();
1110         updateDebugHwOverdrawOptions();
1111     }
1112 
updateDebugLayoutOptions()1113     private void updateDebugLayoutOptions() {
1114         updateSwitchPreference(mDebugLayout,
1115                 SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false));
1116     }
1117 
writeDebugLayoutOptions()1118     private void writeDebugLayoutOptions() {
1119         SystemProperties.set(View.DEBUG_LAYOUT_PROPERTY,
1120                 mDebugLayout.isChecked() ? "true" : "false");
1121         SystemPropPoker.getInstance().poke();
1122     }
1123 
updateSimulateColorSpace()1124     private void updateSimulateColorSpace() {
1125         final boolean enabled = Settings.Secure.getInt(
1126                 mContentResolver, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1127         if (enabled) {
1128             final String mode = Integer.toString(Settings.Secure.getInt(
1129                     mContentResolver, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1130                     AccessibilityManager.DALTONIZER_DISABLED));
1131             mSimulateColorSpace.setValue(mode);
1132             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1133             if (index < 0) {
1134                 // We're using a mode controlled by accessibility preferences.
1135                 mSimulateColorSpace.setSummary(getString(R.string.daltonizer_type_overridden,
1136                         getString(R.string.accessibility_display_daltonizer_preference_title)));
1137             } else {
1138                 mSimulateColorSpace.setSummary("%s");
1139             }
1140         } else {
1141             mSimulateColorSpace.setValue(
1142                     Integer.toString(AccessibilityManager.DALTONIZER_DISABLED));
1143         }
1144     }
1145 
1146     /**
1147      * @return <code>true</code> if the color space preference is currently
1148      *         controlled by development settings
1149      */
usingDevelopmentColorSpace()1150     private boolean usingDevelopmentColorSpace() {
1151         final boolean enabled = Settings.Secure.getInt(
1152                 mContentResolver, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1153         if (enabled) {
1154             final String mode = Integer.toString(Settings.Secure.getInt(
1155                     mContentResolver, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1156                     AccessibilityManager.DALTONIZER_DISABLED));
1157             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1158             if (index >= 0) {
1159                 // We're using a mode controlled by developer preferences.
1160                 return true;
1161             }
1162         }
1163         return false;
1164     }
1165 
writeSimulateColorSpace(Object value)1166     private void writeSimulateColorSpace(Object value) {
1167         final int newMode = Integer.parseInt(value.toString());
1168         if (newMode < 0) {
1169             Settings.Secure.putInt(mContentResolver,
1170                     Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0);
1171         } else {
1172             Settings.Secure.putInt(mContentResolver,
1173                     Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 1);
1174             Settings.Secure.putInt(mContentResolver,
1175                     Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, newMode);
1176         }
1177     }
1178 
updateUSBAudioOptions()1179     private void updateUSBAudioOptions() {
1180         updateSwitchPreference(mUSBAudio, Settings.Secure.getInt(mContentResolver,
1181                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED, 0) != 0);
1182     }
1183 
writeUSBAudioOptions()1184     private void writeUSBAudioOptions() {
1185         Settings.Secure.putInt(mContentResolver,
1186                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED,
1187                 mUSBAudio.isChecked() ? 1 : 0);
1188     }
1189 
updateForceResizableOptions()1190     private void updateForceResizableOptions() {
1191         updateSwitchPreference(mForceResizable,
1192                 Settings.Global.getInt(mContentResolver,
1193                 Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0);
1194     }
1195 
writeForceResizableOptions()1196     private void writeForceResizableOptions() {
1197         Settings.Global.putInt(mContentResolver,
1198                 Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES,
1199                 mForceResizable.isChecked() ? 1 : 0);
1200     }
1201 
updateForceRtlOptions()1202     private void updateForceRtlOptions() {
1203         updateSwitchPreference(mForceRtlLayout,
1204                 Settings.Global.getInt(mContentResolver,
1205                         Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0);
1206     }
1207 
writeForceRtlOptions()1208     private void writeForceRtlOptions() {
1209         boolean value = mForceRtlLayout.isChecked();
1210         Settings.Global.putInt(mContentResolver,
1211                 Settings.Global.DEVELOPMENT_FORCE_RTL, value ? 1 : 0);
1212         SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, value ? "1" : "0");
1213         LocalePicker.updateLocale(
1214                 getActivity().getResources().getConfiguration().getLocales().get(0));
1215     }
1216 
updateWifiDisplayCertificationOptions()1217     private void updateWifiDisplayCertificationOptions() {
1218         updateSwitchPreference(mWifiDisplayCertification, Settings.Global.getInt(
1219                 mContentResolver, Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, 0) != 0);
1220     }
1221 
writeWifiDisplayCertificationOptions()1222     private void writeWifiDisplayCertificationOptions() {
1223         Settings.Global.putInt(mContentResolver,
1224                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
1225                 mWifiDisplayCertification.isChecked() ? 1 : 0);
1226     }
1227 
updateWifiVerboseLoggingOptions()1228     private void updateWifiVerboseLoggingOptions() {
1229         boolean enabled = mWifiManager.getVerboseLoggingLevel() > 0;
1230         updateSwitchPreference(mWifiVerboseLogging, enabled);
1231     }
1232 
writeWifiVerboseLoggingOptions()1233     private void writeWifiVerboseLoggingOptions() {
1234         mWifiManager.enableVerboseLogging(mWifiVerboseLogging.isChecked() ? 1 : 0);
1235     }
1236 
updateMobileDataAlwaysOnOptions()1237     private void updateMobileDataAlwaysOnOptions() {
1238         updateSwitchPreference(mMobileDataAlwaysOn, Settings.Global.getInt(mContentResolver,
1239                 Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) != 0);
1240     }
1241 
writeMobileDataAlwaysOnOptions()1242     private void writeMobileDataAlwaysOnOptions() {
1243         Settings.Global.putInt(mContentResolver, Settings.Global.MOBILE_DATA_ALWAYS_ON,
1244                 mMobileDataAlwaysOn.isChecked() ? 1 : 0);
1245     }
1246 
updateUsbConfigurationValues()1247     private void updateUsbConfigurationValues() {
1248         if (mUsbConfiguration != null) {
1249             UsbManager manager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
1250 
1251             String[] values = getResources().getStringArray(R.array.usb_configuration_values);
1252             String[] titles = getResources().getStringArray(R.array.usb_configuration_titles);
1253             int index = 0;
1254             long functions = manager.getCurrentFunctions();
1255             for (int i = 0; i < titles.length; i++) {
1256                 if ((functions | UsbManager.usbFunctionsFromString(values[i])) != 0) {
1257                     index = i;
1258                     break;
1259                 }
1260             }
1261             mUsbConfiguration.setValue(values[index]);
1262             mUsbConfiguration.setSummary(titles[index]);
1263             mUsbConfiguration.setOnPreferenceChangeListener(this);
1264         }
1265     }
1266 
writeUsbConfigurationOption(Object newValue)1267     private void writeUsbConfigurationOption(Object newValue) {
1268         UsbManager manager = (UsbManager)getActivity().getSystemService(Context.USB_SERVICE);
1269         String function = newValue.toString();
1270         manager.setCurrentFunctions(UsbManager.usbFunctionsFromString(function));
1271     }
1272 
writeImmediatelyDestroyActivitiesOptions()1273     private void writeImmediatelyDestroyActivitiesOptions() {
1274         try {
1275             ActivityManager.getService().setAlwaysFinish(
1276                     mImmediatelyDestroyActivities.isChecked());
1277         } catch (RemoteException ex) {
1278             // ignore
1279         }
1280     }
1281 
updateImmediatelyDestroyActivitiesOptions()1282     private void updateImmediatelyDestroyActivitiesOptions() {
1283         updateSwitchPreference(mImmediatelyDestroyActivities, Settings.Global.getInt(
1284                 mContentResolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0);
1285     }
1286 
updateAnimationScaleValue(int which, ListPreference pref)1287     private void updateAnimationScaleValue(int which, ListPreference pref) {
1288         try {
1289             float scale = mWindowManager.getAnimationScale(which);
1290             if (scale != 1) {
1291                 mHaveDebugSettings = true;
1292             }
1293             CharSequence[] values = pref.getEntryValues();
1294             for (int i=0; i<values.length; i++) {
1295                 float val = Float.parseFloat(values[i].toString());
1296                 if (scale <= val) {
1297                     pref.setValueIndex(i);
1298                     pref.setSummary(pref.getEntries()[i]);
1299                     return;
1300                 }
1301             }
1302             pref.setValueIndex(values.length-1);
1303             pref.setSummary(pref.getEntries()[0]);
1304         } catch (RemoteException e) {
1305             // ignore
1306         }
1307     }
1308 
updateAnimationScaleOptions()1309     private void updateAnimationScaleOptions() {
1310         updateAnimationScaleValue(0, mWindowAnimationScale);
1311         updateAnimationScaleValue(1, mTransitionAnimationScale);
1312         updateAnimationScaleValue(2, mAnimatorDurationScale);
1313     }
1314 
writeAnimationScaleOption(int which, ListPreference pref, Object newValue)1315     private void writeAnimationScaleOption(int which, ListPreference pref, Object newValue) {
1316         try {
1317             float scale = newValue != null ? Float.parseFloat(newValue.toString()) : 1;
1318             mWindowManager.setAnimationScale(which, scale);
1319             updateAnimationScaleValue(which, pref);
1320         } catch (RemoteException e) {
1321             // ignore
1322         }
1323     }
1324 
updateOverlayDisplayDevicesOptions()1325     private void updateOverlayDisplayDevicesOptions() {
1326         String value = Settings.Global.getString(mContentResolver,
1327                 Settings.Global.OVERLAY_DISPLAY_DEVICES);
1328         if (value == null) {
1329             value = "";
1330         }
1331 
1332         CharSequence[] values = mOverlayDisplayDevices.getEntryValues();
1333         for (int i = 0; i < values.length; i++) {
1334             if (value.contentEquals(values[i])) {
1335                 mOverlayDisplayDevices.setValueIndex(i);
1336                 mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[i]);
1337                 return;
1338             }
1339         }
1340         mOverlayDisplayDevices.setValueIndex(0);
1341         mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[0]);
1342     }
1343 
writeOverlayDisplayDevicesOptions(Object newValue)1344     private void writeOverlayDisplayDevicesOptions(Object newValue) {
1345         Settings.Global.putString(mContentResolver, Settings.Global.OVERLAY_DISPLAY_DEVICES,
1346                 (String)newValue);
1347         updateOverlayDisplayDevicesOptions();
1348     }
1349 
updateOpenGLTracesOptions()1350     private void updateOpenGLTracesOptions() {
1351         String value = SystemProperties.get(OPENGL_TRACES_PROPERTY);
1352         if (value == null) {
1353             value = "";
1354         }
1355 
1356         CharSequence[] values = mOpenGLTraces.getEntryValues();
1357         for (int i = 0; i < values.length; i++) {
1358             if (value.contentEquals(values[i])) {
1359                 mOpenGLTraces.setValueIndex(i);
1360                 mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[i]);
1361                 return;
1362             }
1363         }
1364         mOpenGLTraces.setValueIndex(0);
1365         mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[0]);
1366     }
1367 
writeOpenGLTracesOptions(Object newValue)1368     private void writeOpenGLTracesOptions(Object newValue) {
1369         SystemProperties.set(OPENGL_TRACES_PROPERTY, newValue == null ? "" : newValue.toString());
1370         SystemPropPoker.getInstance().poke();
1371         updateOpenGLTracesOptions();
1372     }
1373 
updateAppProcessLimitOptions()1374     private void updateAppProcessLimitOptions() {
1375         try {
1376             int limit = ActivityManager.getService().getProcessLimit();
1377             CharSequence[] values = mAppProcessLimit.getEntryValues();
1378             for (int i=0; i<values.length; i++) {
1379                 int val = Integer.parseInt(values[i].toString());
1380                 if (val >= limit) {
1381                     if (i != 0) {
1382                         mHaveDebugSettings = true;
1383                     }
1384                     mAppProcessLimit.setValueIndex(i);
1385                     mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]);
1386                     return;
1387                 }
1388             }
1389             mAppProcessLimit.setValueIndex(0);
1390             mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]);
1391         } catch (RemoteException e) {
1392             // ignore
1393         }
1394     }
1395 
writeAppProcessLimitOptions(Object newValue)1396     private void writeAppProcessLimitOptions(Object newValue) {
1397         try {
1398             int limit = newValue != null ? Integer.parseInt(newValue.toString()) : -1;
1399             ActivityManager.getService().setProcessLimit(limit);
1400             updateAppProcessLimitOptions();
1401         } catch (RemoteException e) {
1402             // ignore
1403         }
1404     }
1405 
writeShowAllANRsOptions()1406     private void writeShowAllANRsOptions() {
1407         Settings.Secure.putInt(mContentResolver, Settings.Secure.ANR_SHOW_BACKGROUND,
1408                 mShowAllANRs.isChecked() ? 1 : 0);
1409     }
1410 
updateShowAllANRsOptions()1411     private void updateShowAllANRsOptions() {
1412         updateSwitchPreference(mShowAllANRs, Settings.Secure.getInt(
1413                 mContentResolver, Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0);
1414     }
1415 
1416     @Override
onOemUnlockConfirm()1417     public void onOemUnlockConfirm() {
1418         mEnableOemUnlock.setChecked(true);
1419         setOemUnlockEnabled(getActivity(), true);
1420         updateAllOptions();
1421     }
1422 
1423     @Override
onEnableDevelopmentConfirm()1424     public void onEnableDevelopmentConfirm() {
1425         mEnableDeveloper.setChecked(true);
1426         DevelopmentSettingsEnabler.setDevelopmentSettingsEnabled(getContext(), true);
1427         mLastEnabledState = true;
1428         setPrefsEnabledState(true);
1429     }
1430 
1431     @Override
onEnableAdbConfirm()1432     public void onEnableAdbConfirm() {
1433         Settings.Global.putInt(mContentResolver, Settings.Global.ADB_ENABLED, 1);
1434         mVerifyAppsOverUsb.setEnabled(true);
1435         updateVerifyAppsOverUsbOptions();
1436     }
1437 
1438     @Override
onActivityResult(int requestCode, int resultCode, Intent data)1439     public void onActivityResult(int requestCode, int resultCode, Intent data) {
1440         if (requestCode == RESULT_DEBUG_APP) {
1441             if (resultCode == Activity.RESULT_OK) {
1442                 mDebugApp = data.getAction();
1443                 writeDebuggerOptions();
1444                 updateDebuggerOptions();
1445             }
1446         } else if (requestCode == RESULT_MOCK_LOCATION_APP) {
1447             if (resultCode == Activity.RESULT_OK) {
1448                 mMockLocationApp = data.getAction();
1449                 writeMockLocation();
1450                 updateMockLocation();
1451             }
1452         } else {
1453             super.onActivityResult(requestCode, resultCode, data);
1454         }
1455     }
1456 
1457     @Override
onPreferenceTreeClick(Preference preference)1458     public boolean onPreferenceTreeClick(Preference preference) {
1459         if (ActivityManager.isUserAMonkey()) {
1460             return false;
1461         }
1462 
1463         if (preference == mEnableDeveloper) {
1464             if (mEnableDeveloper.isChecked()) {
1465                 // Pass to super to launch the dialog, then uncheck until the dialog
1466                 // result comes back
1467                 super.onPreferenceTreeClick(preference);
1468                 mEnableDeveloper.setChecked(false);
1469             } else {
1470                 resetDangerousOptions();
1471                 DevelopmentSettingsEnabler.setDevelopmentSettingsEnabled(getContext(), false);
1472                 mLastEnabledState = false;
1473                 setPrefsEnabledState(false);
1474             }
1475         } else if (preference == mBugreport) {
1476             captureBugReport();
1477         } else if (preference == mEnableAdb) {
1478             if (mEnableAdb.isChecked()) {
1479                 // Pass to super to launch the dialog, then uncheck until the dialog
1480                 // result comes back
1481                 super.onPreferenceTreeClick(preference);
1482                 mEnableAdb.setChecked(false);
1483             } else {
1484                 Settings.Global.putInt(mContentResolver, Settings.Global.ADB_ENABLED, 0);
1485                 mVerifyAppsOverUsb.setEnabled(false);
1486                 mVerifyAppsOverUsb.setChecked(false);
1487             }
1488         } else if (preference == mEnableTerminal) {
1489             final PackageManager pm = getActivity().getPackageManager();
1490             pm.setApplicationEnabledSetting(TERMINAL_APP_PACKAGE,
1491                     mEnableTerminal.isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1492                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
1493         } else if (preference == mKeepScreenOn) {
1494             Settings.Global.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
1495                     mKeepScreenOn.isChecked() ?
1496                             (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB)
1497                             : 0);
1498         } else if (preference == mBtHciSnoopLog) {
1499             writeBtHciSnoopLogOptions();
1500         } else if (preference == mEnableOemUnlock) {
1501             if (mEnableOemUnlock.isChecked()) {
1502                 // Pass to super to launch the dialog, then uncheck until the dialog
1503                 // result comes back
1504                 super.onPreferenceTreeClick(preference);
1505                 mEnableOemUnlock.setChecked(false);
1506             } else {
1507                 setOemUnlockEnabled(getActivity(), false);
1508             }
1509         } else if (preference == mMockLocationAppPref) {
1510             Intent intent = new Intent(getActivity(), AppPicker.class);
1511             intent.putExtra(AppPicker.EXTRA_REQUESTIING_PERMISSION,
1512                     Manifest.permission.ACCESS_MOCK_LOCATION);
1513             startActivityForResult(intent, RESULT_MOCK_LOCATION_APP);
1514         } else if (preference == mDebugViewAttributes) {
1515             Settings.Global.putInt(mContentResolver, Settings.Global.DEBUG_VIEW_ATTRIBUTES,
1516                     mDebugViewAttributes.isChecked() ? 1 : 0);
1517         } else if (preference == mForceAllowOnExternal) {
1518             Settings.Global.putInt(mContentResolver, Settings.Global.FORCE_ALLOW_ON_EXTERNAL,
1519                     mForceAllowOnExternal.isChecked() ? 1 : 0);
1520         } else if (preference == mDebugAppPref) {
1521             Intent intent = new Intent(getActivity(), AppPicker.class);
1522             intent.putExtra(AppPicker.EXTRA_DEBUGGABLE, true);
1523             startActivityForResult(intent, RESULT_DEBUG_APP);
1524         } else if (preference == mWaitForDebugger) {
1525             writeDebuggerOptions();
1526         } else if (preference == mVerifyAppsOverUsb) {
1527             writeVerifyAppsOverUsbOptions();
1528         } else if (preference == mStrictMode) {
1529             writeStrictModeVisualOptions();
1530         } else if (preference == mPointerLocation) {
1531             writePointerLocationOptions();
1532         } else if (preference == mShowTouches) {
1533             writeShowTouchesOptions();
1534         } else if (preference == mShowScreenUpdates) {
1535             writeShowUpdatesOption();
1536         } else if (preference == mDisableOverlays) {
1537             writeDisableOverlaysOption();
1538         } else if (preference == mImmediatelyDestroyActivities) {
1539             writeImmediatelyDestroyActivitiesOptions();
1540         } else if (preference == mShowAllANRs) {
1541             writeShowAllANRsOptions();
1542         } else if (preference == mForceHardwareUi) {
1543             writeHardwareUiOptions();
1544         } else if (preference == mForceMsaa) {
1545             writeMsaaOptions();
1546         } else if (preference == mShowHwScreenUpdates) {
1547             writeShowHwScreenUpdatesOptions();
1548         } else if (preference == mShowHwLayersUpdates) {
1549             writeShowHwLayersUpdatesOptions();
1550         } else if (preference == mDebugLayout) {
1551             writeDebugLayoutOptions();
1552         } else if (preference == mForceRtlLayout) {
1553             writeForceRtlOptions();
1554         } else if (preference == mWifiDisplayCertification) {
1555             writeWifiDisplayCertificationOptions();
1556         } else if (preference == mWifiVerboseLogging) {
1557             writeWifiVerboseLoggingOptions();
1558         } else if (preference == mMobileDataAlwaysOn) {
1559             writeMobileDataAlwaysOnOptions();
1560         } else if (preference == mUSBAudio) {
1561             writeUSBAudioOptions();
1562         } else if (preference == mForceResizable) {
1563             writeForceResizableOptions();
1564         } else {
1565             return super.onPreferenceTreeClick(preference);
1566         }
1567 
1568         return false;
1569     }
1570 
1571     @Override
onPreferenceChange(Preference preference, Object newValue)1572     public boolean onPreferenceChange(Preference preference, Object newValue) {
1573         if (HDCP_CHECKING_KEY.equals(preference.getKey())) {
1574             SystemProperties.set(HDCP_CHECKING_PROPERTY, newValue.toString());
1575             updateHdcpValues();
1576             SystemPropPoker.getInstance().poke();
1577             return true;
1578         } else if (preference == mUsbConfiguration) {
1579             writeUsbConfigurationOption(newValue);
1580             return true;
1581         } else if (preference == mWindowAnimationScale) {
1582             writeAnimationScaleOption(0, mWindowAnimationScale, newValue);
1583             return true;
1584         } else if (preference == mTransitionAnimationScale) {
1585             writeAnimationScaleOption(1, mTransitionAnimationScale, newValue);
1586             return true;
1587         } else if (preference == mAnimatorDurationScale) {
1588             writeAnimationScaleOption(2, mAnimatorDurationScale, newValue);
1589             return true;
1590         } else if (preference == mOverlayDisplayDevices) {
1591             writeOverlayDisplayDevicesOptions(newValue);
1592             return true;
1593         } else if (preference == mOpenGLTraces) {
1594             writeOpenGLTracesOptions(newValue);
1595             return true;
1596         } else if (preference == mTrackFrameTime) {
1597             writeTrackFrameTimeOptions(newValue);
1598             return true;
1599         } else if (preference == mDebugHwOverdraw) {
1600             writeDebugHwOverdrawOptions(newValue);
1601             return true;
1602         } else if (preference == mShowNonRectClip) {
1603             writeShowNonRectClipOptions(newValue);
1604             return true;
1605         } else if (preference == mAppProcessLimit) {
1606             writeAppProcessLimitOptions(newValue);
1607             return true;
1608         } else if (preference == mSimulateColorSpace) {
1609             writeSimulateColorSpace(newValue);
1610             return true;
1611         }
1612         return false;
1613     }
1614 
1615     /**
1616      * Iterates through preference controllers that show confirmation dialogs and returns the
1617      * preference key for the first currently showing dialog. Ideally there should only ever be one.
1618      * @return Preference key, or null if no dialog is showing
1619      */
getKeyForShowingDialog()1620     private String getKeyForShowingDialog() {
1621         // TODO: iterate through a fragment-wide list of PreferenceControllers and just pick out the
1622         // ConfirmationDialogController objects
1623         final List<ConfirmationDialogController> dialogControllers = new ArrayList<>(2);
1624         dialogControllers.add(mLogpersistController);
1625         for (ConfirmationDialogController dialogController : dialogControllers) {
1626             if (dialogController.isConfirmationDialogShowing()) {
1627                 return dialogController.getPreferenceKey();
1628             }
1629         }
1630         return null;
1631     }
1632 
1633     /**
1634      * Re-show the dialog we lost previously
1635      * @param preferenceKey Key for the preference the dialog is for
1636      */
recreateDialogForKey(String preferenceKey)1637     private void recreateDialogForKey(String preferenceKey) {
1638         // TODO: iterate through a fragment-wide list of PreferenceControllers and just pick out the
1639         // ConfirmationDialogController objects
1640         final List<ConfirmationDialogController> dialogControllers = new ArrayList<>(2);
1641         dialogControllers.add(mLogpersistController);
1642         for (ConfirmationDialogController dialogController : dialogControllers) {
1643             if (TextUtils.equals(preferenceKey, dialogController.getPreferenceKey())) {
1644                 dialogController.showConfirmationDialog(findPreference(preferenceKey));
1645             }
1646         }
1647     }
1648 
dismissDialogs()1649     private void dismissDialogs() {
1650         mLogpersistController.dismissConfirmationDialog();
1651     }
1652 
1653     private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
1654         @Override
1655         public void onReceive(Context context, Intent intent) {
1656             updateUsbConfigurationValues();
1657         }
1658     };
1659 
isPackageInstalled(Context context, String packageName)1660     private static boolean isPackageInstalled(Context context, String packageName) {
1661         try {
1662             return context.getPackageManager().getPackageInfo(packageName, 0) != null;
1663         } catch (PackageManager.NameNotFoundException e) {
1664             return false;
1665         }
1666     }
1667 
1668     /**
1669      * Returns whether or not this device is able to be OEM unlocked.
1670      */
isOemUnlockEnabled(Context context)1671     static boolean isOemUnlockEnabled(Context context) {
1672         PersistentDataBlockManager manager =(PersistentDataBlockManager)
1673                 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
1674         return manager.getOemUnlockEnabled();
1675     }
1676 
1677     /**
1678      * Allows enabling or disabling OEM unlock on this device. OEM unlocked
1679      * devices allow users to flash other OSes to them.
1680      */
setOemUnlockEnabled(Context context, boolean enabled)1681     static void setOemUnlockEnabled(Context context, boolean enabled) {
1682         try {
1683             PersistentDataBlockManager manager = (PersistentDataBlockManager)
1684                     context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
1685             manager.setOemUnlockEnabled(enabled);
1686         } catch (SecurityException e) {
1687             Log.e(TAG, "Fail to set oem unlock.", e);
1688         }
1689     }
1690 }
1691