OSDN Git Service

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