OSDN Git Service

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