OSDN Git Service

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