OSDN Git Service

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