OSDN Git Service

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