OSDN Git Service

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