OSDN Git Service

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