OSDN Git Service

Settings: Set root access options appropriately
[android-x86/packages-apps-Settings.git] / src / com / android / settings / DevelopmentSettings.java
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  * Copyright (C) 2013-2014 The CyanogenMod Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package com.android.settings;
19
20 import android.Manifest;
21 import android.app.Activity;
22 import android.app.ActivityManagerNative;
23 import android.app.AlertDialog;
24 import android.app.AppOpsManager;
25 import android.app.AppOpsManager.PackageOps;
26 import android.app.Dialog;
27 import android.app.admin.DevicePolicyManager;
28 import android.app.backup.IBackupManager;
29 import android.bluetooth.BluetoothAdapter;
30 import android.content.BroadcastReceiver;
31 import android.content.ComponentName;
32 import android.content.ContentResolver;
33 import android.content.Context;
34 import android.content.DialogInterface;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.pm.ApplicationInfo;
38 import android.content.pm.PackageManager;
39 import android.content.pm.PackageManager.NameNotFoundException;
40 import android.content.pm.ResolveInfo;
41 import android.content.res.Resources;
42 import android.net.NetworkUtils;
43 import android.net.wifi.IWifiManager;
44 import android.net.wifi.WifiInfo;
45 import android.hardware.usb.IUsbManager;
46 import android.hardware.usb.UsbManager;
47 import android.net.wifi.WifiManager;
48 import android.os.AsyncTask;
49 import android.os.BatteryManager;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.IBinder;
53 import android.os.Parcel;
54 import android.os.RemoteException;
55 import android.os.ServiceManager;
56 import android.os.StrictMode;
57 import android.os.SystemProperties;
58 import android.os.UserHandle;
59 import android.os.UserManager;
60 import android.preference.ListPreference;
61 import android.preference.Preference;
62 import android.preference.Preference.OnPreferenceChangeListener;
63 import android.preference.Preference.OnPreferenceClickListener;
64 import android.preference.PreferenceGroup;
65 import android.preference.PreferenceScreen;
66 import android.preference.SwitchPreference;
67 import android.provider.SearchIndexableResource;
68 import android.provider.Settings;
69 import android.text.TextUtils;
70 import android.util.Log;
71 import android.view.HardwareRenderer;
72 import android.view.IWindowManager;
73 import android.view.LayoutInflater;
74 import android.view.View;
75 import android.view.ViewGroup;
76 import android.view.accessibility.AccessibilityManager;
77 import android.widget.Switch;
78 import android.widget.TextView;
79 import android.widget.Toast;
80
81 import com.android.internal.logging.MetricsLogger;
82 import com.android.settings.fuelgauge.InactiveApps;
83 import com.android.settings.search.BaseSearchIndexProvider;
84 import com.android.settings.search.Indexable;
85 import com.android.settings.widget.SwitchBar;
86 import cyanogenmod.providers.CMSettings;
87
88 import java.io.File;
89 import java.util.ArrayList;
90 import java.util.Arrays;
91 import java.util.HashSet;
92 import java.util.List;
93
94 /*
95  * Displays preferences for application developers.
96  */
97 public class DevelopmentSettings extends SettingsPreferenceFragment
98         implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener,
99                 OnPreferenceChangeListener, SwitchBar.OnSwitchChangeListener, Indexable,
100                 OnPreferenceClickListener {
101     private static final String TAG = "DevelopmentSettings";
102
103     /**
104      * Preference file were development settings prefs are stored.
105      */
106     public static final String PREF_FILE = "development";
107
108     /**
109      * Whether to show the development settings to the user.  Default is false.
110      */
111     public static final String PREF_SHOW = "show";
112
113     private static final String ENABLE_ADB = "enable_adb";
114     private static final String ADB_NOTIFY = "adb_notify";
115     private static final String ADB_TCPIP = "adb_over_network";
116     private static final String CLEAR_ADB_KEYS = "clear_adb_keys";
117     private static final String ENABLE_TERMINAL = "enable_terminal";
118     private static final String KEEP_SCREEN_ON_MODES = "keep_screen_on_modes";
119     private static final String BT_HCI_SNOOP_LOG = "bt_hci_snoop_log";
120     private static final String ENABLE_OEM_UNLOCK = "oem_unlock_enable";
121     private static final String HDCP_CHECKING_KEY = "hdcp_checking";
122     private static final String HDCP_CHECKING_PROPERTY = "persist.sys.hdcp_checking";
123     private static final String LOCAL_BACKUP_PASSWORD = "local_backup_password";
124     private static final String HARDWARE_UI_PROPERTY = "persist.sys.ui.hw";
125     private static final String MSAA_PROPERTY = "debug.egl.force_msaa";
126     private static final String BUGREPORT = "bugreport";
127     private static final String BUGREPORT_IN_POWER_KEY = "bugreport_in_power";
128     private static final String OPENGL_TRACES_PROPERTY = "debug.egl.trace";
129     private static final String TUNER_UI_KEY = "tuner_ui";
130     private static final String COLOR_TEMPERATURE_PROPERTY = "persist.sys.debug.color_temp";
131
132     private static final String DEBUG_APP_KEY = "debug_app";
133     private static final String WAIT_FOR_DEBUGGER_KEY = "wait_for_debugger";
134     private static final String MOCK_LOCATION_APP_KEY = "mock_location_app";
135     private static final String VERIFY_APPS_OVER_USB_KEY = "verify_apps_over_usb";
136     private static final String DEBUG_VIEW_ATTRIBUTES =  "debug_view_attributes";
137     private static final String STRICT_MODE_KEY = "strict_mode";
138     private static final String POINTER_LOCATION_KEY = "pointer_location";
139     private static final String SHOW_TOUCHES_KEY = "show_touches";
140     private static final String SHOW_SCREEN_UPDATES_KEY = "show_screen_updates";
141     private static final String DISABLE_OVERLAYS_KEY = "disable_overlays";
142     private static final String SIMULATE_COLOR_SPACE = "simulate_color_space";
143     private static final String USB_AUDIO_KEY = "usb_audio";
144     private static final String SHOW_CPU_USAGE_KEY = "show_cpu_usage";
145     private static final String FORCE_HARDWARE_UI_KEY = "force_hw_ui";
146     private static final String FORCE_MSAA_KEY = "force_msaa";
147     private static final String TRACK_FRAME_TIME_KEY = "track_frame_time";
148     private static final String SHOW_NON_RECTANGULAR_CLIP_KEY = "show_non_rect_clip";
149     private static final String SHOW_HW_SCREEN_UPDATES_KEY = "show_hw_screen_udpates";
150     private static final String SHOW_HW_LAYERS_UPDATES_KEY = "show_hw_layers_udpates";
151     private static final String DEBUG_HW_OVERDRAW_KEY = "debug_hw_overdraw";
152     private static final String DEBUG_LAYOUT_KEY = "debug_layout";
153     private static final String FORCE_RTL_LAYOUT_KEY = "force_rtl_layout_all_locales";
154     private static final String WINDOW_ANIMATION_SCALE_KEY = "window_animation_scale";
155     private static final String TRANSITION_ANIMATION_SCALE_KEY = "transition_animation_scale";
156     private static final String ANIMATOR_DURATION_SCALE_KEY = "animator_duration_scale";
157     private static final String OVERLAY_DISPLAY_DEVICES_KEY = "overlay_display_devices";
158     private static final String ENABLE_MULTI_WINDOW_KEY = "enable_multi_window";
159     private static final String DEBUG_DEBUGGING_CATEGORY_KEY = "debug_debugging_category";
160     private static final String SELECT_LOGD_SIZE_KEY = "select_logd_size";
161     private static final String SELECT_LOGD_SIZE_PROPERTY = "persist.logd.size";
162     private static final String SELECT_LOGD_DEFAULT_SIZE_PROPERTY = "ro.logd.size";
163
164     private static final String WIFI_DISPLAY_CERTIFICATION_KEY = "wifi_display_certification";
165     private static final String WIFI_VERBOSE_LOGGING_KEY = "wifi_verbose_logging";
166     private static final String WIFI_AGGRESSIVE_HANDOVER_KEY = "wifi_aggressive_handover";
167     private static final String WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY = "wifi_allow_scan_with_traffic";
168     private static final String USB_CONFIGURATION_KEY = "select_usb_configuration";
169     private static final String WIFI_LEGACY_DHCP_CLIENT_KEY = "legacy_dhcp_client";
170     private static final String MOBILE_DATA_ALWAYS_ON = "mobile_data_always_on";
171     private static final String KEY_COLOR_MODE = "color_mode";
172     private static final String COLOR_TEMPERATURE_KEY = "color_temperature";
173
174     private static final String INACTIVE_APPS_KEY = "inactive_apps";
175
176     private static final String OPENGL_TRACES_KEY = "enable_opengl_traces";
177
178     private static final String ROOT_ACCESS_KEY = "root_access";
179     private static final String ROOT_ACCESS_PROPERTY = "persist.sys.root_access";
180
181     private static final String UPDATE_RECOVERY_KEY = "update_recovery";
182     private static final String UPDATE_RECOVERY_PROPERTY = "persist.sys.recovery_update";
183
184     private static final String IMMEDIATELY_DESTROY_ACTIVITIES_KEY
185             = "immediately_destroy_activities";
186     private static final String APP_PROCESS_LIMIT_KEY = "app_process_limit";
187
188     private static final String SHOW_ALL_ANRS_KEY = "show_all_anrs";
189
190     private static final String KILL_APP_LONGPRESS_BACK = "kill_app_longpress_back";
191
192     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
193
194     private static final String TERMINAL_APP_PACKAGE = "com.android.terminal";
195
196     private static final String DEVELOPMENT_TOOLS = "development_tools";
197
198     private static final String ADVANCED_REBOOT_KEY = "advanced_reboot";
199
200     private static final String DEVELOPMENT_SHORTCUT_KEY = "development_shortcut";
201
202     private static final int RESULT_DEBUG_APP = 1000;
203     private static final int RESULT_MOCK_LOCATION_APP = 1001;
204
205     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
206
207     private static final int REQUEST_CODE_ENABLE_OEM_UNLOCK = 0;
208
209     private static String DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES = "262144"; // 256K
210
211     private static final int[] MOCK_LOCATION_APP_OPS = new int[] {AppOpsManager.OP_MOCK_LOCATION};
212
213     private static final String MULTI_WINDOW_SYSTEM_PROPERTY = "persist.sys.debug.multi_window";
214
215     private static final String SUPERUSER_BINARY_PATH = "/system/xbin/su";
216
217     private IWindowManager mWindowManager;
218     private IBackupManager mBackupManager;
219     private DevicePolicyManager mDpm;
220     private UserManager mUm;
221     private WifiManager mWifiManager;
222
223     private SwitchBar mSwitchBar;
224     private boolean mLastEnabledState;
225     private boolean mHaveDebugSettings;
226     private boolean mDontPokeProperties;
227
228     private SwitchPreference mEnableAdb;
229     private SwitchPreference mAdbNotify;
230     private SwitchPreference mAdbOverNetwork;
231     private Preference mClearAdbKeys;
232     private SwitchPreference mEnableTerminal;
233     private Preference mBugreport;
234     private SwitchPreference mBugreportInPower;
235     private ListPreference mKeepScreenOn;
236     private SwitchPreference mBtHciSnoopLog;
237     private SwitchPreference mEnableOemUnlock;
238     private SwitchPreference mDebugViewAttributes;
239
240     private PreferenceScreen mPassword;
241     private String mDebugApp;
242     private Preference mDebugAppPref;
243
244     private String mMockLocationApp;
245     private Preference mMockLocationAppPref;
246
247     private SwitchPreference mWaitForDebugger;
248     private SwitchPreference mVerifyAppsOverUsb;
249     private SwitchPreference mWifiDisplayCertification;
250     private SwitchPreference mWifiVerboseLogging;
251     private SwitchPreference mWifiAggressiveHandover;
252     private SwitchPreference mLegacyDhcpClient;
253     private SwitchPreference mMobileDataAlwaysOn;
254
255     private SwitchPreference mWifiAllowScansWithTraffic;
256     private SwitchPreference mStrictMode;
257     private SwitchPreference mPointerLocation;
258     private SwitchPreference mShowTouches;
259     private SwitchPreference mShowScreenUpdates;
260     private SwitchPreference mDisableOverlays;
261     private SwitchPreference mEnableMultiWindow;
262     private SwitchPreference mShowCpuUsage;
263     private SwitchPreference mForceHardwareUi;
264     private SwitchPreference mForceMsaa;
265     private SwitchPreference mShowHwScreenUpdates;
266     private SwitchPreference mShowHwLayersUpdates;
267     private SwitchPreference mDebugLayout;
268     private SwitchPreference mForceRtlLayout;
269     private ListPreference mDebugHwOverdraw;
270     private ListPreference mLogdSize;
271     private ListPreference mUsbConfiguration;
272     private ListPreference mTrackFrameTime;
273     private ListPreference mShowNonRectClip;
274     private AnimationScalePreference mWindowAnimationScale;
275     private AnimationScalePreference mTransitionAnimationScale;
276     private AnimationScalePreference mAnimatorDurationScale;
277     private ListPreference mOverlayDisplayDevices;
278     private ListPreference mOpenGLTraces;
279
280     private ListPreference mSimulateColorSpace;
281
282     private SwitchPreference mUSBAudio;
283     private SwitchPreference mImmediatelyDestroyActivities;
284
285     private ListPreference mAppProcessLimit;
286
287     private SwitchPreference mShowAllANRs;
288     private SwitchPreference mKillAppLongpressBack;
289
290     private ListPreference mRootAccess;
291     private Object mSelectedRootValue;
292     private PreferenceScreen mDevelopmentTools;
293     private ColorModePreference mColorModePreference;
294
295     private SwitchPreference mAdvancedReboot;
296
297     private SwitchPreference mUpdateRecovery;
298
299     private SwitchPreference mDevelopmentShortcut;
300
301     private SwitchPreference mColorTemperaturePreference;
302
303     private final ArrayList<Preference> mAllPrefs = new ArrayList<Preference>();
304
305     private final ArrayList<SwitchPreference> mResetSwitchPrefs
306             = new ArrayList<SwitchPreference>();
307
308     private final HashSet<Preference> mDisabledPrefs = new HashSet<Preference>();
309     // To track whether a confirmation dialog was clicked.
310     private boolean mDialogClicked;
311     private Dialog mEnableDialog;
312     private Dialog mAdbDialog;
313     private Dialog mAdbTcpDialog;
314     private Dialog mAdbKeysDialog;
315     private boolean mUnavailable;
316     private Dialog mRootDialog;
317     private Dialog mUpdateRecoveryDialog;
318
319     @Override
320     protected int getMetricsCategory() {
321         return MetricsLogger.DEVELOPMENT;
322     }
323
324     @Override
325     public void onCreate(Bundle icicle) {
326         super.onCreate(icicle);
327
328         mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
329         mBackupManager = IBackupManager.Stub.asInterface(
330                 ServiceManager.getService(Context.BACKUP_SERVICE));
331         mDpm = (DevicePolicyManager)getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
332         mUm = (UserManager) getSystemService(Context.USER_SERVICE);
333
334         mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
335
336         if (android.os.Process.myUserHandle().getIdentifier() != UserHandle.USER_OWNER
337                 || mUm.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES)
338                 || Settings.Global.getInt(getActivity().getContentResolver(),
339                         Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
340             // Block access to developer options if the user is not the owner, if user policy
341             // restricts it, or if the device has not been provisioned
342             mUnavailable = true;
343             setPreferenceScreen(new PreferenceScreen(getActivity(), null));
344             return;
345         }
346
347         addPreferencesFromResource(R.xml.development_prefs);
348
349         final PreferenceGroup debugDebuggingCategory = (PreferenceGroup)
350                 findPreference(DEBUG_DEBUGGING_CATEGORY_KEY);
351         mEnableAdb = findAndInitSwitchPref(ENABLE_ADB);
352
353         mAdbNotify = (SwitchPreference) findPreference(ADB_NOTIFY);
354         mAllPrefs.add(mAdbNotify);
355         mAdbOverNetwork = findAndInitSwitchPref(ADB_TCPIP);
356
357         mClearAdbKeys = findPreference(CLEAR_ADB_KEYS);
358         if (!SystemProperties.getBoolean("ro.adb.secure", false)) {
359             if (debugDebuggingCategory != null) {
360                 debugDebuggingCategory.removePreference(mClearAdbKeys);
361             }
362         }
363         mAllPrefs.add(mClearAdbKeys);
364         mEnableTerminal = findAndInitSwitchPref(ENABLE_TERMINAL);
365         if (!isPackageInstalled(getActivity(), TERMINAL_APP_PACKAGE)) {
366             debugDebuggingCategory.removePreference(mEnableTerminal);
367             mEnableTerminal = null;
368         }
369
370         mBugreport = findPreference(BUGREPORT);
371         mBugreportInPower = findAndInitSwitchPref(BUGREPORT_IN_POWER_KEY);
372         mKeepScreenOn = addListPreference(KEEP_SCREEN_ON_MODES);
373         mBtHciSnoopLog = findAndInitSwitchPref(BT_HCI_SNOOP_LOG);
374         mEnableOemUnlock = findAndInitSwitchPref(ENABLE_OEM_UNLOCK);
375         if (!showEnableOemUnlockPreference()) {
376             removePreference(mEnableOemUnlock);
377             mEnableOemUnlock = null;
378         }
379
380         mDebugViewAttributes = findAndInitSwitchPref(DEBUG_VIEW_ATTRIBUTES);
381         mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD);
382         mAllPrefs.add(mPassword);
383         mAdvancedReboot = findAndInitSwitchPref(ADVANCED_REBOOT_KEY);
384         mUpdateRecovery = findAndInitSwitchPref(UPDATE_RECOVERY_KEY);
385         mDevelopmentShortcut = findAndInitSwitchPref(DEVELOPMENT_SHORTCUT_KEY);
386
387
388         if (!android.os.Process.myUserHandle().equals(UserHandle.OWNER)) {
389             disableForUser(mEnableAdb);
390             disableForUser(mClearAdbKeys);
391             disableForUser(mEnableTerminal);
392             disableForUser(mPassword);
393             disableForUser(mAdvancedReboot);
394             disableForUser(mUpdateRecovery);
395             disableForUser(mDevelopmentShortcut);
396         }
397
398         mDebugAppPref = findPreference(DEBUG_APP_KEY);
399         mAllPrefs.add(mDebugAppPref);
400         mWaitForDebugger = findAndInitSwitchPref(WAIT_FOR_DEBUGGER_KEY);
401
402         mMockLocationAppPref = findPreference(MOCK_LOCATION_APP_KEY);
403         mAllPrefs.add(mMockLocationAppPref);
404
405         mVerifyAppsOverUsb = (SwitchPreference) findPreference(VERIFY_APPS_OVER_USB_KEY);
406         mAllPrefs.add(mVerifyAppsOverUsb);
407         if (!showVerifierSetting()) {
408             if (debugDebuggingCategory != null) {
409                 debugDebuggingCategory.removePreference(mVerifyAppsOverUsb);
410             } else {
411                 mVerifyAppsOverUsb.setEnabled(false);
412             }
413         }
414         mStrictMode = findAndInitSwitchPref(STRICT_MODE_KEY);
415         mPointerLocation = findAndInitSwitchPref(POINTER_LOCATION_KEY);
416         mShowTouches = findAndInitSwitchPref(SHOW_TOUCHES_KEY);
417         mShowScreenUpdates = findAndInitSwitchPref(SHOW_SCREEN_UPDATES_KEY);
418         mDisableOverlays = findAndInitSwitchPref(DISABLE_OVERLAYS_KEY);
419         mShowCpuUsage = findAndInitSwitchPref(SHOW_CPU_USAGE_KEY);
420         mForceHardwareUi = findAndInitSwitchPref(FORCE_HARDWARE_UI_KEY);
421         mForceMsaa = findAndInitSwitchPref(FORCE_MSAA_KEY);
422         mTrackFrameTime = addListPreference(TRACK_FRAME_TIME_KEY);
423         mShowNonRectClip = addListPreference(SHOW_NON_RECTANGULAR_CLIP_KEY);
424         mShowHwScreenUpdates = findAndInitSwitchPref(SHOW_HW_SCREEN_UPDATES_KEY);
425         mShowHwLayersUpdates = findAndInitSwitchPref(SHOW_HW_LAYERS_UPDATES_KEY);
426         mDebugLayout = findAndInitSwitchPref(DEBUG_LAYOUT_KEY);
427         mForceRtlLayout = findAndInitSwitchPref(FORCE_RTL_LAYOUT_KEY);
428         mDebugHwOverdraw = addListPreference(DEBUG_HW_OVERDRAW_KEY);
429         mWifiDisplayCertification = findAndInitSwitchPref(WIFI_DISPLAY_CERTIFICATION_KEY);
430         mWifiVerboseLogging = findAndInitSwitchPref(WIFI_VERBOSE_LOGGING_KEY);
431         mWifiAggressiveHandover = findAndInitSwitchPref(WIFI_AGGRESSIVE_HANDOVER_KEY);
432         mWifiAllowScansWithTraffic = findAndInitSwitchPref(WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY);
433         mLegacyDhcpClient = findAndInitSwitchPref(WIFI_LEGACY_DHCP_CLIENT_KEY);
434         mMobileDataAlwaysOn = findAndInitSwitchPref(MOBILE_DATA_ALWAYS_ON);
435         mLogdSize = addListPreference(SELECT_LOGD_SIZE_KEY);
436         mUsbConfiguration = addListPreference(USB_CONFIGURATION_KEY);
437
438         mWindowAnimationScale = findAndInitAnimationScalePreference(WINDOW_ANIMATION_SCALE_KEY);
439         mTransitionAnimationScale = findAndInitAnimationScalePreference(TRANSITION_ANIMATION_SCALE_KEY);
440         mAnimatorDurationScale = findAndInitAnimationScalePreference(ANIMATOR_DURATION_SCALE_KEY);
441         mOverlayDisplayDevices = addListPreference(OVERLAY_DISPLAY_DEVICES_KEY);
442         mEnableMultiWindow = findAndInitSwitchPref(ENABLE_MULTI_WINDOW_KEY);
443         if (!showEnableMultiWindowPreference()) {
444             final PreferenceGroup drawingGroup =
445                     (PreferenceGroup)findPreference("debug_drawing_category");
446             if (drawingGroup != null) {
447                 drawingGroup.removePreference(mEnableMultiWindow);
448             } else {
449                 mEnableMultiWindow.setEnabled(false);
450             }
451             removePreference(mEnableMultiWindow);
452             mEnableMultiWindow = null;
453         }
454         mOpenGLTraces = addListPreference(OPENGL_TRACES_KEY);
455         mSimulateColorSpace = addListPreference(SIMULATE_COLOR_SPACE);
456         mUSBAudio = findAndInitSwitchPref(USB_AUDIO_KEY);
457
458         mImmediatelyDestroyActivities = (SwitchPreference) findPreference(
459                 IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
460         mAllPrefs.add(mImmediatelyDestroyActivities);
461         mResetSwitchPrefs.add(mImmediatelyDestroyActivities);
462
463         mAppProcessLimit = addListPreference(APP_PROCESS_LIMIT_KEY);
464
465         mShowAllANRs = (SwitchPreference) findPreference(
466                 SHOW_ALL_ANRS_KEY);
467         mAllPrefs.add(mShowAllANRs);
468         mResetSwitchPrefs.add(mShowAllANRs);
469
470         mKillAppLongpressBack = findAndInitSwitchPref(KILL_APP_LONGPRESS_BACK);
471
472         Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY);
473         if (hdcpChecking != null) {
474             mAllPrefs.add(hdcpChecking);
475             removePreferenceForProduction(hdcpChecking);
476         }
477
478         mRootAccess = (ListPreference) findPreference(ROOT_ACCESS_KEY);
479         mRootAccess.setOnPreferenceChangeListener(this);
480         if (!removeRootOptionsIfRequired()) {
481             if (isRootForAppsAvailable()) {
482                 mRootAccess.setEntries(R.array.root_access_entries);
483                 mRootAccess.setEntryValues(R.array.root_access_values);
484             } else {
485                 mRootAccess.setEntries(R.array.root_access_entries_adb);
486                 mRootAccess.setEntryValues(R.array.root_access_values_adb);
487             }
488             mAllPrefs.add(mRootAccess);
489         }
490
491         mDevelopmentTools = (PreferenceScreen) findPreference(DEVELOPMENT_TOOLS);
492         if (Utils.updatePreferenceToSpecificActivityOrRemove(getActivity(),
493                 getPreferenceScreen(), mDevelopmentTools.getKey(), 0)) {
494             mAllPrefs.add(mDevelopmentTools);
495         }
496
497         mColorModePreference = (ColorModePreference) findPreference(KEY_COLOR_MODE);
498         mColorModePreference.updateCurrentAndSupported();
499         if (mColorModePreference.getTransformsCount() < 2) {
500             removePreference(KEY_COLOR_MODE);
501             mColorModePreference = null;
502         }
503
504         mColorTemperaturePreference = (SwitchPreference) findPreference(COLOR_TEMPERATURE_KEY);
505         if (getResources().getBoolean(R.bool.config_enableColorTemperature)) {
506             mAllPrefs.add(mColorTemperaturePreference);
507             mResetSwitchPrefs.add(mColorTemperaturePreference);
508         } else {
509             removePreference(COLOR_TEMPERATURE_KEY);
510             mColorTemperaturePreference = null;
511         }
512     }
513
514     private ListPreference addListPreference(String prefKey) {
515         ListPreference pref = (ListPreference) findPreference(prefKey);
516         mAllPrefs.add(pref);
517         pref.setOnPreferenceChangeListener(this);
518         return pref;
519     }
520
521     private void disableForUser(Preference pref) {
522         if (pref != null) {
523             pref.setEnabled(false);
524             mDisabledPrefs.add(pref);
525         }
526     }
527
528     private AnimationScalePreference findAndInitAnimationScalePreference(String key) {
529         AnimationScalePreference pref = (AnimationScalePreference) findPreference(key);
530         pref.setOnPreferenceChangeListener(this);
531         pref.setOnPreferenceClickListener(this);
532         mAllPrefs.add(pref);
533         return pref;
534     }
535
536     private SwitchPreference findAndInitSwitchPref(String key) {
537         SwitchPreference pref = (SwitchPreference) findPreference(key);
538         if (pref == null) {
539             throw new IllegalArgumentException("Cannot find preference with key = " + key);
540         }
541         mAllPrefs.add(pref);
542         mResetSwitchPrefs.add(pref);
543         return pref;
544     }
545
546     private boolean removeRootOptionsIfRequired() {
547         // user builds don't get root, and eng always gets root
548         if (!(Build.IS_DEBUGGABLE || "eng".equals(Build.TYPE))) {
549             if (mRootAccess != null) {
550                 getPreferenceScreen().removePreference(mRootAccess);
551                 return true;
552             }
553         }
554
555         return false;
556     }
557
558     @Override
559     public void onActivityCreated(Bundle savedInstanceState) {
560         super.onActivityCreated(savedInstanceState);
561
562         final SettingsActivity activity = (SettingsActivity) getActivity();
563
564         mSwitchBar = activity.getSwitchBar();
565        if (mUnavailable) {
566             mSwitchBar.setEnabled(false);
567             return;
568         }
569
570         mSwitchBar.addOnSwitchChangeListener(this);
571     }
572
573     private boolean removePreferenceForProduction(Preference preference) {
574         if ("user".equals(Build.TYPE)) {
575             removePreference(preference);
576             return true;
577         }
578         return false;
579     }
580
581     private void removePreference(Preference preference) {
582         getPreferenceScreen().removePreference(preference);
583         mAllPrefs.remove(preference);
584         mResetSwitchPrefs.remove(preference);
585     }
586
587     private void setPrefsEnabledState(boolean enabled) {
588         for (int i = 0; i < mAllPrefs.size(); i++) {
589             Preference pref = mAllPrefs.get(i);
590             pref.setEnabled(enabled && !mDisabledPrefs.contains(pref));
591         }
592         updateAllOptions();
593     }
594
595     @Override
596     public void onResume() {
597         super.onResume();
598
599         if (mUnavailable) {
600             // Show error message
601             TextView emptyView = (TextView) getView().findViewById(android.R.id.empty);
602             getListView().setEmptyView(emptyView);
603             if (emptyView != null) {
604                 emptyView.setText(R.string.development_settings_not_available);
605             }
606             return;
607         }
608
609         if (mDpm.getMaximumTimeToLock(null) > 0) {
610             // A DeviceAdmin has specified a maximum time until the device
611             // will lock...  in this case we can't allow the user to turn
612             // on "stay awake when plugged in" because that would defeat the
613             // restriction.
614             mDisabledPrefs.add(mKeepScreenOn);
615         } else {
616             mDisabledPrefs.remove(mKeepScreenOn);
617         }
618
619         final ContentResolver cr = getActivity().getContentResolver();
620         mLastEnabledState = Settings.Global.getInt(cr,
621                 Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
622         mSwitchBar.setChecked(mLastEnabledState);
623         setPrefsEnabledState(mLastEnabledState);
624
625         if (mHaveDebugSettings && !mLastEnabledState) {
626             // Overall debugging is disabled, but there are some debug
627             // settings that are enabled.  This is an invalid state.  Switch
628             // to debug settings being enabled, so the user knows there is
629             // stuff enabled and can turn it all off if they want.
630             Settings.Global.putInt(getActivity().getContentResolver(),
631                     Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
632             mLastEnabledState = true;
633             mSwitchBar.setChecked(mLastEnabledState);
634             setPrefsEnabledState(mLastEnabledState);
635         }
636         mSwitchBar.show();
637         updateKillAppLongpressBackOptions();
638
639         if (mColorModePreference != null) {
640             mColorModePreference.startListening();
641             mColorModePreference.updateCurrentAndSupported();
642         }
643     }
644
645     @Override
646     public void onPause() {
647         super.onPause();
648         if (mColorModePreference != null) {
649             mColorModePreference.stopListening();
650         }
651     }
652
653     @Override
654     public View onCreateView(LayoutInflater inflater, ViewGroup container,
655             Bundle savedInstanceState) {
656         IntentFilter filter = new IntentFilter();
657         filter.addAction(UsbManager.ACTION_USB_STATE);
658         getActivity().registerReceiver(mUsbReceiver, filter);
659         return super.onCreateView(inflater, container, savedInstanceState);
660     }
661
662     @Override
663     public void onDestroyView() {
664         super.onDestroyView();
665
666         if (mUnavailable) {
667             return;
668         }
669         mSwitchBar.removeOnSwitchChangeListener(this);
670         mSwitchBar.hide();
671         getActivity().unregisterReceiver(mUsbReceiver);
672     }
673
674     void updateSwitchPreference(SwitchPreference switchPreference, boolean value) {
675         switchPreference.setChecked(value);
676         mHaveDebugSettings |= value;
677     }
678
679     private void updateAllOptions() {
680         final Context context = getActivity();
681         final ContentResolver cr = context.getContentResolver();
682         mHaveDebugSettings = false;
683         updateSwitchPreference(mEnableAdb, Settings.Global.getInt(cr,
684                 Settings.Global.ADB_ENABLED, 0) != 0);
685
686         mAdbNotify.setChecked(CMSettings.Secure.getInt(cr,
687                 CMSettings.Secure.ADB_NOTIFY, 1) != 0);
688         updateAdbOverNetwork();
689
690         if (mEnableTerminal != null) {
691             updateSwitchPreference(mEnableTerminal,
692                     context.getPackageManager().getApplicationEnabledSetting(TERMINAL_APP_PACKAGE)
693                             == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
694         }
695         updateSwitchPreference(mBugreportInPower, Settings.Secure.getInt(cr,
696                 Settings.Secure.BUGREPORT_IN_POWER_MENU, 0) != 0);
697         updateStayAwakeOptions();
698         updateSwitchPreference(mBtHciSnoopLog, Settings.Secure.getInt(cr,
699                 Settings.Secure.BLUETOOTH_HCI_LOG, 0) != 0);
700         if (mEnableOemUnlock != null) {
701             updateSwitchPreference(mEnableOemUnlock, Utils.isOemUnlockEnabled(getActivity()));
702         }
703         updateSwitchPreference(mDebugViewAttributes, Settings.Global.getInt(cr,
704                 Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0);
705         updateHdcpValues();
706         updatePasswordSummary();
707         updateDebuggerOptions();
708         updateMockLocation();
709         updateStrictModeVisualOptions();
710         updatePointerLocationOptions();
711         updateShowTouchesOptions();
712         updateFlingerOptions();
713         updateCpuUsageOptions();
714         updateHardwareUiOptions();
715         updateMsaaOptions();
716         updateTrackFrameTimeOptions();
717         updateShowNonRectClipOptions();
718         updateShowHwScreenUpdatesOptions();
719         updateShowHwLayersUpdatesOptions();
720         updateDebugHwOverdrawOptions();
721         updateDebugLayoutOptions();
722         updateAnimationScaleOptions();
723         updateOverlayDisplayDevicesOptions();
724         if (mEnableMultiWindow != null) {
725             updateSwitchPreference(mEnableMultiWindow,
726                     SystemProperties.getBoolean(MULTI_WINDOW_SYSTEM_PROPERTY, false));
727         }
728         updateOpenGLTracesOptions();
729         updateImmediatelyDestroyActivitiesOptions();
730         updateAppProcessLimitOptions();
731         updateShowAllANRsOptions();
732         updateVerifyAppsOverUsbOptions();
733         updateBugreportOptions();
734         updateForceRtlOptions();
735         updateLogdSizeValues();
736         updateWifiDisplayCertificationOptions();
737         updateWifiVerboseLoggingOptions();
738         updateWifiAggressiveHandoverOptions();
739         updateWifiAllowScansWithTrafficOptions();
740         updateLegacyDhcpClientOptions();
741         updateMobileDataAlwaysOnOptions();
742         updateSimulateColorSpace();
743         updateUSBAudioOptions();
744         updateRootAccessOptions();
745         updateAdvancedRebootOptions();
746         updateDevelopmentShortcutOptions();
747         updateUpdateRecoveryOptions();
748         if (mColorTemperaturePreference != null) {
749             updateColorTemperature();
750         }
751     }
752
753     private void writeAdvancedRebootOptions() {
754         CMSettings.Secure.putInt(getActivity().getContentResolver(),
755                 CMSettings.Secure.ADVANCED_REBOOT,
756                 mAdvancedReboot.isChecked() ? 1 : 0);
757     }
758
759     private void updateAdvancedRebootOptions() {
760         mAdvancedReboot.setChecked(CMSettings.Secure.getInt(getActivity().getContentResolver(),
761                 CMSettings.Secure.ADVANCED_REBOOT, 0) != 0);
762     }
763
764     private void resetDevelopmentShortcutOptions() {
765         CMSettings.Secure.putInt(getActivity().getContentResolver(),
766                 CMSettings.Secure.DEVELOPMENT_SHORTCUT, 0);
767     }
768
769     private void writeDevelopmentShortcutOptions() {
770         CMSettings.Secure.putInt(getActivity().getContentResolver(),
771                 CMSettings.Secure.DEVELOPMENT_SHORTCUT,
772                 mDevelopmentShortcut.isChecked() ? 1 : 0);
773     }
774
775     private void updateDevelopmentShortcutOptions() {
776         mDevelopmentShortcut.setChecked(CMSettings.Secure.getInt(getActivity().getContentResolver(),
777                 CMSettings.Secure.DEVELOPMENT_SHORTCUT, 0) != 0);
778     }
779
780     private void updateAdbOverNetwork() {
781         int port = CMSettings.Secure.getInt(getActivity().getContentResolver(),
782                 CMSettings.Secure.ADB_PORT, 0);
783         boolean enabled = port > 0;
784
785         updateSwitchPreference(mAdbOverNetwork, enabled);
786
787         WifiInfo wifiInfo = null;
788
789         if (enabled) {
790             IWifiManager wifiManager = IWifiManager.Stub.asInterface(
791                     ServiceManager.getService(Context.WIFI_SERVICE));
792             try {
793                 wifiInfo = wifiManager.getConnectionInfo();
794             } catch (RemoteException e) {
795                 Log.e(TAG, "wifiManager, getConnectionInfo()", e);
796             }
797         }
798
799         if (wifiInfo != null) {
800             String hostAddress = NetworkUtils.intToInetAddress(
801                     wifiInfo.getIpAddress()).getHostAddress();
802             mAdbOverNetwork.setSummary(hostAddress + ":" + String.valueOf(port));
803         } else {
804             mAdbOverNetwork.setSummary(R.string.adb_over_network_summary);
805         }
806     }
807
808     private void resetDangerousOptions() {
809         mDontPokeProperties = true;
810         for (int i=0; i< mResetSwitchPrefs.size(); i++) {
811             SwitchPreference cb = mResetSwitchPrefs.get(i);
812             if (cb.isChecked()) {
813                 cb.setChecked(false);
814                 onPreferenceTreeClick(null, cb);
815             }
816         }
817         resetDebuggerOptions();
818         writeLogdSizeOption(null);
819         resetRootAccessOptions();
820         resetAdbNotifyOptions();
821         resetVerifyAppsOverUsbOptions();
822         resetDevelopmentShortcutOptions();
823         resetUpdateRecoveryOptions();
824         writeAnimationScaleOption(0, mWindowAnimationScale, null);
825         writeAnimationScaleOption(1, mTransitionAnimationScale, null);
826         writeAnimationScaleOption(2, mAnimatorDurationScale, null);
827         // Only poke the color space setting if we control it.
828         if (usingDevelopmentColorSpace()) {
829             writeSimulateColorSpace(-1);
830         }
831         writeOverlayDisplayDevicesOptions(null);
832         writeAppProcessLimitOptions(null);
833         mHaveDebugSettings = false;
834         updateAllOptions();
835         mDontPokeProperties = false;
836         pokeSystemProperties();
837     }
838
839    private void updateRootAccessOptions() {
840         String value = SystemProperties.get(ROOT_ACCESS_PROPERTY, "0");
841         mRootAccess.setValue(value);
842         mRootAccess.setSummary(getResources()
843                 .getStringArray(R.array.root_access_entries)[Integer.valueOf(value)]);
844     }
845
846     private boolean isRootForAppsAvailable() {
847         boolean exists = false;
848         try {
849             File f = new File(SUPERUSER_BINARY_PATH);
850             exists = f.exists();
851         } catch (SecurityException e) {
852             // Ignore
853         }
854         return exists;
855     }
856
857     public static boolean isRootForAppsEnabled() {
858         int value = SystemProperties.getInt(ROOT_ACCESS_PROPERTY, 0);
859         boolean daemonState =
860                 SystemProperties.get("init.svc.su_daemon", "absent").equals("running");
861         return daemonState && (value == 1 || value == 3);
862     }
863
864     private void writeRootAccessOptions(Object newValue) {
865         String oldValue = SystemProperties.get(ROOT_ACCESS_PROPERTY, "0");
866         SystemProperties.set(ROOT_ACCESS_PROPERTY, newValue.toString());
867         if (Integer.valueOf(newValue.toString()) < 2 && !oldValue.equals(newValue)
868                 && "1".equals(SystemProperties.get("service.adb.root", "0"))) {
869             SystemProperties.set("service.adb.root", "0");
870             Settings.Global.putInt(getActivity().getContentResolver(),
871                     Settings.Global.ADB_ENABLED, 0);
872             Settings.Global.putInt(getActivity().getContentResolver(),
873                     Settings.Global.ADB_ENABLED, 1);
874         }
875         updateRootAccessOptions();
876     }
877
878     private void resetRootAccessOptions() {
879         String oldValue = SystemProperties.get(ROOT_ACCESS_PROPERTY, "0");
880         SystemProperties.set(ROOT_ACCESS_PROPERTY, "0");
881         if (!oldValue.equals("0") && "1".equals(SystemProperties.get("service.adb.root", "0"))) {
882             SystemProperties.set("service.adb.root", "0");
883             Settings.Global.putInt(getActivity().getContentResolver(),
884                     Settings.Global.ADB_ENABLED, 0);
885             Settings.Global.putInt(getActivity().getContentResolver(),
886                     Settings.Global.ADB_ENABLED, 1);
887         }
888         updateRootAccessOptions();
889     }
890
891     private void resetAdbNotifyOptions() {
892         CMSettings.Secure.putInt(getActivity().getContentResolver(),
893                 CMSettings.Secure.ADB_NOTIFY, 1);
894     }
895
896     private void updateStayAwakeOptions() {
897         int index = Settings.Global.getInt(getActivity().getContentResolver(),
898                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
899         final String[] values = getResources().getStringArray(R.array.keep_screen_on_values);
900         final String[] summaries = getResources().getStringArray(R.array.keep_screen_on_titles);
901         // The old value contained 0 (disable) or 3 (BATTERY_PLUGGED_AC|BATTERY_PLUGGED_USB)
902         // Currently only have 3 values (0: Not enabled; 1: debugging over usb; >2: charging)
903         // NOTE: If we have newer values, then we need to migrate
904         // this property
905         if (index >= values.length) {
906             index = values.length - 1;
907         }
908         mKeepScreenOn.setValue(values[index]);
909         mKeepScreenOn.setSummary(summaries[index]);
910         mKeepScreenOn.setOnPreferenceChangeListener(this);
911     }
912
913     private void updateHdcpValues() {
914         ListPreference hdcpChecking = (ListPreference) findPreference(HDCP_CHECKING_KEY);
915         if (hdcpChecking != null) {
916             String currentValue = SystemProperties.get(HDCP_CHECKING_PROPERTY);
917             String[] values = getResources().getStringArray(R.array.hdcp_checking_values);
918             String[] summaries = getResources().getStringArray(R.array.hdcp_checking_summaries);
919             int index = 1; // Defaults to drm-only. Needs to match with R.array.hdcp_checking_values
920             for (int i = 0; i < values.length; i++) {
921                 if (currentValue.equals(values[i])) {
922                     index = i;
923                     break;
924                 }
925             }
926             hdcpChecking.setValue(values[index]);
927             hdcpChecking.setSummary(summaries[index]);
928             hdcpChecking.setOnPreferenceChangeListener(this);
929         }
930     }
931
932     private void writeKillAppLongpressBackOptions() {
933         CMSettings.Secure.putInt(getActivity().getContentResolver(),
934                 CMSettings.Secure.KILL_APP_LONGPRESS_BACK,
935                 mKillAppLongpressBack.isChecked() ? 1 : 0);
936     }
937
938     private void updateKillAppLongpressBackOptions() {
939         mKillAppLongpressBack.setChecked(CMSettings.Secure.getInt(
940             getActivity().getContentResolver(), CMSettings.Secure.KILL_APP_LONGPRESS_BACK, 0) != 0);
941     }
942
943     private void updatePasswordSummary() {
944         try {
945             if (mBackupManager.hasBackupPassword()) {
946                 mPassword.setSummary(R.string.local_backup_password_summary_change);
947             } else {
948                 mPassword.setSummary(R.string.local_backup_password_summary_none);
949             }
950         } catch (RemoteException e) {
951             // Not much we can do here
952         }
953     }
954
955     private void writeBtHciSnoopLogOptions() {
956         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
957         adapter.configHciSnoopLog(mBtHciSnoopLog.isChecked());
958         Settings.Secure.putInt(getActivity().getContentResolver(),
959                 Settings.Secure.BLUETOOTH_HCI_LOG,
960                 mBtHciSnoopLog.isChecked() ? 1 : 0);
961     }
962
963     private void writeDebuggerOptions() {
964         try {
965             ActivityManagerNative.getDefault().setDebugApp(
966                 mDebugApp, mWaitForDebugger.isChecked(), true);
967         } catch (RemoteException ex) {
968         }
969     }
970
971     private void writeMockLocation() {
972         AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
973
974         // Disable the app op of the previous mock location app if such.
975         List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
976         if (packageOps != null) {
977             // Should be one but in case we are in a bad state due to use of command line tools.
978             for (PackageOps packageOp : packageOps) {
979                 if (packageOp.getOps().get(0).getMode() != AppOpsManager.MODE_ERRORED) {
980                     String oldMockLocationApp = packageOp.getPackageName();
981                     try {
982                         ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
983                                 oldMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
984                         appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
985                                 oldMockLocationApp, AppOpsManager.MODE_ERRORED);
986                     } catch (NameNotFoundException e) {
987                         /* ignore */
988                     }
989                 }
990             }
991         }
992
993         // Enable the app op of the new mock location app if such.
994         if (!TextUtils.isEmpty(mMockLocationApp)) {
995             try {
996                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
997                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
998                 appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
999                         mMockLocationApp, AppOpsManager.MODE_ALLOWED);
1000             } catch (NameNotFoundException e) {
1001                 /* ignore */
1002             }
1003         }
1004     }
1005
1006     private static void resetDebuggerOptions() {
1007         try {
1008             ActivityManagerNative.getDefault().setDebugApp(
1009                     null, false, true);
1010         } catch (RemoteException ex) {
1011         }
1012     }
1013
1014     private void updateDebuggerOptions() {
1015         mDebugApp = Settings.Global.getString(
1016                 getActivity().getContentResolver(), Settings.Global.DEBUG_APP);
1017         updateSwitchPreference(mWaitForDebugger, Settings.Global.getInt(
1018                 getActivity().getContentResolver(), Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0);
1019         if (mDebugApp != null && mDebugApp.length() > 0) {
1020             String label;
1021             try {
1022                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mDebugApp,
1023                         PackageManager.GET_DISABLED_COMPONENTS);
1024                 CharSequence lab = getActivity().getPackageManager().getApplicationLabel(ai);
1025                 label = lab != null ? lab.toString() : mDebugApp;
1026             } catch (PackageManager.NameNotFoundException e) {
1027                 label = mDebugApp;
1028             }
1029             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_set, label));
1030             mWaitForDebugger.setEnabled(true);
1031             mHaveDebugSettings = true;
1032         } else {
1033             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_not_set));
1034             mWaitForDebugger.setEnabled(false);
1035         }
1036     }
1037
1038     private void updateMockLocation() {
1039         AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
1040
1041         List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
1042         if (packageOps != null) {
1043             for (PackageOps packageOp : packageOps) {
1044                 if (packageOp.getOps().get(0).getMode() == AppOpsManager.MODE_ALLOWED) {
1045                     mMockLocationApp = packageOps.get(0).getPackageName();
1046                     break;
1047                 }
1048             }
1049         }
1050
1051         if (!TextUtils.isEmpty(mMockLocationApp)) {
1052             String label = mMockLocationApp;
1053             try {
1054                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
1055                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
1056                 CharSequence appLabel = getPackageManager().getApplicationLabel(ai);
1057                 if (appLabel != null) {
1058                     label = appLabel.toString();
1059                 }
1060             } catch (PackageManager.NameNotFoundException e) {
1061                 /* ignore */
1062             }
1063
1064             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_set, label));
1065             mHaveDebugSettings = true;
1066         } else {
1067             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_not_set));
1068         }
1069     }
1070
1071     private void updateVerifyAppsOverUsbOptions() {
1072         updateSwitchPreference(mVerifyAppsOverUsb, Settings.Global.getInt(getActivity().getContentResolver(),
1073                 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0);
1074         mVerifyAppsOverUsb.setEnabled(enableVerifierSetting());
1075     }
1076
1077     private void writeVerifyAppsOverUsbOptions() {
1078         Settings.Global.putInt(getActivity().getContentResolver(),
1079               Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, mVerifyAppsOverUsb.isChecked() ? 1 : 0);
1080     }
1081
1082     private void resetVerifyAppsOverUsbOptions() {
1083         Settings.Global.putInt(getActivity().getContentResolver(),
1084               Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1);
1085     }
1086
1087     private boolean enableVerifierSetting() {
1088         final ContentResolver cr = getActivity().getContentResolver();
1089         if (Settings.Global.getInt(cr, Settings.Global.ADB_ENABLED, 0) == 0) {
1090             return false;
1091         }
1092         if (Settings.Global.getInt(cr, Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 0) {
1093             return false;
1094         } else {
1095             final PackageManager pm = getActivity().getPackageManager();
1096             final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1097             verification.setType(PACKAGE_MIME_TYPE);
1098             verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1099             final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(verification, 0);
1100             if (receivers.size() == 0) {
1101                 return false;
1102             }
1103         }
1104         return true;
1105     }
1106
1107     private boolean showVerifierSetting() {
1108         return Settings.Global.getInt(getActivity().getContentResolver(),
1109                 Settings.Global.PACKAGE_VERIFIER_SETTING_VISIBLE, 1) > 0;
1110     }
1111
1112     private static boolean showEnableOemUnlockPreference() {
1113         return !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
1114     }
1115
1116     private static boolean showEnableMultiWindowPreference() {
1117         return !"user".equals(Build.TYPE);
1118     }
1119
1120     private void setEnableMultiWindow(boolean value) {
1121         SystemProperties.set(MULTI_WINDOW_SYSTEM_PROPERTY, String.valueOf(value));
1122         pokeSystemProperties();
1123     }
1124
1125     private void updateBugreportOptions() {
1126         final ComponentName bugreportStorageProviderComponentName =
1127                 new ComponentName("com.android.shell",
1128                         "com.android.shell.BugreportStorageProvider");
1129         if ("user".equals(Build.TYPE)) {
1130             final ContentResolver resolver = getActivity().getContentResolver();
1131             final boolean adbEnabled = Settings.Global.getInt(
1132                     resolver, Settings.Global.ADB_ENABLED, 0) != 0;
1133             if (adbEnabled) {
1134                 mBugreport.setEnabled(true);
1135                 mBugreportInPower.setEnabled(true);
1136                 getPackageManager().setComponentEnabledSetting(
1137                         bugreportStorageProviderComponentName,
1138                         PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
1139             } else {
1140                 mBugreport.setEnabled(false);
1141                 mBugreportInPower.setEnabled(false);
1142                 mBugreportInPower.setChecked(false);
1143                 Settings.Secure.putInt(resolver, Settings.Secure.BUGREPORT_IN_POWER_MENU, 0);
1144                 getPackageManager().setComponentEnabledSetting(
1145                         bugreportStorageProviderComponentName,
1146                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
1147             }
1148         } else {
1149             mBugreportInPower.setEnabled(true);
1150             getPackageManager().setComponentEnabledSetting(
1151                     bugreportStorageProviderComponentName,
1152                     PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
1153         }
1154     }
1155
1156     // Returns the current state of the system property that controls
1157     // strictmode flashes.  One of:
1158     //    0: not explicitly set one way or another
1159     //    1: on
1160     //    2: off
1161     private static int currentStrictModeActiveIndex() {
1162         if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) {
1163             return 0;
1164         }
1165         boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false);
1166         return enabled ? 1 : 2;
1167     }
1168
1169     private void writeStrictModeVisualOptions() {
1170         try {
1171             mWindowManager.setStrictModeVisualIndicatorPreference(mStrictMode.isChecked()
1172                     ? "1" : "");
1173         } catch (RemoteException e) {
1174         }
1175     }
1176
1177     private void updateStrictModeVisualOptions() {
1178         updateSwitchPreference(mStrictMode, currentStrictModeActiveIndex() == 1);
1179     }
1180
1181     private void writePointerLocationOptions() {
1182         Settings.System.putInt(getActivity().getContentResolver(),
1183                 Settings.System.POINTER_LOCATION, mPointerLocation.isChecked() ? 1 : 0);
1184     }
1185
1186     private void updatePointerLocationOptions() {
1187         updateSwitchPreference(mPointerLocation,
1188                 Settings.System.getInt(getActivity().getContentResolver(),
1189                 Settings.System.POINTER_LOCATION, 0) != 0);
1190     }
1191
1192     private void writeShowTouchesOptions() {
1193         Settings.System.putInt(getActivity().getContentResolver(),
1194                 Settings.System.SHOW_TOUCHES, mShowTouches.isChecked() ? 1 : 0);
1195     }
1196
1197     private void updateShowTouchesOptions() {
1198         updateSwitchPreference(mShowTouches,
1199                 Settings.System.getInt(getActivity().getContentResolver(),
1200                 Settings.System.SHOW_TOUCHES, 0) != 0);
1201     }
1202
1203     private void updateFlingerOptions() {
1204         // magic communication with surface flinger.
1205         try {
1206             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1207             if (flinger != null) {
1208                 Parcel data = Parcel.obtain();
1209                 Parcel reply = Parcel.obtain();
1210                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1211                 flinger.transact(1010, data, reply, 0);
1212                 @SuppressWarnings("unused")
1213                 int showCpu = reply.readInt();
1214                 @SuppressWarnings("unused")
1215                 int enableGL = reply.readInt();
1216                 int showUpdates = reply.readInt();
1217                 updateSwitchPreference(mShowScreenUpdates, showUpdates != 0);
1218                 @SuppressWarnings("unused")
1219                 int showBackground = reply.readInt();
1220                 int disableOverlays = reply.readInt();
1221                 updateSwitchPreference(mDisableOverlays, disableOverlays != 0);
1222                 reply.recycle();
1223                 data.recycle();
1224             }
1225         } catch (RemoteException ex) {
1226         }
1227     }
1228
1229     private void writeShowUpdatesOption() {
1230         try {
1231             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1232             if (flinger != null) {
1233                 Parcel data = Parcel.obtain();
1234                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1235                 final int showUpdates = mShowScreenUpdates.isChecked() ? 1 : 0;
1236                 data.writeInt(showUpdates);
1237                 flinger.transact(1002, data, null, 0);
1238                 data.recycle();
1239
1240                 updateFlingerOptions();
1241             }
1242         } catch (RemoteException ex) {
1243         }
1244     }
1245
1246     private void writeDisableOverlaysOption() {
1247         try {
1248             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1249             if (flinger != null) {
1250                 Parcel data = Parcel.obtain();
1251                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1252                 final int disableOverlays = mDisableOverlays.isChecked() ? 1 : 0;
1253                 data.writeInt(disableOverlays);
1254                 flinger.transact(1008, data, null, 0);
1255                 data.recycle();
1256
1257                 updateFlingerOptions();
1258             }
1259         } catch (RemoteException ex) {
1260         }
1261     }
1262
1263     private void updateHardwareUiOptions() {
1264         updateSwitchPreference(mForceHardwareUi, SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false));
1265     }
1266
1267     private void writeHardwareUiOptions() {
1268         SystemProperties.set(HARDWARE_UI_PROPERTY, mForceHardwareUi.isChecked() ? "true" : "false");
1269         pokeSystemProperties();
1270     }
1271
1272     private void updateMsaaOptions() {
1273         updateSwitchPreference(mForceMsaa, SystemProperties.getBoolean(MSAA_PROPERTY, false));
1274     }
1275
1276     private void writeMsaaOptions() {
1277         SystemProperties.set(MSAA_PROPERTY, mForceMsaa.isChecked() ? "true" : "false");
1278         pokeSystemProperties();
1279     }
1280
1281     private void updateTrackFrameTimeOptions() {
1282         String value = SystemProperties.get(HardwareRenderer.PROFILE_PROPERTY);
1283         if (value == null) {
1284             value = "";
1285         }
1286
1287         CharSequence[] values = mTrackFrameTime.getEntryValues();
1288         for (int i = 0; i < values.length; i++) {
1289             if (value.contentEquals(values[i])) {
1290                 mTrackFrameTime.setValueIndex(i);
1291                 mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[i]);
1292                 return;
1293             }
1294         }
1295         mTrackFrameTime.setValueIndex(0);
1296         mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[0]);
1297     }
1298
1299     private void writeTrackFrameTimeOptions(Object newValue) {
1300         SystemProperties.set(HardwareRenderer.PROFILE_PROPERTY,
1301                 newValue == null ? "" : newValue.toString());
1302         pokeSystemProperties();
1303         updateTrackFrameTimeOptions();
1304     }
1305
1306     private void updateShowNonRectClipOptions() {
1307         String value = SystemProperties.get(
1308                 HardwareRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY);
1309         if (value == null) {
1310             value = "hide";
1311         }
1312
1313         CharSequence[] values = mShowNonRectClip.getEntryValues();
1314         for (int i = 0; i < values.length; i++) {
1315             if (value.contentEquals(values[i])) {
1316                 mShowNonRectClip.setValueIndex(i);
1317                 mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[i]);
1318                 return;
1319             }
1320         }
1321         mShowNonRectClip.setValueIndex(0);
1322         mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[0]);
1323     }
1324
1325     private void writeStayAwakeOptions(Object newValue) {
1326         int val = Integer.parseInt((String) newValue);
1327         Settings.Global.putInt(getActivity().getContentResolver(),
1328                     Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
1329         updateStayAwakeOptions();
1330     }
1331
1332     private void writeShowNonRectClipOptions(Object newValue) {
1333         SystemProperties.set(HardwareRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY,
1334                 newValue == null ? "" : newValue.toString());
1335         pokeSystemProperties();
1336         updateShowNonRectClipOptions();
1337     }
1338
1339     private void updateShowHwScreenUpdatesOptions() {
1340         updateSwitchPreference(mShowHwScreenUpdates,
1341                 SystemProperties.getBoolean(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, false));
1342     }
1343
1344     private void writeShowHwScreenUpdatesOptions() {
1345         SystemProperties.set(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY,
1346                 mShowHwScreenUpdates.isChecked() ? "true" : null);
1347         pokeSystemProperties();
1348     }
1349
1350     private void updateShowHwLayersUpdatesOptions() {
1351         updateSwitchPreference(mShowHwLayersUpdates, SystemProperties.getBoolean(
1352                 HardwareRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY, false));
1353     }
1354
1355     private void writeShowHwLayersUpdatesOptions() {
1356         SystemProperties.set(HardwareRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY,
1357                 mShowHwLayersUpdates.isChecked() ? "true" : null);
1358         pokeSystemProperties();
1359     }
1360
1361     private void updateDebugHwOverdrawOptions() {
1362         String value = SystemProperties.get(HardwareRenderer.DEBUG_OVERDRAW_PROPERTY);
1363         if (value == null) {
1364             value = "";
1365         }
1366
1367         CharSequence[] values = mDebugHwOverdraw.getEntryValues();
1368         for (int i = 0; i < values.length; i++) {
1369             if (value.contentEquals(values[i])) {
1370                 mDebugHwOverdraw.setValueIndex(i);
1371                 mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[i]);
1372                 return;
1373             }
1374         }
1375         mDebugHwOverdraw.setValueIndex(0);
1376         mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[0]);
1377     }
1378
1379     private void writeDebugHwOverdrawOptions(Object newValue) {
1380         SystemProperties.set(HardwareRenderer.DEBUG_OVERDRAW_PROPERTY,
1381                 newValue == null ? "" : newValue.toString());
1382         pokeSystemProperties();
1383         updateDebugHwOverdrawOptions();
1384     }
1385
1386     private void updateDebugLayoutOptions() {
1387         updateSwitchPreference(mDebugLayout,
1388                 SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false));
1389     }
1390
1391     private void writeDebugLayoutOptions() {
1392         SystemProperties.set(View.DEBUG_LAYOUT_PROPERTY,
1393                 mDebugLayout.isChecked() ? "true" : "false");
1394         pokeSystemProperties();
1395     }
1396
1397     private void updateSimulateColorSpace() {
1398         final ContentResolver cr = getContentResolver();
1399         final boolean enabled = Settings.Secure.getInt(
1400                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1401         if (enabled) {
1402             final String mode = Integer.toString(Settings.Secure.getInt(
1403                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1404                     AccessibilityManager.DALTONIZER_DISABLED));
1405             mSimulateColorSpace.setValue(mode);
1406             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1407             if (index < 0) {
1408                 // We're using a mode controlled by accessibility preferences.
1409                 mSimulateColorSpace.setSummary(getString(R.string.daltonizer_type_overridden,
1410                         getString(R.string.accessibility_display_daltonizer_preference_title)));
1411             } else {
1412                 mSimulateColorSpace.setSummary("%s");
1413             }
1414         } else {
1415             mSimulateColorSpace.setValue(
1416                     Integer.toString(AccessibilityManager.DALTONIZER_DISABLED));
1417         }
1418     }
1419
1420     /**
1421      * @return <code>true</code> if the color space preference is currently
1422      *         controlled by development settings
1423      */
1424     private boolean usingDevelopmentColorSpace() {
1425         final ContentResolver cr = getContentResolver();
1426         final boolean enabled = Settings.Secure.getInt(
1427                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1428         if (enabled) {
1429             final String mode = Integer.toString(Settings.Secure.getInt(
1430                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1431                     AccessibilityManager.DALTONIZER_DISABLED));
1432             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1433             if (index >= 0) {
1434                 // We're using a mode controlled by developer preferences.
1435                 return true;
1436             }
1437         }
1438         return false;
1439     }
1440
1441     private void writeSimulateColorSpace(Object value) {
1442         final ContentResolver cr = getContentResolver();
1443         final int newMode = Integer.parseInt(value.toString());
1444         if (newMode < 0) {
1445             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0);
1446         } else {
1447             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 1);
1448             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, newMode);
1449         }
1450     }
1451
1452     private void updateColorTemperature() {
1453         updateSwitchPreference(mColorTemperaturePreference,
1454                 SystemProperties.getBoolean(COLOR_TEMPERATURE_PROPERTY, false));
1455     }
1456
1457     private void writeColorTemperature() {
1458         SystemProperties.set(COLOR_TEMPERATURE_PROPERTY,
1459                 mColorTemperaturePreference.isChecked() ? "1" : "0");
1460         pokeSystemProperties();
1461         Toast.makeText(getActivity(), R.string.color_temperature_toast, Toast.LENGTH_LONG).show();
1462     }
1463
1464     private void updateUSBAudioOptions() {
1465         updateSwitchPreference(mUSBAudio, Settings.Secure.getInt(getContentResolver(),
1466                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED, 0) != 0);
1467     }
1468
1469     private void writeUSBAudioOptions() {
1470         Settings.Secure.putInt(getContentResolver(),
1471                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED,
1472                 mUSBAudio.isChecked() ? 1 : 0);
1473     }
1474
1475     private void updateForceRtlOptions() {
1476         updateSwitchPreference(mForceRtlLayout,
1477                 Settings.Global.getInt(getActivity().getContentResolver(),
1478                 Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0);
1479     }
1480
1481     private void writeForceRtlOptions() {
1482         boolean value = mForceRtlLayout.isChecked();
1483         Settings.Global.putInt(getActivity().getContentResolver(),
1484                 Settings.Global.DEVELOPMENT_FORCE_RTL, value ? 1 : 0);
1485         SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, value ? "1" : "0");
1486         LocalePicker.updateLocale(getActivity().getResources().getConfiguration().locale);
1487     }
1488
1489     private void updateWifiDisplayCertificationOptions() {
1490         updateSwitchPreference(mWifiDisplayCertification, Settings.Global.getInt(
1491                 getActivity().getContentResolver(),
1492                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, 0) != 0);
1493     }
1494
1495     private void writeWifiDisplayCertificationOptions() {
1496         Settings.Global.putInt(getActivity().getContentResolver(),
1497                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
1498                 mWifiDisplayCertification.isChecked() ? 1 : 0);
1499     }
1500
1501     private void updateWifiVerboseLoggingOptions() {
1502         boolean enabled = mWifiManager.getVerboseLoggingLevel() > 0;
1503         updateSwitchPreference(mWifiVerboseLogging, enabled);
1504     }
1505
1506     private void writeWifiVerboseLoggingOptions() {
1507         mWifiManager.enableVerboseLogging(mWifiVerboseLogging.isChecked() ? 1 : 0);
1508     }
1509
1510     private void updateWifiAggressiveHandoverOptions() {
1511         boolean enabled = mWifiManager.getAggressiveHandover() > 0;
1512         updateSwitchPreference(mWifiAggressiveHandover, enabled);
1513     }
1514
1515     private void writeWifiAggressiveHandoverOptions() {
1516         mWifiManager.enableAggressiveHandover(mWifiAggressiveHandover.isChecked() ? 1 : 0);
1517     }
1518
1519     private void updateWifiAllowScansWithTrafficOptions() {
1520         boolean enabled = mWifiManager.getAllowScansWithTraffic() > 0;
1521         updateSwitchPreference(mWifiAllowScansWithTraffic, enabled);
1522     }
1523
1524     private void writeWifiAllowScansWithTrafficOptions() {
1525         mWifiManager.setAllowScansWithTraffic(mWifiAllowScansWithTraffic.isChecked() ? 1 : 0);
1526     }
1527
1528     private void updateLegacyDhcpClientOptions() {
1529         updateSwitchPreference(mLegacyDhcpClient, Settings.Global.getInt(
1530                 getActivity().getContentResolver(),
1531                 Settings.Global.LEGACY_DHCP_CLIENT, 0) != 0);
1532     }
1533
1534     private void writeLegacyDhcpClientOptions() {
1535         Settings.Global.putInt(getActivity().getContentResolver(),
1536                 Settings.Global.LEGACY_DHCP_CLIENT,
1537                 mLegacyDhcpClient.isChecked() ? 1 : 0);
1538     }
1539
1540     private void updateMobileDataAlwaysOnOptions() {
1541         updateSwitchPreference(mMobileDataAlwaysOn, Settings.Global.getInt(
1542                 getActivity().getContentResolver(),
1543                 Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) != 0);
1544     }
1545
1546     private void writeMobileDataAlwaysOnOptions() {
1547         Settings.Global.putInt(getActivity().getContentResolver(),
1548                 Settings.Global.MOBILE_DATA_ALWAYS_ON,
1549                 mMobileDataAlwaysOn.isChecked() ? 1 : 0);
1550     }
1551
1552     private void updateLogdSizeValues() {
1553         if (mLogdSize != null) {
1554             String currentValue = SystemProperties.get(SELECT_LOGD_SIZE_PROPERTY);
1555             if (currentValue == null) {
1556                 currentValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1557                 if (currentValue == null) {
1558                     currentValue = "256K";
1559                 }
1560             }
1561             String[] values = getResources().getStringArray(R.array.select_logd_size_values);
1562             String[] titles = getResources().getStringArray(R.array.select_logd_size_titles);
1563             if (SystemProperties.get("ro.config.low_ram").equals("true")) {
1564                 mLogdSize.setEntries(R.array.select_logd_size_lowram_titles);
1565                 titles = getResources().getStringArray(R.array.select_logd_size_lowram_titles);
1566             }
1567             String[] summaries = getResources().getStringArray(R.array.select_logd_size_summaries);
1568             int index = 1; // punt to second entry if not found
1569             for (int i = 0; i < titles.length; i++) {
1570                 if (currentValue.equals(values[i])
1571                         || currentValue.equals(titles[i])) {
1572                     index = i;
1573                     break;
1574                 }
1575             }
1576             mLogdSize.setValue(values[index]);
1577             mLogdSize.setSummary(summaries[index]);
1578             mLogdSize.setOnPreferenceChangeListener(this);
1579         }
1580     }
1581
1582     private void writeLogdSizeOption(Object newValue) {
1583         String currentValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1584         if (currentValue != null) {
1585             DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES = currentValue;
1586         }
1587         final String size = (newValue != null) ?
1588                 newValue.toString() : DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES;
1589         SystemProperties.set(SELECT_LOGD_SIZE_PROPERTY, size);
1590         pokeSystemProperties();
1591         try {
1592             Process p = Runtime.getRuntime().exec("logcat -b all -G " + size);
1593             p.waitFor();
1594             Log.i(TAG, "Logcat ring buffer sizes set to: " + size);
1595         } catch (Exception e) {
1596             Log.w(TAG, "Cannot set logcat ring buffer sizes", e);
1597         }
1598         updateLogdSizeValues();
1599     }
1600
1601     private void updateUsbConfigurationValues(boolean isUnlocked) {
1602         if (mUsbConfiguration != null) {
1603             UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
1604
1605             String[] values = getResources().getStringArray(R.array.usb_configuration_values);
1606             String[] titles = getResources().getStringArray(R.array.usb_configuration_titles);
1607             int index = 0;
1608             // Assume if !isUnlocked -> charging, which should be at index 0
1609             for (int i = 0; i < titles.length && isUnlocked; i++) {
1610                 if (manager.isFunctionEnabled(values[i])) {
1611                     index = i;
1612                     break;
1613                 }
1614             }
1615             mUsbConfiguration.setValue(values[index]);
1616             mUsbConfiguration.setSummary(titles[index]);
1617             mUsbConfiguration.setOnPreferenceChangeListener(this);
1618         }
1619     }
1620
1621     private void writeUsbConfigurationOption(Object newValue) {
1622         UsbManager manager = (UsbManager)getActivity().getSystemService(Context.USB_SERVICE);
1623         String function = newValue.toString();
1624         if (function.equals("none")) {
1625             manager.setCurrentFunction(null);
1626             manager.setUsbDataUnlocked(false);
1627         } else {
1628             manager.setCurrentFunction(function);
1629             manager.setUsbDataUnlocked(true);
1630         }
1631     }
1632
1633     private void updateCpuUsageOptions() {
1634         updateSwitchPreference(mShowCpuUsage,
1635                 Settings.Global.getInt(getActivity().getContentResolver(),
1636                 Settings.Global.SHOW_PROCESSES, 0) != 0);
1637     }
1638
1639     private void writeCpuUsageOptions() {
1640         boolean value = mShowCpuUsage.isChecked();
1641         Settings.Global.putInt(getActivity().getContentResolver(),
1642                 Settings.Global.SHOW_PROCESSES, value ? 1 : 0);
1643         Intent service = (new Intent())
1644                 .setClassName("com.android.systemui", "com.android.systemui.LoadAverageService");
1645         if (value) {
1646             getActivity().startService(service);
1647         } else {
1648             getActivity().stopService(service);
1649         }
1650     }
1651
1652     private void writeImmediatelyDestroyActivitiesOptions() {
1653         try {
1654             ActivityManagerNative.getDefault().setAlwaysFinish(
1655                     mImmediatelyDestroyActivities.isChecked());
1656         } catch (RemoteException ex) {
1657         }
1658     }
1659
1660     private void updateImmediatelyDestroyActivitiesOptions() {
1661         updateSwitchPreference(mImmediatelyDestroyActivities, Settings.Global.getInt(
1662                 getActivity().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0);
1663     }
1664
1665     private void updateAnimationScaleValue(int which, AnimationScalePreference pref) {
1666         try {
1667             float scale = mWindowManager.getAnimationScale(which);
1668             if (scale != 1) {
1669                 mHaveDebugSettings = true;
1670             }
1671             pref.setScale(scale);
1672         } catch (RemoteException e) {
1673         }
1674     }
1675
1676     private void updateAnimationScaleOptions() {
1677         updateAnimationScaleValue(0, mWindowAnimationScale);
1678         updateAnimationScaleValue(1, mTransitionAnimationScale);
1679         updateAnimationScaleValue(2, mAnimatorDurationScale);
1680     }
1681
1682     private void writeAnimationScaleOption(int which, AnimationScalePreference pref,
1683             Object newValue) {
1684         try {
1685             float scale = newValue != null ? Float.parseFloat(newValue.toString()) : 1;
1686             mWindowManager.setAnimationScale(which, scale);
1687             updateAnimationScaleValue(which, pref);
1688         } catch (RemoteException e) {
1689         }
1690     }
1691
1692     private void updateOverlayDisplayDevicesOptions() {
1693         String value = Settings.Global.getString(getActivity().getContentResolver(),
1694                 Settings.Global.OVERLAY_DISPLAY_DEVICES);
1695         if (value == null) {
1696             value = "";
1697         }
1698
1699         CharSequence[] values = mOverlayDisplayDevices.getEntryValues();
1700         for (int i = 0; i < values.length; i++) {
1701             if (value.contentEquals(values[i])) {
1702                 mOverlayDisplayDevices.setValueIndex(i);
1703                 mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[i]);
1704                 return;
1705             }
1706         }
1707         mOverlayDisplayDevices.setValueIndex(0);
1708         mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[0]);
1709     }
1710
1711     private void writeOverlayDisplayDevicesOptions(Object newValue) {
1712         Settings.Global.putString(getActivity().getContentResolver(),
1713                 Settings.Global.OVERLAY_DISPLAY_DEVICES, (String)newValue);
1714         updateOverlayDisplayDevicesOptions();
1715     }
1716
1717     private void updateOpenGLTracesOptions() {
1718         String value = SystemProperties.get(OPENGL_TRACES_PROPERTY);
1719         if (value == null) {
1720             value = "";
1721         }
1722
1723         CharSequence[] values = mOpenGLTraces.getEntryValues();
1724         for (int i = 0; i < values.length; i++) {
1725             if (value.contentEquals(values[i])) {
1726                 mOpenGLTraces.setValueIndex(i);
1727                 mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[i]);
1728                 return;
1729             }
1730         }
1731         mOpenGLTraces.setValueIndex(0);
1732         mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[0]);
1733     }
1734
1735     private void writeOpenGLTracesOptions(Object newValue) {
1736         SystemProperties.set(OPENGL_TRACES_PROPERTY, newValue == null ? "" : newValue.toString());
1737         pokeSystemProperties();
1738         updateOpenGLTracesOptions();
1739     }
1740
1741     private void updateAppProcessLimitOptions() {
1742         try {
1743             int limit = ActivityManagerNative.getDefault().getProcessLimit();
1744             CharSequence[] values = mAppProcessLimit.getEntryValues();
1745             for (int i=0; i<values.length; i++) {
1746                 int val = Integer.parseInt(values[i].toString());
1747                 if (val >= limit) {
1748                     if (i != 0) {
1749                         mHaveDebugSettings = true;
1750                     }
1751                     mAppProcessLimit.setValueIndex(i);
1752                     mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]);
1753                     return;
1754                 }
1755             }
1756             mAppProcessLimit.setValueIndex(0);
1757             mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]);
1758         } catch (RemoteException e) {
1759         }
1760     }
1761
1762     private void writeAppProcessLimitOptions(Object newValue) {
1763         try {
1764             int limit = newValue != null ? Integer.parseInt(newValue.toString()) : -1;
1765             ActivityManagerNative.getDefault().setProcessLimit(limit);
1766             updateAppProcessLimitOptions();
1767         } catch (RemoteException e) {
1768         }
1769     }
1770
1771     private void writeShowAllANRsOptions() {
1772         Settings.Secure.putInt(getActivity().getContentResolver(),
1773                 Settings.Secure.ANR_SHOW_BACKGROUND,
1774                 mShowAllANRs.isChecked() ? 1 : 0);
1775     }
1776
1777     private void updateShowAllANRsOptions() {
1778         updateSwitchPreference(mShowAllANRs, Settings.Secure.getInt(
1779                 getActivity().getContentResolver(), Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0);
1780     }
1781
1782     private void confirmEnableOemUnlock() {
1783         DialogInterface.OnClickListener onEnableOemListener = new DialogInterface.OnClickListener() {
1784             @Override
1785             public void onClick(DialogInterface dialog, int which) {
1786                 if (which == DialogInterface.BUTTON_POSITIVE) {
1787                     Utils.setOemUnlockEnabled(getActivity(), true);
1788                 }
1789                 updateAllOptions();
1790             }
1791         };
1792
1793         new AlertDialog.Builder(getActivity())
1794                 .setTitle(R.string.confirm_enable_oem_unlock_title)
1795                 .setMessage(R.string.confirm_enable_oem_unlock_text)
1796                 .setPositiveButton(R.string.enable_text, onEnableOemListener)
1797                 .setNegativeButton(android.R.string.cancel, onEnableOemListener)
1798                 .setCancelable(false)
1799                 .create()
1800                 .show();
1801     }
1802
1803     private void confirmEnableMultiWindowMode() {
1804         DialogInterface.OnClickListener onConfirmListener = new DialogInterface.OnClickListener() {
1805             @Override
1806             public void onClick(DialogInterface dialog, int which) {
1807                 setEnableMultiWindow((which == DialogInterface.BUTTON_POSITIVE) ? true : false);
1808                 updateAllOptions();
1809             }
1810         };
1811
1812         new AlertDialog.Builder(getActivity())
1813                 .setTitle(R.string.confirm_enable_multi_window_title)
1814                 .setMessage(R.string.confirm_enable_multi_window_text)
1815                 .setPositiveButton(R.string.enable_text, onConfirmListener)
1816                 .setNegativeButton(android.R.string.cancel, onConfirmListener)
1817                 .setCancelable(false)
1818                 .create()
1819                 .show();
1820     }
1821
1822     private void updateUpdateRecoveryOptions() {
1823         updateSwitchPreference(mUpdateRecovery, SystemProperties.getBoolean(
1824                 UPDATE_RECOVERY_PROPERTY, false));
1825     }
1826
1827     private void writeUpdateRecoveryOptions() {
1828         SystemProperties.set(UPDATE_RECOVERY_PROPERTY,
1829                 mUpdateRecovery.isChecked() ? "true" : "false");
1830         pokeSystemProperties();
1831     }
1832
1833     private static void resetUpdateRecoveryOptions() {
1834         // User builds should update recovery by default
1835         if ("user".equals(Build.TYPE)) {
1836             SystemProperties.set(UPDATE_RECOVERY_PROPERTY, "true");
1837         }
1838     }
1839
1840     public static void initializeUpdateRecoveryOption() {
1841         if (TextUtils.isEmpty(SystemProperties.get(UPDATE_RECOVERY_PROPERTY))) {
1842             resetUpdateRecoveryOptions();
1843         }
1844     }
1845
1846     @Override
1847     public void onSwitchChanged(Switch switchView, boolean isChecked) {
1848         if (switchView != mSwitchBar.getSwitch()) {
1849             return;
1850         }
1851         if (isChecked != mLastEnabledState) {
1852             if (isChecked) {
1853                 mDialogClicked = false;
1854                 if (mEnableDialog != null) {
1855                     dismissDialogs();
1856                 }
1857                 mEnableDialog = new AlertDialog.Builder(getActivity()).setMessage(
1858                         getActivity().getResources().getString(
1859                                 R.string.dev_settings_warning_message))
1860                         .setTitle(R.string.dev_settings_warning_title)
1861                         .setPositiveButton(android.R.string.yes, this)
1862                         .setNegativeButton(android.R.string.no, this)
1863                         .show();
1864                 mEnableDialog.setOnDismissListener(this);
1865             } else {
1866                 resetDangerousOptions();
1867                 Settings.Global.putInt(getActivity().getContentResolver(),
1868                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);
1869                 mLastEnabledState = isChecked;
1870                 setPrefsEnabledState(mLastEnabledState);
1871
1872                 // Hide development settings from the Settings menu (Android 4.2 behaviour)
1873                 getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit()
1874                     .putBoolean(PREF_SHOW, false)
1875                     .apply();
1876             }
1877         }
1878     }
1879
1880     @Override
1881     public void onActivityResult(int requestCode, int resultCode, Intent data) {
1882         if (requestCode == RESULT_DEBUG_APP) {
1883             if (resultCode == Activity.RESULT_OK) {
1884                 mDebugApp = data.getAction();
1885                 writeDebuggerOptions();
1886                 updateDebuggerOptions();
1887             }
1888         } else if (requestCode == RESULT_MOCK_LOCATION_APP) {
1889             if (resultCode == Activity.RESULT_OK) {
1890                 mMockLocationApp = data.getAction();
1891                 writeMockLocation();
1892                 updateMockLocation();
1893             }
1894         } else if (requestCode == REQUEST_CODE_ENABLE_OEM_UNLOCK) {
1895             if (resultCode == Activity.RESULT_OK) {
1896                 if (mEnableOemUnlock.isChecked()) {
1897                     confirmEnableOemUnlock();
1898                 } else {
1899                     Utils.setOemUnlockEnabled(getActivity(), false);
1900                 }
1901             }
1902         } else {
1903             super.onActivityResult(requestCode, resultCode, data);
1904         }
1905     }
1906
1907     @Override
1908     public boolean onPreferenceClick(Preference preference) {
1909         if (preference == mWindowAnimationScale ||
1910                 preference == mTransitionAnimationScale ||
1911                 preference == mAnimatorDurationScale) {
1912             ((AnimationScalePreference) preference).click();
1913         }
1914         return false;
1915     }
1916
1917     @Override
1918     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
1919         if (Utils.isMonkeyRunning()) {
1920             return false;
1921         }
1922
1923         if (preference == mEnableAdb) {
1924             if (mEnableAdb.isChecked()) {
1925                 mDialogClicked = false;
1926                 if (mAdbDialog != null) {
1927                     dismissDialogs();
1928                 }
1929                 mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage(
1930                         getActivity().getResources().getString(R.string.adb_warning_message))
1931                         .setTitle(R.string.adb_warning_title)
1932                         .setPositiveButton(android.R.string.yes, this)
1933                         .setNegativeButton(android.R.string.no, this)
1934                         .show();
1935                 mAdbDialog.setOnDismissListener(this);
1936             } else {
1937                 Settings.Global.putInt(getActivity().getContentResolver(),
1938                         Settings.Global.ADB_ENABLED, 0);
1939                 mVerifyAppsOverUsb.setEnabled(false);
1940                 mVerifyAppsOverUsb.setChecked(false);
1941                 updateBugreportOptions();
1942             }
1943         } else if (preference == mAdbNotify) {
1944             CMSettings.Secure.putInt(getActivity().getContentResolver(),
1945                     CMSettings.Secure.ADB_NOTIFY,
1946                     mAdbNotify.isChecked() ? 1 : 0);
1947         } else if (preference == mAdbOverNetwork) {
1948             if (mAdbOverNetwork.isChecked()) {
1949                 if (mAdbTcpDialog != null) {
1950                     dismissDialogs();
1951                 }
1952                 mAdbTcpDialog = new AlertDialog.Builder(getActivity()).setMessage(
1953                         getResources().getString(R.string.adb_over_network_warning))
1954                         .setTitle(R.string.adb_over_network)
1955                         .setPositiveButton(android.R.string.yes, this)
1956                         .setNegativeButton(android.R.string.no, this)
1957                         .show();
1958                 mAdbTcpDialog.setOnDismissListener(this);
1959             } else {
1960                 CMSettings.Secure.putInt(getActivity().getContentResolver(),
1961                         CMSettings.Secure.ADB_PORT, -1);
1962                 updateAdbOverNetwork();
1963             }
1964         } else if (preference == mClearAdbKeys) {
1965             if (mAdbKeysDialog != null) dismissDialogs();
1966             mAdbKeysDialog = new AlertDialog.Builder(getActivity())
1967                         .setMessage(R.string.adb_keys_warning_message)
1968                         .setPositiveButton(android.R.string.ok, this)
1969                         .setNegativeButton(android.R.string.cancel, null)
1970                         .show();
1971         } else if (preference == mEnableTerminal) {
1972             final PackageManager pm = getActivity().getPackageManager();
1973             pm.setApplicationEnabledSetting(TERMINAL_APP_PACKAGE,
1974                     mEnableTerminal.isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1975                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
1976         } else if (preference == mBugreportInPower) {
1977             Settings.Secure.putInt(getActivity().getContentResolver(),
1978                     Settings.Secure.BUGREPORT_IN_POWER_MENU,
1979                     mBugreportInPower.isChecked() ? 1 : 0);
1980         } else if (preference == mBtHciSnoopLog) {
1981             writeBtHciSnoopLogOptions();
1982         } else if (preference == mEnableOemUnlock) {
1983             if (!showKeyguardConfirmation(getResources(), REQUEST_CODE_ENABLE_OEM_UNLOCK)) {
1984                 if (mEnableOemUnlock.isChecked()) {
1985                     confirmEnableOemUnlock();
1986                 } else {
1987                     Utils.setOemUnlockEnabled(getActivity(), false);
1988                 }
1989             }
1990         } else if (preference == mMockLocationAppPref) {
1991             Intent intent = new Intent(getActivity(), AppPicker.class);
1992             intent.putExtra(AppPicker.EXTRA_REQUESTIING_PERMISSION,
1993                     Manifest.permission.ACCESS_MOCK_LOCATION);
1994             startActivityForResult(intent, RESULT_MOCK_LOCATION_APP);
1995         } else if (preference == mDebugViewAttributes) {
1996             Settings.Global.putInt(getActivity().getContentResolver(),
1997                     Settings.Global.DEBUG_VIEW_ATTRIBUTES,
1998                     mDebugViewAttributes.isChecked() ? 1 : 0);
1999         } else if (preference == mDebugAppPref) {
2000             Intent intent = new Intent(getActivity(), AppPicker.class);
2001             intent.putExtra(AppPicker.EXTRA_DEBUGGABLE, true);
2002             startActivityForResult(intent, RESULT_DEBUG_APP);
2003         } else if (preference == mWaitForDebugger) {
2004             writeDebuggerOptions();
2005         } else if (preference == mVerifyAppsOverUsb) {
2006             writeVerifyAppsOverUsbOptions();
2007         } else if (preference == mStrictMode) {
2008             writeStrictModeVisualOptions();
2009         } else if (preference == mPointerLocation) {
2010             writePointerLocationOptions();
2011         } else if (preference == mShowTouches) {
2012             writeShowTouchesOptions();
2013         } else if (preference == mShowScreenUpdates) {
2014             writeShowUpdatesOption();
2015         } else if (preference == mDisableOverlays) {
2016             writeDisableOverlaysOption();
2017         } else if (preference == mEnableMultiWindow) {
2018             if (mEnableMultiWindow.isChecked()) {
2019                 confirmEnableMultiWindowMode();
2020             } else {
2021                 setEnableMultiWindow(false);
2022             }
2023         } else if (preference == mShowCpuUsage) {
2024             writeCpuUsageOptions();
2025         } else if (preference == mImmediatelyDestroyActivities) {
2026             writeImmediatelyDestroyActivitiesOptions();
2027         } else if (preference == mShowAllANRs) {
2028             writeShowAllANRsOptions();
2029         } else if (preference == mForceHardwareUi) {
2030             writeHardwareUiOptions();
2031         } else if (preference == mForceMsaa) {
2032             writeMsaaOptions();
2033         } else if (preference == mShowHwScreenUpdates) {
2034             writeShowHwScreenUpdatesOptions();
2035         } else if (preference == mShowHwLayersUpdates) {
2036             writeShowHwLayersUpdatesOptions();
2037         } else if (preference == mDebugLayout) {
2038             writeDebugLayoutOptions();
2039         } else if (preference == mForceRtlLayout) {
2040             writeForceRtlOptions();
2041         } else if (preference == mWifiDisplayCertification) {
2042             writeWifiDisplayCertificationOptions();
2043         } else if (preference == mWifiVerboseLogging) {
2044             writeWifiVerboseLoggingOptions();
2045         } else if (preference == mWifiAggressiveHandover) {
2046             writeWifiAggressiveHandoverOptions();
2047         } else if (preference == mWifiAllowScansWithTraffic) {
2048             writeWifiAllowScansWithTrafficOptions();
2049         } else if (preference == mLegacyDhcpClient) {
2050             writeLegacyDhcpClientOptions();
2051         } else if (preference == mMobileDataAlwaysOn) {
2052             writeMobileDataAlwaysOnOptions();
2053         } else if (preference == mColorTemperaturePreference) {
2054             writeColorTemperature();
2055         } else if (preference == mUSBAudio) {
2056             writeUSBAudioOptions();
2057         } else if (preference == mAdvancedReboot) {
2058             writeAdvancedRebootOptions();
2059         } else if (INACTIVE_APPS_KEY.equals(preference.getKey())) {
2060             startInactiveAppsFragment();
2061         } else if (preference == mDevelopmentShortcut) {
2062             writeDevelopmentShortcutOptions();
2063         } else if (preference == mKillAppLongpressBack) {
2064             writeKillAppLongpressBackOptions();
2065         } else if (preference == mUpdateRecovery) {
2066             if (mSwitchBar.isChecked()) {
2067                 if (mUpdateRecoveryDialog != null) {
2068                     dismissDialogs();
2069                 }
2070                 if (mUpdateRecovery.isChecked()) {
2071                     mUpdateRecoveryDialog = new AlertDialog.Builder(getActivity()).setMessage(
2072                             getResources().getString(R.string.update_recovery_on_warning))
2073                             .setTitle(R.string.update_recovery_title)
2074                             .setPositiveButton(android.R.string.yes, this)
2075                             .setNegativeButton(android.R.string.no, this)
2076                             .show();
2077                 } else {
2078                     mUpdateRecoveryDialog = new AlertDialog.Builder(getActivity()).setMessage(
2079                             getResources().getString(R.string.update_recovery_off_warning))
2080                             .setTitle(R.string.update_recovery_title)
2081                             .setPositiveButton(android.R.string.yes, this)
2082                             .setNegativeButton(android.R.string.no, this)
2083                             .show();
2084                 }
2085                 mUpdateRecoveryDialog.setOnDismissListener(this);
2086             }
2087         } else {
2088             return super.onPreferenceTreeClick(preferenceScreen, preference);
2089         }
2090
2091         return false;
2092     }
2093
2094     private void startInactiveAppsFragment() {
2095         ((SettingsActivity) getActivity()).startPreferencePanel(
2096                 InactiveApps.class.getName(),
2097                 null, R.string.inactive_apps_title, null, null, 0);
2098     }
2099
2100     private boolean showKeyguardConfirmation(Resources resources, int requestCode) {
2101         return new ChooseLockSettingsHelper(getActivity(), this).launchConfirmationActivity(
2102                 requestCode, resources.getString(R.string.oem_unlock_enable));
2103     }
2104
2105     @Override
2106     public boolean onPreferenceChange(Preference preference, Object newValue) {
2107         if (HDCP_CHECKING_KEY.equals(preference.getKey())) {
2108             SystemProperties.set(HDCP_CHECKING_PROPERTY, newValue.toString());
2109             updateHdcpValues();
2110             pokeSystemProperties();
2111             return true;
2112         } else if (preference == mLogdSize) {
2113             writeLogdSizeOption(newValue);
2114             return true;
2115         } else if (preference == mUsbConfiguration) {
2116             writeUsbConfigurationOption(newValue);
2117             return true;
2118         } else if (preference == mWindowAnimationScale) {
2119             writeAnimationScaleOption(0, mWindowAnimationScale, newValue);
2120             return true;
2121         } else if (preference == mTransitionAnimationScale) {
2122             writeAnimationScaleOption(1, mTransitionAnimationScale, newValue);
2123             return true;
2124         } else if (preference == mAnimatorDurationScale) {
2125             writeAnimationScaleOption(2, mAnimatorDurationScale, newValue);
2126             return true;
2127         } else if (preference == mOverlayDisplayDevices) {
2128             writeOverlayDisplayDevicesOptions(newValue);
2129             return true;
2130         } else if (preference == mOpenGLTraces) {
2131             writeOpenGLTracesOptions(newValue);
2132             return true;
2133         } else if (preference == mTrackFrameTime) {
2134             writeTrackFrameTimeOptions(newValue);
2135             return true;
2136         } else if (preference == mDebugHwOverdraw) {
2137             writeDebugHwOverdrawOptions(newValue);
2138             return true;
2139         } else if (preference == mShowNonRectClip) {
2140             writeShowNonRectClipOptions(newValue);
2141             return true;
2142         } else if (preference == mAppProcessLimit) {
2143             writeAppProcessLimitOptions(newValue);
2144             return true;
2145         } else if (preference == mSimulateColorSpace) {
2146             writeSimulateColorSpace(newValue);
2147             return true;
2148         } else if (preference == mRootAccess) {
2149             if ("0".equals(SystemProperties.get(ROOT_ACCESS_PROPERTY, "0"))
2150                     && !"0".equals(newValue)) {
2151                 mSelectedRootValue = newValue;
2152                 mDialogClicked = false;
2153                 if (mRootDialog != null) {
2154                     dismissDialogs();
2155                 }
2156                 mRootDialog = new AlertDialog.Builder(getActivity())
2157                         .setMessage(getResources().getString(R.string.root_access_warning_message))
2158                         .setTitle(R.string.root_access_warning_title)
2159                         .setPositiveButton(android.R.string.yes, this)
2160                         .setNegativeButton(android.R.string.no, this).show();
2161                 mRootDialog.setOnDismissListener(this);
2162             } else {
2163                 writeRootAccessOptions(newValue);
2164             }
2165             return true;
2166         } else if (preference == mKeepScreenOn) {
2167             writeStayAwakeOptions(newValue);
2168             return true;
2169         }
2170         return false;
2171     }
2172
2173     private void dismissDialogs() {
2174         if (mAdbDialog != null) {
2175             mAdbDialog.dismiss();
2176             mAdbDialog = null;
2177         }
2178         if (mAdbTcpDialog != null) {
2179             mAdbTcpDialog.dismiss();
2180             mAdbTcpDialog = null;
2181         }
2182         if (mAdbKeysDialog != null) {
2183             mAdbKeysDialog.dismiss();
2184             mAdbKeysDialog = null;
2185         }
2186         if (mEnableDialog != null) {
2187             mEnableDialog.dismiss();
2188             mEnableDialog = null;
2189         }
2190         if (mRootDialog != null) {
2191             mRootDialog.dismiss();
2192             mRootDialog = null;
2193         }
2194         if (mUpdateRecoveryDialog != null) {
2195             mUpdateRecoveryDialog.dismiss();
2196             mUpdateRecoveryDialog = null;
2197         }
2198     }
2199
2200     public void onClick(DialogInterface dialog, int which) {
2201         if (dialog == mAdbDialog) {
2202             if (which == DialogInterface.BUTTON_POSITIVE) {
2203                 mDialogClicked = true;
2204                 Settings.Global.putInt(getActivity().getContentResolver(),
2205                         Settings.Global.ADB_ENABLED, 1);
2206                 mVerifyAppsOverUsb.setEnabled(true);
2207                 updateVerifyAppsOverUsbOptions();
2208                 updateBugreportOptions();
2209             }
2210         } else if (dialog == mAdbTcpDialog) {
2211             if (which == DialogInterface.BUTTON_POSITIVE) {
2212                 CMSettings.Secure.putInt(getActivity().getContentResolver(),
2213                         CMSettings.Secure.ADB_PORT, 5555);
2214             }
2215         } else if (dialog == mAdbKeysDialog) {
2216             if (which == DialogInterface.BUTTON_POSITIVE) {
2217                 try {
2218                     IBinder b = ServiceManager.getService(Context.USB_SERVICE);
2219                     IUsbManager service = IUsbManager.Stub.asInterface(b);
2220                     service.clearUsbDebuggingKeys();
2221                 } catch (RemoteException e) {
2222                     Log.e(TAG, "Unable to clear adb keys", e);
2223                 }
2224             }
2225         } else if (dialog == mEnableDialog) {
2226             if (which == DialogInterface.BUTTON_POSITIVE) {
2227                 mDialogClicked = true;
2228                 Settings.Global.putInt(getActivity().getContentResolver(),
2229                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
2230                 mLastEnabledState = true;
2231                 setPrefsEnabledState(mLastEnabledState);
2232
2233                 // Make sure the development settings is visible in the main Settings menu
2234                 // This is needed since we may have just turned off dev settings and want to
2235                 // turn it on again
2236                 getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit()
2237                     .putBoolean(PREF_SHOW, true)
2238                     .apply();
2239             }
2240         } else if (dialog == mRootDialog) {
2241             if (which == DialogInterface.BUTTON_POSITIVE) {
2242                 writeRootAccessOptions(mSelectedRootValue);
2243             } else {
2244                 // Reset the option
2245                 writeRootAccessOptions("0");
2246             }
2247         } else if (dialog == mUpdateRecoveryDialog) {
2248             if (which == DialogInterface.BUTTON_POSITIVE) {
2249                 writeUpdateRecoveryOptions();
2250             }
2251         }
2252     }
2253
2254     public void onDismiss(DialogInterface dialog) {
2255         // Assuming that onClick gets called first
2256         if (dialog == mAdbDialog) {
2257             if (!mDialogClicked) {
2258                 mEnableAdb.setChecked(false);
2259             }
2260             mAdbDialog = null;
2261         } else if (dialog == mAdbTcpDialog) {
2262             updateAdbOverNetwork();
2263             mAdbTcpDialog = null;
2264         } else if (dialog == mEnableDialog) {
2265             if (!mDialogClicked) {
2266                 mSwitchBar.setChecked(false);
2267             }
2268             mEnableDialog = null;
2269         } else if (dialog == mRootDialog) {
2270             updateRootAccessOptions();
2271             mRootDialog = null;
2272         } else if (dialog == mUpdateRecoveryDialog) {
2273             updateUpdateRecoveryOptions();
2274             mUpdateRecoveryDialog = null;
2275         }
2276     }
2277
2278     @Override
2279     public void onDestroy() {
2280         dismissDialogs();
2281         super.onDestroy();
2282     }
2283
2284     void pokeSystemProperties() {
2285         if (!mDontPokeProperties) {
2286             //noinspection unchecked
2287             (new SystemPropPoker()).execute();
2288         }
2289     }
2290
2291     private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
2292         @Override
2293         public void onReceive(Context context, Intent intent) {
2294             boolean isUnlocked = intent.getBooleanExtra(UsbManager.USB_DATA_UNLOCKED, false);
2295             updateUsbConfigurationValues(isUnlocked);
2296         }
2297     };
2298
2299     static class SystemPropPoker extends AsyncTask<Void, Void, Void> {
2300         @Override
2301         protected Void doInBackground(Void... params) {
2302             String[] services;
2303             try {
2304                 services = ServiceManager.listServices();
2305             } catch (RemoteException e) {
2306                 return null;
2307             }
2308             for (String service : services) {
2309                 IBinder obj = ServiceManager.checkService(service);
2310                 if (obj != null) {
2311                     Parcel data = Parcel.obtain();
2312                     try {
2313                         obj.transact(IBinder.SYSPROPS_TRANSACTION, data, null, 0);
2314                     } catch (RemoteException e) {
2315                     } catch (Exception e) {
2316                         Log.i(TAG, "Someone wrote a bad service '" + service
2317                                 + "' that doesn't like to be poked: " + e);
2318                     }
2319                     data.recycle();
2320                 }
2321             }
2322             return null;
2323         }
2324     }
2325
2326     private static boolean isPackageInstalled(Context context, String packageName) {
2327         try {
2328             return context.getPackageManager().getPackageInfo(packageName, 0) != null;
2329         } catch (NameNotFoundException e) {
2330             return false;
2331         }
2332     }
2333
2334     /**
2335      * For Search.
2336      */
2337     public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
2338             new BaseSearchIndexProvider() {
2339
2340                 private boolean isShowingDeveloperOptions(Context context) {
2341                     return context.getSharedPreferences(DevelopmentSettings.PREF_FILE,
2342                             Context.MODE_PRIVATE).getBoolean(
2343                                     DevelopmentSettings.PREF_SHOW,
2344                                     android.os.Build.TYPE.equals("eng"));
2345                 }
2346
2347                 @Override
2348                 public List<SearchIndexableResource> getXmlResourcesToIndex(
2349                         Context context, boolean enabled) {
2350
2351                     if (!isShowingDeveloperOptions(context)) {
2352                         return null;
2353                     }
2354
2355                     final SearchIndexableResource sir = new SearchIndexableResource(context);
2356                     sir.xmlResId = R.xml.development_prefs;
2357                     return Arrays.asList(sir);
2358                 }
2359
2360                 @Override
2361                 public List<String> getNonIndexableKeys(Context context) {
2362                     if (!isShowingDeveloperOptions(context)) {
2363                         return null;
2364                     }
2365
2366                     final List<String> keys = new ArrayList<String>();
2367                     if (!showEnableOemUnlockPreference()) {
2368                         keys.add(ENABLE_OEM_UNLOCK);
2369                     }
2370                     if (!showEnableMultiWindowPreference()) {
2371                         keys.add(ENABLE_MULTI_WINDOW_KEY);
2372                     }
2373                     return keys;
2374                 }
2375             };
2376 }