OSDN Git Service

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