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