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