OSDN Git Service

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