OSDN Git Service

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