OSDN Git Service

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