OSDN Git Service

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