OSDN Git Service

Merge "Refactor NetworkScoreAppManager for testing." am: 512368a22e am: 3140bb5ace...
[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.ActivityManager;
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.IShortcutService;
38 import android.content.pm.PackageManager;
39 import android.content.pm.PackageManager.NameNotFoundException;
40 import android.content.pm.ResolveInfo;
41 import android.content.res.Resources;
42 import android.hardware.usb.IUsbManager;
43 import android.hardware.usb.UsbManager;
44 import android.net.wifi.WifiManager;
45 import android.os.AsyncTask;
46 import android.os.BatteryManager;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.IBinder;
50 import android.os.Parcel;
51 import android.os.RemoteException;
52 import android.os.ServiceManager;
53 import android.os.StrictMode;
54 import android.os.SystemProperties;
55 import android.os.UserHandle;
56 import android.os.UserManager;
57 import android.os.storage.IStorageManager;
58 import android.provider.SearchIndexableResource;
59 import android.provider.Settings;
60 import android.service.persistentdata.PersistentDataBlockManager;
61 import android.support.annotation.VisibleForTesting;
62 import android.support.v14.preference.SwitchPreference;
63 import android.support.v7.preference.ListPreference;
64 import android.support.v7.preference.Preference;
65 import android.support.v7.preference.Preference.OnPreferenceChangeListener;
66 import android.support.v7.preference.PreferenceGroup;
67 import android.support.v7.preference.PreferenceScreen;
68 import android.telephony.TelephonyManager;
69 import android.text.TextUtils;
70 import android.util.Log;
71 import android.view.IWindowManager;
72 import android.view.LayoutInflater;
73 import android.view.ThreadedRenderer;
74 import android.view.View;
75 import android.view.ViewGroup;
76 import android.view.accessibility.AccessibilityManager;
77 import android.webkit.IWebViewUpdateService;
78 import android.webkit.WebViewProviderInfo;
79 import android.widget.Switch;
80 import android.widget.Toast;
81
82 import com.android.internal.app.LocalePicker;
83 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
84 import com.android.settings.applications.BackgroundCheckSummary;
85 import com.android.settings.dashboard.DashboardFeatureProvider;
86 import com.android.settings.fuelgauge.InactiveApps;
87 import com.android.settings.overlay.FeatureFactory;
88 import com.android.settings.search.BaseSearchIndexProvider;
89 import com.android.settings.search.Indexable;
90 import com.android.settings.widget.SwitchBar;
91 import com.android.settingslib.RestrictedLockUtils;
92 import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
93 import com.android.settingslib.RestrictedSwitchPreference;
94 import com.android.settingslib.drawer.CategoryKey;
95
96 import java.util.ArrayList;
97 import java.util.Arrays;
98 import java.util.HashSet;
99 import java.util.List;
100
101 /*
102  * Displays preferences for application developers.
103  */
104 public class DevelopmentSettings extends RestrictedSettingsFragment
105         implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener,
106         OnPreferenceChangeListener, SwitchBar.OnSwitchChangeListener, Indexable {
107     private static final String TAG = "DevelopmentSettings";
108
109     /**
110      * Preference file were development settings prefs are stored.
111      */
112     public static final String PREF_FILE = "development";
113
114     /**
115      * Whether to show the development settings to the user.  Default is false.
116      */
117     public static final String PREF_SHOW = "show";
118
119     private static final String ENABLE_ADB = "enable_adb";
120     private static final String CLEAR_ADB_KEYS = "clear_adb_keys";
121     private static final String ENABLE_TERMINAL = "enable_terminal";
122     private static final String KEEP_SCREEN_ON = "keep_screen_on";
123     private static final String BT_HCI_SNOOP_LOG = "bt_hci_snoop_log";
124     private static final String WEBVIEW_PROVIDER_KEY = "select_webview_provider";
125     private static final String WEBVIEW_MULTIPROCESS_KEY = "enable_webview_multiprocess";
126     private static final String ENABLE_OEM_UNLOCK = "oem_unlock_enable";
127     private static final String HDCP_CHECKING_KEY = "hdcp_checking";
128     private static final String HDCP_CHECKING_PROPERTY = "persist.sys.hdcp_checking";
129     private static final String LOCAL_BACKUP_PASSWORD = "local_backup_password";
130     private static final String HARDWARE_UI_PROPERTY = "persist.sys.ui.hw";
131     private static final String MSAA_PROPERTY = "debug.egl.force_msaa";
132     private static final String BUGREPORT = "bugreport";
133     private static final String BUGREPORT_IN_POWER_KEY = "bugreport_in_power";
134     private static final String OPENGL_TRACES_PROPERTY = "debug.egl.trace";
135     private static final String TUNER_UI_KEY = "tuner_ui";
136     private static final String COLOR_TEMPERATURE_PROPERTY = "persist.sys.debug.color_temp";
137
138     private static final String DEBUG_APP_KEY = "debug_app";
139     private static final String WAIT_FOR_DEBUGGER_KEY = "wait_for_debugger";
140     private static final String MOCK_LOCATION_APP_KEY = "mock_location_app";
141     private static final String VERIFY_APPS_OVER_USB_KEY = "verify_apps_over_usb";
142     private static final String DEBUG_VIEW_ATTRIBUTES = "debug_view_attributes";
143     private static final String FORCE_ALLOW_ON_EXTERNAL_KEY = "force_allow_on_external";
144     private static final String STRICT_MODE_KEY = "strict_mode";
145     private static final String POINTER_LOCATION_KEY = "pointer_location";
146     private static final String SHOW_TOUCHES_KEY = "show_touches";
147     private static final String SHOW_SCREEN_UPDATES_KEY = "show_screen_updates";
148     private static final String DISABLE_OVERLAYS_KEY = "disable_overlays";
149     private static final String SIMULATE_COLOR_SPACE = "simulate_color_space";
150     private static final String USB_AUDIO_KEY = "usb_audio";
151     private static final String FORCE_HARDWARE_UI_KEY = "force_hw_ui";
152     private static final String FORCE_MSAA_KEY = "force_msaa";
153     private static final String TRACK_FRAME_TIME_KEY = "track_frame_time";
154     private static final String SHOW_NON_RECTANGULAR_CLIP_KEY = "show_non_rect_clip";
155     private static final String SHOW_HW_SCREEN_UPDATES_KEY = "show_hw_screen_udpates";
156     private static final String SHOW_HW_LAYERS_UPDATES_KEY = "show_hw_layers_udpates";
157     private static final String DEBUG_HW_OVERDRAW_KEY = "debug_hw_overdraw";
158     private static final String DEBUG_LAYOUT_KEY = "debug_layout";
159     private static final String FORCE_RTL_LAYOUT_KEY = "force_rtl_layout_all_locales";
160     private static final String WINDOW_ANIMATION_SCALE_KEY = "window_animation_scale";
161     private static final String TRANSITION_ANIMATION_SCALE_KEY = "transition_animation_scale";
162     private static final String ANIMATOR_DURATION_SCALE_KEY = "animator_duration_scale";
163     private static final String OVERLAY_DISPLAY_DEVICES_KEY = "overlay_display_devices";
164     private static final String DEBUG_DEBUGGING_CATEGORY_KEY = "debug_debugging_category";
165     private static final String SELECT_LOGD_SIZE_KEY = "select_logd_size";
166     private static final String SELECT_LOGD_SIZE_PROPERTY = "persist.logd.size";
167     private static final String SELECT_LOGD_TAG_PROPERTY = "persist.log.tag";
168     // Tricky, isLoggable only checks for first character, assumes silence
169     private static final String SELECT_LOGD_TAG_SILENCE = "Settings";
170     private static final String SELECT_LOGD_SNET_TAG_PROPERTY = "persist.log.tag.snet_event_log";
171     private static final String SELECT_LOGD_RUNTIME_SNET_TAG_PROPERTY = "log.tag.snet_event_log";
172     private static final String SELECT_LOGD_DEFAULT_SIZE_PROPERTY = "ro.logd.size";
173     private static final String SELECT_LOGD_DEFAULT_SIZE_VALUE = "262144";
174     private static final String SELECT_LOGD_SVELTE_DEFAULT_SIZE_VALUE = "65536";
175     // 32768 is merely a menu marker, 64K is our lowest log buffer size we replace it with.
176     private static final String SELECT_LOGD_MINIMUM_SIZE_VALUE = "65536";
177     private static final String SELECT_LOGD_OFF_SIZE_MARKER_VALUE = "32768";
178     private static final String SELECT_LOGPERSIST_KEY = "select_logpersist";
179     private static final String SELECT_LOGPERSIST_PROPERTY = "persist.logd.logpersistd";
180     private static final String ACTUAL_LOGPERSIST_PROPERTY = "logd.logpersistd";
181     private static final String SELECT_LOGPERSIST_PROPERTY_SERVICE = "logcatd";
182     private static final String SELECT_LOGPERSIST_PROPERTY_CLEAR = "clear";
183     private static final String SELECT_LOGPERSIST_PROPERTY_STOP = "stop";
184     private static final String SELECT_LOGPERSIST_PROPERTY_BUFFER =
185             "persist.logd.logpersistd.buffer";
186     private static final String ACTUAL_LOGPERSIST_PROPERTY_BUFFER = "logd.logpersistd.buffer";
187     private static final String ACTUAL_LOGPERSIST_PROPERTY_ENABLE = "logd.logpersistd.enable";
188
189     private static final String WIFI_DISPLAY_CERTIFICATION_KEY = "wifi_display_certification";
190     private static final String WIFI_VERBOSE_LOGGING_KEY = "wifi_verbose_logging";
191     private static final String WIFI_AGGRESSIVE_HANDOVER_KEY = "wifi_aggressive_handover";
192     private static final String WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY = "wifi_allow_scan_with_traffic";
193     private static final String USB_CONFIGURATION_KEY = "select_usb_configuration";
194     private static final String MOBILE_DATA_ALWAYS_ON = "mobile_data_always_on";
195     private static final String KEY_COLOR_MODE = "color_mode";
196     private static final String FORCE_RESIZABLE_KEY = "force_resizable_activities";
197     private static final String COLOR_TEMPERATURE_KEY = "color_temperature";
198
199     private static final String BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_KEY =
200             "bluetooth_disable_absolute_volume";
201     private static final String BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_PROPERTY =
202             "persist.bluetooth.disableabsvol";
203
204     private static final String INACTIVE_APPS_KEY = "inactive_apps";
205
206     private static final String IMMEDIATELY_DESTROY_ACTIVITIES_KEY
207             = "immediately_destroy_activities";
208     private static final String APP_PROCESS_LIMIT_KEY = "app_process_limit";
209
210     private static final String BACKGROUND_CHECK_KEY = "background_check";
211
212     private static final String SHOW_ALL_ANRS_KEY = "show_all_anrs";
213
214     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
215
216     private static final String TERMINAL_APP_PACKAGE = "com.android.terminal";
217
218     private static final String KEY_CONVERT_FBE = "convert_to_file_encryption";
219
220     private static final String OTA_DISABLE_AUTOMATIC_UPDATE_KEY = "ota_disable_automatic_update";
221
222     private static final int RESULT_DEBUG_APP = 1000;
223     private static final int RESULT_MOCK_LOCATION_APP = 1001;
224
225     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
226     private static final String FLASH_LOCKED_PROP = "ro.boot.flash.locked";
227
228     private static final String SHORTCUT_MANAGER_RESET_KEY = "reset_shortcut_manager_throttling";
229
230     private static final int REQUEST_CODE_ENABLE_OEM_UNLOCK = 0;
231
232     private static final int[] MOCK_LOCATION_APP_OPS = new int[]{AppOpsManager.OP_MOCK_LOCATION};
233
234     private IWindowManager mWindowManager;
235     private IBackupManager mBackupManager;
236     private IWebViewUpdateService mWebViewUpdateService;
237     private DevicePolicyManager mDpm;
238     private UserManager mUm;
239     private WifiManager mWifiManager;
240     private PersistentDataBlockManager mOemUnlockManager;
241     private TelephonyManager mTelephonyManager;
242
243     private SwitchBar mSwitchBar;
244     private boolean mLastEnabledState;
245     private boolean mHaveDebugSettings;
246     private boolean mDontPokeProperties;
247
248     private SwitchPreference mEnableAdb;
249     private Preference mClearAdbKeys;
250     private SwitchPreference mEnableTerminal;
251     private Preference mBugreport;
252     private SwitchPreference mBugreportInPower;
253     private RestrictedSwitchPreference mKeepScreenOn;
254     private SwitchPreference mBtHciSnoopLog;
255     private RestrictedSwitchPreference mEnableOemUnlock;
256     private SwitchPreference mDebugViewAttributes;
257     private SwitchPreference mForceAllowOnExternal;
258
259     private PreferenceScreen mPassword;
260     private String mDebugApp;
261     private Preference mDebugAppPref;
262
263     private String mMockLocationApp;
264     private Preference mMockLocationAppPref;
265
266     private SwitchPreference mWaitForDebugger;
267     private SwitchPreference mVerifyAppsOverUsb;
268     private SwitchPreference mWifiDisplayCertification;
269     private SwitchPreference mWifiVerboseLogging;
270     private SwitchPreference mWifiAggressiveHandover;
271     private SwitchPreference mMobileDataAlwaysOn;
272     private SwitchPreference mBluetoothDisableAbsVolume;
273     private SwitchPreference mOtaDisableAutomaticUpdate;
274
275     private SwitchPreference mWifiAllowScansWithTraffic;
276     private SwitchPreference mStrictMode;
277     private SwitchPreference mPointerLocation;
278     private SwitchPreference mShowTouches;
279     private SwitchPreference mShowScreenUpdates;
280     private SwitchPreference mDisableOverlays;
281     private SwitchPreference mForceHardwareUi;
282     private SwitchPreference mForceMsaa;
283     private SwitchPreference mShowHwScreenUpdates;
284     private SwitchPreference mShowHwLayersUpdates;
285     private SwitchPreference mDebugLayout;
286     private SwitchPreference mForceRtlLayout;
287     private ListPreference mDebugHwOverdraw;
288     private ListPreference mLogdSize;
289     private ListPreference mLogpersist;
290     private ListPreference mUsbConfiguration;
291     private ListPreference mTrackFrameTime;
292     private ListPreference mShowNonRectClip;
293     private ListPreference mWindowAnimationScale;
294     private ListPreference mTransitionAnimationScale;
295     private ListPreference mAnimatorDurationScale;
296     private ListPreference mOverlayDisplayDevices;
297
298     private SwitchPreference mWebViewMultiprocess;
299     private ListPreference mWebViewProvider;
300
301     private ListPreference mSimulateColorSpace;
302
303     private SwitchPreference mUSBAudio;
304     private SwitchPreference mImmediatelyDestroyActivities;
305
306     private ListPreference mAppProcessLimit;
307
308     private SwitchPreference mShowAllANRs;
309
310     private ColorModePreference mColorModePreference;
311
312     private SwitchPreference mForceResizable;
313
314     private SwitchPreference mColorTemperaturePreference;
315
316     private final ArrayList<Preference> mAllPrefs = new ArrayList<Preference>();
317
318     private final ArrayList<SwitchPreference> mResetSwitchPrefs
319             = new ArrayList<SwitchPreference>();
320
321     private final HashSet<Preference> mDisabledPrefs = new HashSet<Preference>();
322     // To track whether a confirmation dialog was clicked.
323     private boolean mDialogClicked;
324     private Dialog mEnableDialog;
325     private Dialog mAdbDialog;
326
327     private Dialog mAdbKeysDialog;
328     private boolean mUnavailable;
329
330     private boolean mLogpersistCleared;
331     private Dialog mLogpersistClearDialog;
332     private DashboardFeatureProvider mDashboardFeatureProvider;
333
334     public DevelopmentSettings() {
335         super(UserManager.DISALLOW_DEBUGGING_FEATURES);
336     }
337
338     @Override
339     public int getMetricsCategory() {
340         return MetricsEvent.DEVELOPMENT;
341     }
342
343     @Override
344     public void onAttach(Context context) {
345         super.onAttach(context);
346         mDashboardFeatureProvider = FeatureFactory.getFactory(context)
347                 .getDashboardFeatureProvider(context);
348     }
349
350     @Override
351     public void onCreate(Bundle icicle) {
352         super.onCreate(icicle);
353
354         mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
355         mBackupManager = IBackupManager.Stub.asInterface(
356                 ServiceManager.getService(Context.BACKUP_SERVICE));
357         mWebViewUpdateService =
358                 IWebViewUpdateService.Stub.asInterface(ServiceManager.getService("webviewupdate"));
359         mOemUnlockManager = (PersistentDataBlockManager) getActivity()
360                 .getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
361         mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
362
363         mDpm = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
364         mUm = (UserManager) getSystemService(Context.USER_SERVICE);
365
366         mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
367
368         setIfOnlyAvailableForAdmins(true);
369         if (isUiRestricted() || !Utils.isDeviceProvisioned(getActivity())) {
370             // Block access to developer options if the user is not the owner, if user policy
371             // restricts it, or if the device has not been provisioned
372             mUnavailable = true;
373             setPreferenceScreen(new PreferenceScreen(getPrefContext(), null));
374             return;
375         }
376
377         addPreferencesFromResource(R.xml.development_prefs);
378
379         final PreferenceGroup debugDebuggingCategory = (PreferenceGroup)
380                 findPreference(DEBUG_DEBUGGING_CATEGORY_KEY);
381         mEnableAdb = findAndInitSwitchPref(ENABLE_ADB);
382         mClearAdbKeys = findPreference(CLEAR_ADB_KEYS);
383         if (!SystemProperties.getBoolean("ro.adb.secure", false)) {
384             if (debugDebuggingCategory != null) {
385                 debugDebuggingCategory.removePreference(mClearAdbKeys);
386             }
387         }
388         mAllPrefs.add(mClearAdbKeys);
389         mEnableTerminal = findAndInitSwitchPref(ENABLE_TERMINAL);
390         if (!isPackageInstalled(getActivity(), TERMINAL_APP_PACKAGE)) {
391             debugDebuggingCategory.removePreference(mEnableTerminal);
392             mEnableTerminal = null;
393         }
394
395         mBugreport = findPreference(BUGREPORT);
396         mBugreportInPower = findAndInitSwitchPref(BUGREPORT_IN_POWER_KEY);
397         mKeepScreenOn = (RestrictedSwitchPreference) findAndInitSwitchPref(KEEP_SCREEN_ON);
398         mBtHciSnoopLog = findAndInitSwitchPref(BT_HCI_SNOOP_LOG);
399         mEnableOemUnlock = (RestrictedSwitchPreference) findAndInitSwitchPref(ENABLE_OEM_UNLOCK);
400         if (!showEnableOemUnlockPreference()) {
401             removePreference(mEnableOemUnlock);
402             mEnableOemUnlock = null;
403         }
404
405         mDebugViewAttributes = findAndInitSwitchPref(DEBUG_VIEW_ATTRIBUTES);
406         mForceAllowOnExternal = findAndInitSwitchPref(FORCE_ALLOW_ON_EXTERNAL_KEY);
407         mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD);
408         mAllPrefs.add(mPassword);
409
410         if (!mUm.isAdminUser()) {
411             disableForUser(mEnableAdb);
412             disableForUser(mClearAdbKeys);
413             disableForUser(mEnableTerminal);
414             disableForUser(mPassword);
415         }
416
417         mDebugAppPref = findPreference(DEBUG_APP_KEY);
418         mAllPrefs.add(mDebugAppPref);
419         mWaitForDebugger = findAndInitSwitchPref(WAIT_FOR_DEBUGGER_KEY);
420
421         mMockLocationAppPref = findPreference(MOCK_LOCATION_APP_KEY);
422         mAllPrefs.add(mMockLocationAppPref);
423
424         mVerifyAppsOverUsb = findAndInitSwitchPref(VERIFY_APPS_OVER_USB_KEY);
425         if (!showVerifierSetting()) {
426             if (debugDebuggingCategory != null) {
427                 debugDebuggingCategory.removePreference(mVerifyAppsOverUsb);
428             } else {
429                 mVerifyAppsOverUsb.setEnabled(false);
430             }
431         }
432         mStrictMode = findAndInitSwitchPref(STRICT_MODE_KEY);
433         mPointerLocation = findAndInitSwitchPref(POINTER_LOCATION_KEY);
434         mShowTouches = findAndInitSwitchPref(SHOW_TOUCHES_KEY);
435         mShowScreenUpdates = findAndInitSwitchPref(SHOW_SCREEN_UPDATES_KEY);
436         mDisableOverlays = findAndInitSwitchPref(DISABLE_OVERLAYS_KEY);
437         mForceHardwareUi = findAndInitSwitchPref(FORCE_HARDWARE_UI_KEY);
438         mForceMsaa = findAndInitSwitchPref(FORCE_MSAA_KEY);
439         mTrackFrameTime = addListPreference(TRACK_FRAME_TIME_KEY);
440         mShowNonRectClip = addListPreference(SHOW_NON_RECTANGULAR_CLIP_KEY);
441         mShowHwScreenUpdates = findAndInitSwitchPref(SHOW_HW_SCREEN_UPDATES_KEY);
442         mShowHwLayersUpdates = findAndInitSwitchPref(SHOW_HW_LAYERS_UPDATES_KEY);
443         mDebugLayout = findAndInitSwitchPref(DEBUG_LAYOUT_KEY);
444         mForceRtlLayout = findAndInitSwitchPref(FORCE_RTL_LAYOUT_KEY);
445         mDebugHwOverdraw = addListPreference(DEBUG_HW_OVERDRAW_KEY);
446         mWifiDisplayCertification = findAndInitSwitchPref(WIFI_DISPLAY_CERTIFICATION_KEY);
447         mWifiVerboseLogging = findAndInitSwitchPref(WIFI_VERBOSE_LOGGING_KEY);
448         mWifiAggressiveHandover = findAndInitSwitchPref(WIFI_AGGRESSIVE_HANDOVER_KEY);
449         mWifiAllowScansWithTraffic = findAndInitSwitchPref(WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY);
450         mMobileDataAlwaysOn = findAndInitSwitchPref(MOBILE_DATA_ALWAYS_ON);
451         mLogdSize = addListPreference(SELECT_LOGD_SIZE_KEY);
452         if ("1".equals(SystemProperties.get("ro.debuggable", "0"))) {
453             mLogpersist = addListPreference(SELECT_LOGPERSIST_KEY);
454         } else {
455             mLogpersist = (ListPreference) findPreference(SELECT_LOGPERSIST_KEY);
456             if (mLogpersist != null) {
457                 mLogpersist.setEnabled(false);
458                 if (debugDebuggingCategory != null) {
459                     debugDebuggingCategory.removePreference(mLogpersist);
460                 }
461             }
462             mLogpersist = null;
463         }
464         mUsbConfiguration = addListPreference(USB_CONFIGURATION_KEY);
465         mWebViewProvider = addListPreference(WEBVIEW_PROVIDER_KEY);
466         mWebViewMultiprocess = findAndInitSwitchPref(WEBVIEW_MULTIPROCESS_KEY);
467         mBluetoothDisableAbsVolume = findAndInitSwitchPref(BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_KEY);
468
469         mWindowAnimationScale = addListPreference(WINDOW_ANIMATION_SCALE_KEY);
470         mTransitionAnimationScale = addListPreference(TRANSITION_ANIMATION_SCALE_KEY);
471         mAnimatorDurationScale = addListPreference(ANIMATOR_DURATION_SCALE_KEY);
472         mOverlayDisplayDevices = addListPreference(OVERLAY_DISPLAY_DEVICES_KEY);
473         mSimulateColorSpace = addListPreference(SIMULATE_COLOR_SPACE);
474         mUSBAudio = findAndInitSwitchPref(USB_AUDIO_KEY);
475         mForceResizable = findAndInitSwitchPref(FORCE_RESIZABLE_KEY);
476
477         mImmediatelyDestroyActivities = (SwitchPreference) findPreference(
478                 IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
479         mAllPrefs.add(mImmediatelyDestroyActivities);
480         mResetSwitchPrefs.add(mImmediatelyDestroyActivities);
481
482         mAppProcessLimit = addListPreference(APP_PROCESS_LIMIT_KEY);
483
484         mShowAllANRs = (SwitchPreference) findPreference(
485                 SHOW_ALL_ANRS_KEY);
486         mAllPrefs.add(mShowAllANRs);
487         mResetSwitchPrefs.add(mShowAllANRs);
488
489         Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY);
490         if (hdcpChecking != null) {
491             mAllPrefs.add(hdcpChecking);
492             removePreferenceForProduction(hdcpChecking);
493         }
494
495         PreferenceScreen convertFbePreference =
496                 (PreferenceScreen) findPreference(KEY_CONVERT_FBE);
497
498         try {
499             IBinder service = ServiceManager.getService("mount");
500             IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
501             if (!storageManager.isConvertibleToFBE()) {
502                 removePreference(KEY_CONVERT_FBE);
503             } else if ("file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
504                 convertFbePreference.setEnabled(false);
505                 convertFbePreference.setSummary(getResources()
506                         .getString(R.string.convert_to_file_encryption_done));
507             }
508         } catch (RemoteException e) {
509             removePreference(KEY_CONVERT_FBE);
510         }
511
512         mOtaDisableAutomaticUpdate = findAndInitSwitchPref(OTA_DISABLE_AUTOMATIC_UPDATE_KEY);
513
514         mColorModePreference = (ColorModePreference) findPreference(KEY_COLOR_MODE);
515         mColorModePreference.updateCurrentAndSupported();
516         if (mColorModePreference.getColorModeCount() < 2) {
517             removePreference(KEY_COLOR_MODE);
518             mColorModePreference = null;
519         }
520         updateWebViewProviderOptions();
521
522         mColorTemperaturePreference = (SwitchPreference) findPreference(COLOR_TEMPERATURE_KEY);
523         if (getResources().getBoolean(R.bool.config_enableColorTemperature)) {
524             mAllPrefs.add(mColorTemperaturePreference);
525             mResetSwitchPrefs.add(mColorTemperaturePreference);
526         } else {
527             removePreference(COLOR_TEMPERATURE_KEY);
528             mColorTemperaturePreference = null;
529         }
530
531         addDashboardCategoryPreferences();
532     }
533
534     @VisibleForTesting
535     void addDashboardCategoryPreferences() {
536         final PreferenceScreen screen = getPreferenceScreen();
537         final List<Preference> tilePrefs = mDashboardFeatureProvider.getPreferencesForCategory(
538                 getActivity(), getPrefContext(), CategoryKey.CATEGORY_SYSTEM_DEVELOPMENT);
539         if (tilePrefs != null) {
540             for (Preference preference : tilePrefs) {
541                 screen.addPreference(preference);
542             }
543         }
544     }
545
546     private ListPreference addListPreference(String prefKey) {
547         ListPreference pref = (ListPreference) findPreference(prefKey);
548         mAllPrefs.add(pref);
549         pref.setOnPreferenceChangeListener(this);
550         return pref;
551     }
552
553     private void disableForUser(Preference pref) {
554         if (pref != null) {
555             pref.setEnabled(false);
556             mDisabledPrefs.add(pref);
557         }
558     }
559
560     private SwitchPreference findAndInitSwitchPref(String key) {
561         SwitchPreference pref = (SwitchPreference) findPreference(key);
562         if (pref == null) {
563             throw new IllegalArgumentException("Cannot find preference with key = " + key);
564         }
565         mAllPrefs.add(pref);
566         mResetSwitchPrefs.add(pref);
567         return pref;
568     }
569
570     @Override
571     public void onActivityCreated(Bundle savedInstanceState) {
572         super.onActivityCreated(savedInstanceState);
573
574         final SettingsActivity activity = (SettingsActivity) getActivity();
575
576         mSwitchBar = activity.getSwitchBar();
577         if (mUnavailable) {
578             mSwitchBar.setEnabled(false);
579             return;
580         }
581
582         mSwitchBar.addOnSwitchChangeListener(this);
583     }
584
585     private boolean removePreferenceForProduction(Preference preference) {
586         if ("user".equals(Build.TYPE)) {
587             removePreference(preference);
588             return true;
589         }
590         return false;
591     }
592
593     private void removePreference(Preference preference) {
594         getPreferenceScreen().removePreference(preference);
595         mAllPrefs.remove(preference);
596         mResetSwitchPrefs.remove(preference);
597     }
598
599     private void setPrefsEnabledState(boolean enabled) {
600         for (int i = 0; i < mAllPrefs.size(); i++) {
601             Preference pref = mAllPrefs.get(i);
602             pref.setEnabled(enabled && !mDisabledPrefs.contains(pref));
603         }
604         updateAllOptions();
605     }
606
607     @Override
608     public void onResume() {
609         super.onResume();
610
611         if (mUnavailable) {
612             // Show error message
613             if (!isUiRestrictedByOnlyAdmin()) {
614                 getEmptyTextView().setText(R.string.development_settings_not_available);
615             }
616             getPreferenceScreen().removeAll();
617             return;
618         }
619
620         // A DeviceAdmin has specified a maximum time until the device
621         // will lock...  in this case we can't allow the user to turn
622         // on "stay awake when plugged in" because that would defeat the
623         // restriction.
624         final EnforcedAdmin admin = RestrictedLockUtils.checkIfMaximumTimeToLockIsSet(
625                 getActivity());
626         mKeepScreenOn.setDisabledByAdmin(admin);
627         if (admin == null) {
628             mDisabledPrefs.remove(mKeepScreenOn);
629         } else {
630             mDisabledPrefs.add(mKeepScreenOn);
631         }
632
633         final ContentResolver cr = getActivity().getContentResolver();
634         mLastEnabledState = Settings.Global.getInt(cr,
635                 Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
636         mSwitchBar.setChecked(mLastEnabledState);
637         setPrefsEnabledState(mLastEnabledState);
638
639         if (mHaveDebugSettings && !mLastEnabledState) {
640             // Overall debugging is disabled, but there are some debug
641             // settings that are enabled.  This is an invalid state.  Switch
642             // to debug settings being enabled, so the user knows there is
643             // stuff enabled and can turn it all off if they want.
644             Settings.Global.putInt(getActivity().getContentResolver(),
645                     Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
646             mLastEnabledState = true;
647             mSwitchBar.setChecked(mLastEnabledState);
648             setPrefsEnabledState(mLastEnabledState);
649         }
650         mSwitchBar.show();
651
652         if (mColorModePreference != null) {
653             mColorModePreference.startListening();
654             mColorModePreference.updateCurrentAndSupported();
655         }
656     }
657
658     @Override
659     public void onPause() {
660         super.onPause();
661         if (mColorModePreference != null) {
662             mColorModePreference.stopListening();
663         }
664     }
665
666     @Override
667     public View onCreateView(LayoutInflater inflater, ViewGroup container,
668             Bundle savedInstanceState) {
669         IntentFilter filter = new IntentFilter();
670         filter.addAction(UsbManager.ACTION_USB_STATE);
671         if (getActivity().registerReceiver(mUsbReceiver, filter) == null) {
672             updateUsbConfigurationValues();
673         }
674         return super.onCreateView(inflater, container, savedInstanceState);
675     }
676
677     @Override
678     public void onDestroyView() {
679         super.onDestroyView();
680
681         if (mUnavailable) {
682             return;
683         }
684         mSwitchBar.removeOnSwitchChangeListener(this);
685         mSwitchBar.hide();
686         getActivity().unregisterReceiver(mUsbReceiver);
687     }
688
689     void updateSwitchPreference(SwitchPreference switchPreference, boolean value) {
690         switchPreference.setChecked(value);
691         mHaveDebugSettings |= value;
692     }
693
694     private void updateAllOptions() {
695         final Context context = getActivity();
696         final ContentResolver cr = context.getContentResolver();
697         mHaveDebugSettings = false;
698         updateSwitchPreference(mEnableAdb, Settings.Global.getInt(cr,
699                 Settings.Global.ADB_ENABLED, 0) != 0);
700         if (mEnableTerminal != null) {
701             updateSwitchPreference(mEnableTerminal,
702                     context.getPackageManager().getApplicationEnabledSetting(TERMINAL_APP_PACKAGE)
703                             == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
704         }
705         updateSwitchPreference(mBugreportInPower, Settings.Secure.getInt(cr,
706                 Settings.Global.BUGREPORT_IN_POWER_MENU, 0) != 0);
707         updateSwitchPreference(mKeepScreenOn, Settings.Global.getInt(cr,
708                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0) != 0);
709         updateSwitchPreference(mBtHciSnoopLog, Settings.Secure.getInt(cr,
710                 Settings.Secure.BLUETOOTH_HCI_LOG, 0) != 0);
711         updateSwitchPreference(mDebugViewAttributes, Settings.Global.getInt(cr,
712                 Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0);
713         updateSwitchPreference(mForceAllowOnExternal, Settings.Global.getInt(cr,
714                 Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0);
715         updateHdcpValues();
716         updatePasswordSummary();
717         updateDebuggerOptions();
718         updateMockLocation();
719         updateStrictModeVisualOptions();
720         updatePointerLocationOptions();
721         updateShowTouchesOptions();
722         updateFlingerOptions();
723         updateHardwareUiOptions();
724         updateMsaaOptions();
725         updateTrackFrameTimeOptions();
726         updateShowNonRectClipOptions();
727         updateShowHwScreenUpdatesOptions();
728         updateShowHwLayersUpdatesOptions();
729         updateDebugHwOverdrawOptions();
730         updateDebugLayoutOptions();
731         updateAnimationScaleOptions();
732         updateOverlayDisplayDevicesOptions();
733         updateImmediatelyDestroyActivitiesOptions();
734         updateAppProcessLimitOptions();
735         updateShowAllANRsOptions();
736         updateVerifyAppsOverUsbOptions();
737         updateOtaDisableAutomaticUpdateOptions();
738         updateBugreportOptions();
739         updateForceRtlOptions();
740         updateLogdSizeValues();
741         updateLogpersistValues();
742         updateWifiDisplayCertificationOptions();
743         updateWifiVerboseLoggingOptions();
744         updateWifiAggressiveHandoverOptions();
745         updateWifiAllowScansWithTrafficOptions();
746         updateMobileDataAlwaysOnOptions();
747         updateSimulateColorSpace();
748         updateUSBAudioOptions();
749         updateForceResizableOptions();
750         updateWebViewMultiprocessOptions();
751         updateWebViewProviderOptions();
752         updateOemUnlockOptions();
753         if (mColorTemperaturePreference != null) {
754             updateColorTemperature();
755         }
756         updateBluetoothDisableAbsVolumeOptions();
757     }
758
759     private void resetDangerousOptions() {
760         mDontPokeProperties = true;
761         for (int i = 0; i < mResetSwitchPrefs.size(); i++) {
762             SwitchPreference cb = mResetSwitchPrefs.get(i);
763             if (cb.isChecked()) {
764                 cb.setChecked(false);
765                 onPreferenceTreeClick(cb);
766             }
767         }
768         resetDebuggerOptions();
769         writeLogpersistOption(null, true);
770         writeLogdSizeOption(null);
771         writeAnimationScaleOption(0, mWindowAnimationScale, null);
772         writeAnimationScaleOption(1, mTransitionAnimationScale, null);
773         writeAnimationScaleOption(2, mAnimatorDurationScale, null);
774         // Only poke the color space setting if we control it.
775         if (usingDevelopmentColorSpace()) {
776             writeSimulateColorSpace(-1);
777         }
778         writeOverlayDisplayDevicesOptions(null);
779         writeAppProcessLimitOptions(null);
780         mHaveDebugSettings = false;
781         updateAllOptions();
782         mDontPokeProperties = false;
783         pokeSystemProperties();
784     }
785
786     private void updateWebViewProviderOptions() {
787         try {
788             WebViewProviderInfo[] providers = mWebViewUpdateService.getValidWebViewPackages();
789             if (providers == null) {
790                 Log.e(TAG, "No WebView providers available");
791                 return;
792             }
793             ArrayList<String> options = new ArrayList<String>();
794             ArrayList<String> values = new ArrayList<String>();
795             for (int n = 0; n < providers.length; n++) {
796                 if (Utils.isPackageEnabled(getActivity(), providers[n].packageName)) {
797                     options.add(providers[n].description);
798                     values.add(providers[n].packageName);
799                 }
800             }
801             mWebViewProvider.setEntries(options.toArray(new String[options.size()]));
802             mWebViewProvider.setEntryValues(values.toArray(new String[values.size()]));
803
804             String value = mWebViewUpdateService.getCurrentWebViewPackageName();
805             if (value == null) {
806                 value = "";
807             }
808
809             for (int i = 0; i < values.size(); i++) {
810                 if (value.contentEquals(values.get(i))) {
811                     mWebViewProvider.setValueIndex(i);
812                     return;
813                 }
814             }
815         } catch (RemoteException e) {
816         }
817     }
818
819     private void updateWebViewMultiprocessOptions() {
820         updateSwitchPreference(mWebViewMultiprocess,
821                 Settings.Global.getInt(getActivity().getContentResolver(),
822                         Settings.Global.WEBVIEW_MULTIPROCESS, 0) != 0);
823     }
824
825     private void writeWebViewMultiprocessOptions() {
826         boolean value = mWebViewMultiprocess.isChecked();
827         Settings.Global.putInt(getActivity().getContentResolver(),
828                 Settings.Global.WEBVIEW_MULTIPROCESS, value ? 1 : 0);
829
830         try {
831             String wv_package = mWebViewUpdateService.getCurrentWebViewPackageName();
832             ActivityManager.getService().killPackageDependents(
833                     wv_package, UserHandle.USER_ALL);
834         } catch (RemoteException e) {
835         }
836     }
837
838     private void updateHdcpValues() {
839         ListPreference hdcpChecking = (ListPreference) findPreference(HDCP_CHECKING_KEY);
840         if (hdcpChecking != null) {
841             String currentValue = SystemProperties.get(HDCP_CHECKING_PROPERTY);
842             String[] values = getResources().getStringArray(R.array.hdcp_checking_values);
843             String[] summaries = getResources().getStringArray(R.array.hdcp_checking_summaries);
844             int index = 1; // Defaults to drm-only. Needs to match with R.array.hdcp_checking_values
845             for (int i = 0; i < values.length; i++) {
846                 if (currentValue.equals(values[i])) {
847                     index = i;
848                     break;
849                 }
850             }
851             hdcpChecking.setValue(values[index]);
852             hdcpChecking.setSummary(summaries[index]);
853             hdcpChecking.setOnPreferenceChangeListener(this);
854         }
855     }
856
857     private void updatePasswordSummary() {
858         try {
859             if (mBackupManager.hasBackupPassword()) {
860                 mPassword.setSummary(R.string.local_backup_password_summary_change);
861             } else {
862                 mPassword.setSummary(R.string.local_backup_password_summary_none);
863             }
864         } catch (RemoteException e) {
865             // Not much we can do here
866         }
867     }
868
869     private void writeBtHciSnoopLogOptions() {
870         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
871         adapter.configHciSnoopLog(mBtHciSnoopLog.isChecked());
872         Settings.Secure.putInt(getActivity().getContentResolver(),
873                 Settings.Secure.BLUETOOTH_HCI_LOG,
874                 mBtHciSnoopLog.isChecked() ? 1 : 0);
875     }
876
877     private boolean writeWebViewProviderOptions(Object newValue) {
878         try {
879             String updatedProvider = mWebViewUpdateService.changeProviderAndSetting(
880                     newValue == null ? "" : newValue.toString());
881             updateWebViewProviderOptions();
882             return newValue != null && newValue.equals(updatedProvider);
883         } catch (RemoteException e) {
884         }
885         return false;
886     }
887
888     private void writeDebuggerOptions() {
889         try {
890             ActivityManager.getService().setDebugApp(
891                     mDebugApp, mWaitForDebugger.isChecked(), true);
892         } catch (RemoteException ex) {
893         }
894     }
895
896     private void writeMockLocation() {
897         AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
898
899         // Disable the app op of the previous mock location app if such.
900         List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
901         if (packageOps != null) {
902             // Should be one but in case we are in a bad state due to use of command line tools.
903             for (PackageOps packageOp : packageOps) {
904                 if (packageOp.getOps().get(0).getMode() != AppOpsManager.MODE_ERRORED) {
905                     String oldMockLocationApp = packageOp.getPackageName();
906                     try {
907                         ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
908                                 oldMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
909                         appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
910                                 oldMockLocationApp, AppOpsManager.MODE_ERRORED);
911                     } catch (NameNotFoundException e) {
912                         /* ignore */
913                     }
914                 }
915             }
916         }
917
918         // Enable the app op of the new mock location app if such.
919         if (!TextUtils.isEmpty(mMockLocationApp)) {
920             try {
921                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
922                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
923                 appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
924                         mMockLocationApp, AppOpsManager.MODE_ALLOWED);
925             } catch (NameNotFoundException e) {
926                 /* ignore */
927             }
928         }
929     }
930
931     private static void resetDebuggerOptions() {
932         try {
933             ActivityManager.getService().setDebugApp(
934                     null, false, true);
935         } catch (RemoteException ex) {
936         }
937     }
938
939     private void updateDebuggerOptions() {
940         mDebugApp = Settings.Global.getString(
941                 getActivity().getContentResolver(), Settings.Global.DEBUG_APP);
942         updateSwitchPreference(mWaitForDebugger, Settings.Global.getInt(
943                 getActivity().getContentResolver(), Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0);
944         if (mDebugApp != null && mDebugApp.length() > 0) {
945             String label;
946             try {
947                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mDebugApp,
948                         PackageManager.GET_DISABLED_COMPONENTS);
949                 CharSequence lab = getActivity().getPackageManager().getApplicationLabel(ai);
950                 label = lab != null ? lab.toString() : mDebugApp;
951             } catch (PackageManager.NameNotFoundException e) {
952                 label = mDebugApp;
953             }
954             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_set, label));
955             mWaitForDebugger.setEnabled(true);
956             mHaveDebugSettings = true;
957         } else {
958             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_not_set));
959             mWaitForDebugger.setEnabled(false);
960         }
961     }
962
963     private void updateMockLocation() {
964         AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
965
966         List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
967         if (packageOps != null) {
968             for (PackageOps packageOp : packageOps) {
969                 if (packageOp.getOps().get(0).getMode() == AppOpsManager.MODE_ALLOWED) {
970                     mMockLocationApp = packageOps.get(0).getPackageName();
971                     break;
972                 }
973             }
974         }
975
976         if (!TextUtils.isEmpty(mMockLocationApp)) {
977             String label = mMockLocationApp;
978             try {
979                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
980                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
981                 CharSequence appLabel = getPackageManager().getApplicationLabel(ai);
982                 if (appLabel != null) {
983                     label = appLabel.toString();
984                 }
985             } catch (PackageManager.NameNotFoundException e) {
986                 /* ignore */
987             }
988
989             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_set, label));
990             mHaveDebugSettings = true;
991         } else {
992             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_not_set));
993         }
994     }
995
996     private void updateVerifyAppsOverUsbOptions() {
997         updateSwitchPreference(mVerifyAppsOverUsb,
998                 Settings.Global.getInt(getActivity().getContentResolver(),
999                         Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0);
1000         mVerifyAppsOverUsb.setEnabled(enableVerifierSetting());
1001     }
1002
1003     private void writeVerifyAppsOverUsbOptions() {
1004         Settings.Global.putInt(getActivity().getContentResolver(),
1005                 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
1006                 mVerifyAppsOverUsb.isChecked() ? 1 : 0);
1007     }
1008
1009     private void updateOtaDisableAutomaticUpdateOptions() {
1010         // We use the "disabled status" in code, but show the opposite text
1011         // "Automatic system updates" on screen. So a value 0 indicates the
1012         // automatic update is enabled.
1013         updateSwitchPreference(mOtaDisableAutomaticUpdate, Settings.Global.getInt(
1014                 getActivity().getContentResolver(),
1015                 Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, 0) != 1);
1016     }
1017
1018     private void writeOtaDisableAutomaticUpdateOptions() {
1019         // We use the "disabled status" in code, but show the opposite text
1020         // "Automatic system updates" on screen. So a value 0 indicates the
1021         // automatic update is enabled.
1022         Settings.Global.putInt(getActivity().getContentResolver(),
1023                 Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE,
1024                 mOtaDisableAutomaticUpdate.isChecked() ? 0 : 1);
1025     }
1026
1027     private boolean enableVerifierSetting() {
1028         final ContentResolver cr = getActivity().getContentResolver();
1029         if (Settings.Global.getInt(cr, Settings.Global.ADB_ENABLED, 0) == 0) {
1030             return false;
1031         }
1032         if (Settings.Global.getInt(cr, Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 0) {
1033             return false;
1034         } else {
1035             final PackageManager pm = getActivity().getPackageManager();
1036             final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1037             verification.setType(PACKAGE_MIME_TYPE);
1038             verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1039             final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(verification, 0);
1040             if (receivers.size() == 0) {
1041                 return false;
1042             }
1043         }
1044         return true;
1045     }
1046
1047     private boolean showVerifierSetting() {
1048         return Settings.Global.getInt(getActivity().getContentResolver(),
1049                 Settings.Global.PACKAGE_VERIFIER_SETTING_VISIBLE, 1) > 0;
1050     }
1051
1052     private static boolean showEnableOemUnlockPreference() {
1053         return !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
1054     }
1055
1056     private boolean enableOemUnlockPreference() {
1057         return !isBootloaderUnlocked() && isOemUnlockAllowed();
1058     }
1059
1060     private void updateOemUnlockOptions() {
1061         if (mEnableOemUnlock != null) {
1062             updateSwitchPreference(mEnableOemUnlock, Utils.isOemUnlockEnabled(getActivity()));
1063             updateOemUnlockSettingDescription();
1064             // Showing mEnableOemUnlock preference as device has persistent data block.
1065             mEnableOemUnlock.setDisabledByAdmin(null);
1066             mEnableOemUnlock.setEnabled(enableOemUnlockPreference());
1067             if (mEnableOemUnlock.isEnabled()) {
1068                 // Check restriction, disable mEnableOemUnlock and apply policy transparency.
1069                 mEnableOemUnlock.checkRestrictionAndSetDisabled(UserManager.DISALLOW_FACTORY_RESET);
1070             }
1071             if (mEnableOemUnlock.isEnabled()) {
1072                 // Check restriction, disable mEnableOemUnlock and apply policy transparency.
1073                 mEnableOemUnlock.checkRestrictionAndSetDisabled(UserManager.DISALLOW_OEM_UNLOCK);
1074             }
1075         }
1076     }
1077
1078     private void updateBugreportOptions() {
1079         mBugreport.setEnabled(true);
1080         mBugreportInPower.setEnabled(true);
1081         setBugreportStorageProviderStatus();
1082     }
1083
1084     private void setBugreportStorageProviderStatus() {
1085         final ComponentName componentName = new ComponentName("com.android.shell",
1086                 "com.android.shell.BugreportStorageProvider");
1087         final boolean enabled = mBugreportInPower.isChecked();
1088         getPackageManager().setComponentEnabledSetting(componentName,
1089                 enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1090                         : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
1091                 0);
1092     }
1093
1094     // Returns the current state of the system property that controls
1095     // strictmode flashes.  One of:
1096     //    0: not explicitly set one way or another
1097     //    1: on
1098     //    2: off
1099     private static int currentStrictModeActiveIndex() {
1100         if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) {
1101             return 0;
1102         }
1103         boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false);
1104         return enabled ? 1 : 2;
1105     }
1106
1107     private void writeStrictModeVisualOptions() {
1108         try {
1109             mWindowManager.setStrictModeVisualIndicatorPreference(mStrictMode.isChecked()
1110                     ? "1" : "");
1111         } catch (RemoteException e) {
1112         }
1113     }
1114
1115     private void updateStrictModeVisualOptions() {
1116         updateSwitchPreference(mStrictMode, currentStrictModeActiveIndex() == 1);
1117     }
1118
1119     private void writePointerLocationOptions() {
1120         Settings.System.putInt(getActivity().getContentResolver(),
1121                 Settings.System.POINTER_LOCATION, mPointerLocation.isChecked() ? 1 : 0);
1122     }
1123
1124     private void updatePointerLocationOptions() {
1125         updateSwitchPreference(mPointerLocation,
1126                 Settings.System.getInt(getActivity().getContentResolver(),
1127                         Settings.System.POINTER_LOCATION, 0) != 0);
1128     }
1129
1130     private void writeShowTouchesOptions() {
1131         Settings.System.putInt(getActivity().getContentResolver(),
1132                 Settings.System.SHOW_TOUCHES, mShowTouches.isChecked() ? 1 : 0);
1133     }
1134
1135     private void updateShowTouchesOptions() {
1136         updateSwitchPreference(mShowTouches,
1137                 Settings.System.getInt(getActivity().getContentResolver(),
1138                         Settings.System.SHOW_TOUCHES, 0) != 0);
1139     }
1140
1141     private void updateFlingerOptions() {
1142         // magic communication with surface flinger.
1143         try {
1144             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1145             if (flinger != null) {
1146                 Parcel data = Parcel.obtain();
1147                 Parcel reply = Parcel.obtain();
1148                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1149                 flinger.transact(1010, data, reply, 0);
1150                 @SuppressWarnings("unused")
1151                 int showCpu = reply.readInt();
1152                 @SuppressWarnings("unused")
1153                 int enableGL = reply.readInt();
1154                 int showUpdates = reply.readInt();
1155                 updateSwitchPreference(mShowScreenUpdates, showUpdates != 0);
1156                 @SuppressWarnings("unused")
1157                 int showBackground = reply.readInt();
1158                 int disableOverlays = reply.readInt();
1159                 updateSwitchPreference(mDisableOverlays, disableOverlays != 0);
1160                 reply.recycle();
1161                 data.recycle();
1162             }
1163         } catch (RemoteException ex) {
1164         }
1165     }
1166
1167     private void writeShowUpdatesOption() {
1168         try {
1169             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1170             if (flinger != null) {
1171                 Parcel data = Parcel.obtain();
1172                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1173                 final int showUpdates = mShowScreenUpdates.isChecked() ? 1 : 0;
1174                 data.writeInt(showUpdates);
1175                 flinger.transact(1002, data, null, 0);
1176                 data.recycle();
1177
1178                 updateFlingerOptions();
1179             }
1180         } catch (RemoteException ex) {
1181         }
1182     }
1183
1184     private void writeDisableOverlaysOption() {
1185         try {
1186             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1187             if (flinger != null) {
1188                 Parcel data = Parcel.obtain();
1189                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1190                 final int disableOverlays = mDisableOverlays.isChecked() ? 1 : 0;
1191                 data.writeInt(disableOverlays);
1192                 flinger.transact(1008, data, null, 0);
1193                 data.recycle();
1194
1195                 updateFlingerOptions();
1196             }
1197         } catch (RemoteException ex) {
1198         }
1199     }
1200
1201     private void updateHardwareUiOptions() {
1202         updateSwitchPreference(mForceHardwareUi,
1203                 SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false));
1204     }
1205
1206     private void writeHardwareUiOptions() {
1207         SystemProperties.set(HARDWARE_UI_PROPERTY, mForceHardwareUi.isChecked() ? "true" : "false");
1208         pokeSystemProperties();
1209     }
1210
1211     private void updateMsaaOptions() {
1212         updateSwitchPreference(mForceMsaa, SystemProperties.getBoolean(MSAA_PROPERTY, false));
1213     }
1214
1215     private void writeMsaaOptions() {
1216         SystemProperties.set(MSAA_PROPERTY, mForceMsaa.isChecked() ? "true" : "false");
1217         pokeSystemProperties();
1218     }
1219
1220     private void updateTrackFrameTimeOptions() {
1221         String value = SystemProperties.get(ThreadedRenderer.PROFILE_PROPERTY);
1222         if (value == null) {
1223             value = "";
1224         }
1225
1226         CharSequence[] values = mTrackFrameTime.getEntryValues();
1227         for (int i = 0; i < values.length; i++) {
1228             if (value.contentEquals(values[i])) {
1229                 mTrackFrameTime.setValueIndex(i);
1230                 mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[i]);
1231                 return;
1232             }
1233         }
1234         mTrackFrameTime.setValueIndex(0);
1235         mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[0]);
1236     }
1237
1238     private void writeTrackFrameTimeOptions(Object newValue) {
1239         SystemProperties.set(ThreadedRenderer.PROFILE_PROPERTY,
1240                 newValue == null ? "" : newValue.toString());
1241         pokeSystemProperties();
1242         updateTrackFrameTimeOptions();
1243     }
1244
1245     private void updateShowNonRectClipOptions() {
1246         String value = SystemProperties.get(
1247                 ThreadedRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY);
1248         if (value == null) {
1249             value = "hide";
1250         }
1251
1252         CharSequence[] values = mShowNonRectClip.getEntryValues();
1253         for (int i = 0; i < values.length; i++) {
1254             if (value.contentEquals(values[i])) {
1255                 mShowNonRectClip.setValueIndex(i);
1256                 mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[i]);
1257                 return;
1258             }
1259         }
1260         mShowNonRectClip.setValueIndex(0);
1261         mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[0]);
1262     }
1263
1264     private void writeShowNonRectClipOptions(Object newValue) {
1265         SystemProperties.set(ThreadedRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY,
1266                 newValue == null ? "" : newValue.toString());
1267         pokeSystemProperties();
1268         updateShowNonRectClipOptions();
1269     }
1270
1271     private void updateShowHwScreenUpdatesOptions() {
1272         updateSwitchPreference(mShowHwScreenUpdates,
1273                 SystemProperties.getBoolean(ThreadedRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, false));
1274     }
1275
1276     private void writeShowHwScreenUpdatesOptions() {
1277         SystemProperties.set(ThreadedRenderer.DEBUG_DIRTY_REGIONS_PROPERTY,
1278                 mShowHwScreenUpdates.isChecked() ? "true" : null);
1279         pokeSystemProperties();
1280     }
1281
1282     private void updateShowHwLayersUpdatesOptions() {
1283         updateSwitchPreference(mShowHwLayersUpdates, SystemProperties.getBoolean(
1284                 ThreadedRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY, false));
1285     }
1286
1287     private void writeShowHwLayersUpdatesOptions() {
1288         SystemProperties.set(ThreadedRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY,
1289                 mShowHwLayersUpdates.isChecked() ? "true" : null);
1290         pokeSystemProperties();
1291     }
1292
1293     private void updateDebugHwOverdrawOptions() {
1294         String value = SystemProperties.get(ThreadedRenderer.DEBUG_OVERDRAW_PROPERTY);
1295         if (value == null) {
1296             value = "";
1297         }
1298
1299         CharSequence[] values = mDebugHwOverdraw.getEntryValues();
1300         for (int i = 0; i < values.length; i++) {
1301             if (value.contentEquals(values[i])) {
1302                 mDebugHwOverdraw.setValueIndex(i);
1303                 mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[i]);
1304                 return;
1305             }
1306         }
1307         mDebugHwOverdraw.setValueIndex(0);
1308         mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[0]);
1309     }
1310
1311     private void writeDebugHwOverdrawOptions(Object newValue) {
1312         SystemProperties.set(ThreadedRenderer.DEBUG_OVERDRAW_PROPERTY,
1313                 newValue == null ? "" : newValue.toString());
1314         pokeSystemProperties();
1315         updateDebugHwOverdrawOptions();
1316     }
1317
1318     private void updateDebugLayoutOptions() {
1319         updateSwitchPreference(mDebugLayout,
1320                 SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false));
1321     }
1322
1323     private void writeDebugLayoutOptions() {
1324         SystemProperties.set(View.DEBUG_LAYOUT_PROPERTY,
1325                 mDebugLayout.isChecked() ? "true" : "false");
1326         pokeSystemProperties();
1327     }
1328
1329     private void updateSimulateColorSpace() {
1330         final ContentResolver cr = getContentResolver();
1331         final boolean enabled = Settings.Secure.getInt(
1332                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1333         if (enabled) {
1334             final String mode = Integer.toString(Settings.Secure.getInt(
1335                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1336                     AccessibilityManager.DALTONIZER_DISABLED));
1337             mSimulateColorSpace.setValue(mode);
1338             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1339             if (index < 0) {
1340                 // We're using a mode controlled by accessibility preferences.
1341                 mSimulateColorSpace.setSummary(getString(R.string.daltonizer_type_overridden,
1342                         getString(R.string.accessibility_display_daltonizer_preference_title)));
1343             } else {
1344                 mSimulateColorSpace.setSummary("%s");
1345             }
1346         } else {
1347             mSimulateColorSpace.setValue(
1348                     Integer.toString(AccessibilityManager.DALTONIZER_DISABLED));
1349         }
1350     }
1351
1352     /**
1353      * @return <code>true</code> if the color space preference is currently
1354      * controlled by development settings
1355      */
1356     private boolean usingDevelopmentColorSpace() {
1357         final ContentResolver cr = getContentResolver();
1358         final boolean enabled = Settings.Secure.getInt(
1359                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1360         if (enabled) {
1361             final String mode = Integer.toString(Settings.Secure.getInt(
1362                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1363                     AccessibilityManager.DALTONIZER_DISABLED));
1364             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1365             if (index >= 0) {
1366                 // We're using a mode controlled by developer preferences.
1367                 return true;
1368             }
1369         }
1370         return false;
1371     }
1372
1373     private void writeSimulateColorSpace(Object value) {
1374         final ContentResolver cr = getContentResolver();
1375         final int newMode = Integer.parseInt(value.toString());
1376         if (newMode < 0) {
1377             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0);
1378         } else {
1379             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 1);
1380             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, newMode);
1381         }
1382     }
1383
1384     private void updateColorTemperature() {
1385         updateSwitchPreference(mColorTemperaturePreference,
1386                 SystemProperties.getBoolean(COLOR_TEMPERATURE_PROPERTY, false));
1387     }
1388
1389     private void writeColorTemperature() {
1390         SystemProperties.set(COLOR_TEMPERATURE_PROPERTY,
1391                 mColorTemperaturePreference.isChecked() ? "1" : "0");
1392         pokeSystemProperties();
1393         Toast.makeText(getActivity(), R.string.color_temperature_toast, Toast.LENGTH_LONG).show();
1394     }
1395
1396     private void updateUSBAudioOptions() {
1397         updateSwitchPreference(mUSBAudio, Settings.Secure.getInt(getContentResolver(),
1398                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED, 0) != 0);
1399     }
1400
1401     private void writeUSBAudioOptions() {
1402         Settings.Secure.putInt(getContentResolver(),
1403                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED,
1404                 mUSBAudio.isChecked() ? 1 : 0);
1405     }
1406
1407     private void updateForceResizableOptions() {
1408         updateSwitchPreference(mForceResizable, Settings.Global.getInt(getContentResolver(),
1409                 Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0);
1410     }
1411
1412     private void writeForceResizableOptions() {
1413         Settings.Global.putInt(getContentResolver(),
1414                 Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES,
1415                 mForceResizable.isChecked() ? 1 : 0);
1416     }
1417
1418     private void updateForceRtlOptions() {
1419         updateSwitchPreference(mForceRtlLayout,
1420                 Settings.Global.getInt(getActivity().getContentResolver(),
1421                         Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0);
1422     }
1423
1424     private void writeForceRtlOptions() {
1425         boolean value = mForceRtlLayout.isChecked();
1426         Settings.Global.putInt(getActivity().getContentResolver(),
1427                 Settings.Global.DEVELOPMENT_FORCE_RTL, value ? 1 : 0);
1428         SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, value ? "1" : "0");
1429         LocalePicker.updateLocale(getActivity().getResources().getConfiguration().locale);
1430     }
1431
1432     private void updateWifiDisplayCertificationOptions() {
1433         updateSwitchPreference(mWifiDisplayCertification, Settings.Global.getInt(
1434                 getActivity().getContentResolver(),
1435                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, 0) != 0);
1436     }
1437
1438     private void writeWifiDisplayCertificationOptions() {
1439         Settings.Global.putInt(getActivity().getContentResolver(),
1440                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
1441                 mWifiDisplayCertification.isChecked() ? 1 : 0);
1442     }
1443
1444     private void updateWifiVerboseLoggingOptions() {
1445         boolean enabled = mWifiManager.getVerboseLoggingLevel() > 0;
1446         updateSwitchPreference(mWifiVerboseLogging, enabled);
1447     }
1448
1449     private void writeWifiVerboseLoggingOptions() {
1450         mWifiManager.enableVerboseLogging(mWifiVerboseLogging.isChecked() ? 1 : 0);
1451     }
1452
1453     private void updateWifiAggressiveHandoverOptions() {
1454         boolean enabled = mWifiManager.getAggressiveHandover() > 0;
1455         updateSwitchPreference(mWifiAggressiveHandover, enabled);
1456     }
1457
1458     private void writeWifiAggressiveHandoverOptions() {
1459         mWifiManager.enableAggressiveHandover(mWifiAggressiveHandover.isChecked() ? 1 : 0);
1460     }
1461
1462     private void updateWifiAllowScansWithTrafficOptions() {
1463         boolean enabled = mWifiManager.getAllowScansWithTraffic() > 0;
1464         updateSwitchPreference(mWifiAllowScansWithTraffic, enabled);
1465     }
1466
1467     private void writeWifiAllowScansWithTrafficOptions() {
1468         mWifiManager.setAllowScansWithTraffic(mWifiAllowScansWithTraffic.isChecked() ? 1 : 0);
1469     }
1470
1471     private void updateBluetoothDisableAbsVolumeOptions() {
1472         updateSwitchPreference(mBluetoothDisableAbsVolume,
1473                 SystemProperties.getBoolean(BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_PROPERTY, false));
1474     }
1475
1476     private void writeBluetoothDisableAbsVolumeOptions() {
1477         SystemProperties.set(BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_PROPERTY,
1478                 mBluetoothDisableAbsVolume.isChecked() ? "true" : "false");
1479     }
1480
1481     private void updateMobileDataAlwaysOnOptions() {
1482         updateSwitchPreference(mMobileDataAlwaysOn, Settings.Global.getInt(
1483                 getActivity().getContentResolver(),
1484                 Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) != 0);
1485     }
1486
1487     private void writeMobileDataAlwaysOnOptions() {
1488         Settings.Global.putInt(getActivity().getContentResolver(),
1489                 Settings.Global.MOBILE_DATA_ALWAYS_ON,
1490                 mMobileDataAlwaysOn.isChecked() ? 1 : 0);
1491     }
1492
1493     private String defaultLogdSizeValue() {
1494         String defaultValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1495         if ((defaultValue == null) || (defaultValue.length() == 0)) {
1496             if (SystemProperties.get("ro.config.low_ram").equals("true")) {
1497                 defaultValue = SELECT_LOGD_SVELTE_DEFAULT_SIZE_VALUE;
1498             } else {
1499                 defaultValue = SELECT_LOGD_DEFAULT_SIZE_VALUE;
1500             }
1501         }
1502         return defaultValue;
1503     }
1504
1505     private void updateLogdSizeValues() {
1506         if (mLogdSize != null) {
1507             String currentTag = SystemProperties.get(SELECT_LOGD_TAG_PROPERTY);
1508             String currentValue = SystemProperties.get(SELECT_LOGD_SIZE_PROPERTY);
1509             if ((currentTag != null) && currentTag.startsWith(SELECT_LOGD_TAG_SILENCE)) {
1510                 currentValue = SELECT_LOGD_OFF_SIZE_MARKER_VALUE;
1511             }
1512             if (mLogpersist != null) {
1513                 String currentLogpersistEnable
1514                         = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY_ENABLE);
1515                 if ((currentLogpersistEnable == null)
1516                         || !currentLogpersistEnable.equals("true")
1517                         || currentValue.equals(SELECT_LOGD_OFF_SIZE_MARKER_VALUE)) {
1518                     writeLogpersistOption(null, true);
1519                     mLogpersist.setEnabled(false);
1520                 } else if (mLastEnabledState) {
1521                     mLogpersist.setEnabled(true);
1522                 }
1523             }
1524             if ((currentValue == null) || (currentValue.length() == 0)) {
1525                 currentValue = defaultLogdSizeValue();
1526             }
1527             String[] values = getResources().getStringArray(R.array.select_logd_size_values);
1528             String[] titles = getResources().getStringArray(R.array.select_logd_size_titles);
1529             int index = 2; // punt to second entry if not found
1530             if (SystemProperties.get("ro.config.low_ram").equals("true")) {
1531                 mLogdSize.setEntries(R.array.select_logd_size_lowram_titles);
1532                 titles = getResources().getStringArray(R.array.select_logd_size_lowram_titles);
1533                 index = 1;
1534             }
1535             String[] summaries = getResources().getStringArray(R.array.select_logd_size_summaries);
1536             for (int i = 0; i < titles.length; i++) {
1537                 if (currentValue.equals(values[i])
1538                         || currentValue.equals(titles[i])) {
1539                     index = i;
1540                     break;
1541                 }
1542             }
1543             mLogdSize.setValue(values[index]);
1544             mLogdSize.setSummary(summaries[index]);
1545             mLogdSize.setOnPreferenceChangeListener(this);
1546         }
1547     }
1548
1549     private void writeLogdSizeOption(Object newValue) {
1550         boolean disable = (newValue != null) &&
1551                 (newValue.toString().equals(SELECT_LOGD_OFF_SIZE_MARKER_VALUE));
1552         String currentTag = SystemProperties.get(SELECT_LOGD_TAG_PROPERTY);
1553         if (currentTag == null) {
1554             currentTag = "";
1555         }
1556         // filter clean and unstack all references to our setting
1557         String newTag = currentTag.replaceAll(
1558                 ",+" + SELECT_LOGD_TAG_SILENCE, "").replaceFirst(
1559                 "^" + SELECT_LOGD_TAG_SILENCE + ",*", "").replaceAll(
1560                 ",+", ",").replaceFirst(
1561                 ",+$", "");
1562         if (disable) {
1563             newValue = SELECT_LOGD_MINIMUM_SIZE_VALUE;
1564             // Make sure snet_event_log get through first, but do not override
1565             String snetValue = SystemProperties.get(SELECT_LOGD_SNET_TAG_PROPERTY);
1566             if ((snetValue == null) || (snetValue.length() == 0)) {
1567                 snetValue = SystemProperties.get(SELECT_LOGD_RUNTIME_SNET_TAG_PROPERTY);
1568                 if ((snetValue == null) || (snetValue.length() == 0)) {
1569                     SystemProperties.set(SELECT_LOGD_SNET_TAG_PROPERTY, "I");
1570                 }
1571             }
1572             // Silence all log sources, security logs notwithstanding
1573             if (newTag.length() != 0) {
1574                 newTag = "," + newTag;
1575             }
1576             // Stack settings, stack to help preserve original value
1577             newTag = SELECT_LOGD_TAG_SILENCE + newTag;
1578         }
1579         if (!newTag.equals(currentTag)) {
1580             SystemProperties.set(SELECT_LOGD_TAG_PROPERTY, newTag);
1581         }
1582         String defaultValue = defaultLogdSizeValue();
1583         final String size = ((newValue != null) && (newValue.toString().length() != 0)) ?
1584                 newValue.toString() : defaultValue;
1585         SystemProperties.set(SELECT_LOGD_SIZE_PROPERTY, defaultValue.equals(size) ? "" : size);
1586         SystemProperties.set("ctl.start", "logd-reinit");
1587         pokeSystemProperties();
1588         updateLogdSizeValues();
1589     }
1590
1591     private void updateLogpersistValues() {
1592         if (mLogpersist == null) {
1593             return;
1594         }
1595         String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1596         if (currentValue == null) {
1597             currentValue = "";
1598         }
1599         String currentBuffers = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY_BUFFER);
1600         if ((currentBuffers == null) || (currentBuffers.length() == 0)) {
1601             currentBuffers = "all";
1602         }
1603         int index = 0;
1604         if (currentValue.equals(SELECT_LOGPERSIST_PROPERTY_SERVICE)) {
1605             index = 1;
1606             if (currentBuffers.equals("kernel")) {
1607                 index = 3;
1608             } else if (!currentBuffers.equals("all") &&
1609                     !currentBuffers.contains("radio") &&
1610                     currentBuffers.contains("security") &&
1611                     currentBuffers.contains("kernel")) {
1612                 index = 2;
1613                 if (!currentBuffers.contains("default")) {
1614                     String[] contains = {"main", "events", "system", "crash"};
1615                     for (int i = 0; i < contains.length; i++) {
1616                         if (!currentBuffers.contains(contains[i])) {
1617                             index = 1;
1618                             break;
1619                         }
1620                     }
1621                 }
1622             }
1623         }
1624         mLogpersist.setValue(
1625                 getResources().getStringArray(R.array.select_logpersist_values)[index]);
1626         mLogpersist.setSummary(
1627                 getResources().getStringArray(R.array.select_logpersist_summaries)[index]);
1628         mLogpersist.setOnPreferenceChangeListener(this);
1629         if (index != 0) {
1630             mLogpersistCleared = false;
1631         } else if (!mLogpersistCleared) {
1632             // would File.delete() directly but need to switch uid/gid to access
1633             SystemProperties.set(ACTUAL_LOGPERSIST_PROPERTY, SELECT_LOGPERSIST_PROPERTY_CLEAR);
1634             pokeSystemProperties();
1635             mLogpersistCleared = true;
1636         }
1637     }
1638
1639     private void setLogpersistOff(boolean update) {
1640         SystemProperties.set(SELECT_LOGPERSIST_PROPERTY_BUFFER, "");
1641         // deal with trampoline of empty properties
1642         SystemProperties.set(ACTUAL_LOGPERSIST_PROPERTY_BUFFER, "");
1643         SystemProperties.set(SELECT_LOGPERSIST_PROPERTY, "");
1644         SystemProperties.set(ACTUAL_LOGPERSIST_PROPERTY,
1645                 update ? "" : SELECT_LOGPERSIST_PROPERTY_STOP);
1646         pokeSystemProperties();
1647         if (update) {
1648             updateLogpersistValues();
1649         } else {
1650             for (int i = 0; i < 3; i++) {
1651                 String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1652                 if ((currentValue == null) || currentValue.equals("")) {
1653                     break;
1654                 }
1655                 try {
1656                     Thread.sleep(100);
1657                 } catch (InterruptedException e) {
1658                 }
1659             }
1660         }
1661     }
1662
1663     private void writeLogpersistOption(Object newValue, boolean skipWarning) {
1664         if (mLogpersist == null) {
1665             return;
1666         }
1667         String currentTag = SystemProperties.get(SELECT_LOGD_TAG_PROPERTY);
1668         if ((currentTag != null) && currentTag.startsWith(SELECT_LOGD_TAG_SILENCE)) {
1669             newValue = null;
1670             skipWarning = true;
1671         }
1672
1673         if ((newValue == null) || newValue.toString().equals("")) {
1674             if (skipWarning) {
1675                 mLogpersistCleared = false;
1676             } else if (!mLogpersistCleared) {
1677                 // if transitioning from on to off, pop up an are you sure?
1678                 String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1679                 if ((currentValue != null) &&
1680                         currentValue.equals(SELECT_LOGPERSIST_PROPERTY_SERVICE)) {
1681                     if (mLogpersistClearDialog != null) dismissDialogs();
1682                     mLogpersistClearDialog = new AlertDialog.Builder(getActivity()).setMessage(
1683                             getActivity().getResources().getString(
1684                                     R.string.dev_logpersist_clear_warning_message))
1685                             .setTitle(R.string.dev_logpersist_clear_warning_title)
1686                             .setPositiveButton(android.R.string.yes, this)
1687                             .setNegativeButton(android.R.string.no, this)
1688                             .show();
1689                     mLogpersistClearDialog.setOnDismissListener(this);
1690                     return;
1691                 }
1692             }
1693             setLogpersistOff(true);
1694             return;
1695         }
1696
1697         String currentBuffer = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY_BUFFER);
1698         if ((currentBuffer != null) && !currentBuffer.equals(newValue.toString())) {
1699             setLogpersistOff(false);
1700         }
1701         SystemProperties.set(SELECT_LOGPERSIST_PROPERTY_BUFFER, newValue.toString());
1702         SystemProperties.set(SELECT_LOGPERSIST_PROPERTY, SELECT_LOGPERSIST_PROPERTY_SERVICE);
1703         pokeSystemProperties();
1704         for (int i = 0; i < 3; i++) {
1705             String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1706             if ((currentValue != null)
1707                     && currentValue.equals(SELECT_LOGPERSIST_PROPERTY_SERVICE)) {
1708                 break;
1709             }
1710             try {
1711                 Thread.sleep(100);
1712             } catch (InterruptedException e) {
1713             }
1714         }
1715         updateLogpersistValues();
1716     }
1717
1718     private void updateUsbConfigurationValues() {
1719         if (mUsbConfiguration != null) {
1720             UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
1721
1722             String[] values = getResources().getStringArray(R.array.usb_configuration_values);
1723             String[] titles = getResources().getStringArray(R.array.usb_configuration_titles);
1724             int index = 0;
1725             for (int i = 0; i < titles.length; i++) {
1726                 if (manager.isFunctionEnabled(values[i])) {
1727                     index = i;
1728                     break;
1729                 }
1730             }
1731             mUsbConfiguration.setValue(values[index]);
1732             mUsbConfiguration.setSummary(titles[index]);
1733             mUsbConfiguration.setOnPreferenceChangeListener(this);
1734         }
1735     }
1736
1737     private void writeUsbConfigurationOption(Object newValue) {
1738         UsbManager manager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
1739         String function = newValue.toString();
1740         if (function.equals("none")) {
1741             manager.setCurrentFunction(function, false);
1742         } else {
1743             manager.setCurrentFunction(function, true);
1744         }
1745     }
1746
1747     private void writeImmediatelyDestroyActivitiesOptions() {
1748         try {
1749             ActivityManager.getService().setAlwaysFinish(
1750                     mImmediatelyDestroyActivities.isChecked());
1751         } catch (RemoteException ex) {
1752         }
1753     }
1754
1755     private void updateImmediatelyDestroyActivitiesOptions() {
1756         updateSwitchPreference(mImmediatelyDestroyActivities, Settings.Global.getInt(
1757                 getActivity().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0)
1758                 != 0);
1759     }
1760
1761     private void updateAnimationScaleValue(int which, ListPreference pref) {
1762         try {
1763             float scale = mWindowManager.getAnimationScale(which);
1764             if (scale != 1) {
1765                 mHaveDebugSettings = true;
1766             }
1767             CharSequence[] values = pref.getEntryValues();
1768             for (int i = 0; i < values.length; i++) {
1769                 float val = Float.parseFloat(values[i].toString());
1770                 if (scale <= val) {
1771                     pref.setValueIndex(i);
1772                     pref.setSummary(pref.getEntries()[i]);
1773                     return;
1774                 }
1775             }
1776             pref.setValueIndex(values.length - 1);
1777             pref.setSummary(pref.getEntries()[0]);
1778         } catch (RemoteException e) {
1779         }
1780     }
1781
1782     private void updateAnimationScaleOptions() {
1783         updateAnimationScaleValue(0, mWindowAnimationScale);
1784         updateAnimationScaleValue(1, mTransitionAnimationScale);
1785         updateAnimationScaleValue(2, mAnimatorDurationScale);
1786     }
1787
1788     private void writeAnimationScaleOption(int which, ListPreference pref, Object newValue) {
1789         try {
1790             float scale = newValue != null ? Float.parseFloat(newValue.toString()) : 1;
1791             mWindowManager.setAnimationScale(which, scale);
1792             updateAnimationScaleValue(which, pref);
1793         } catch (RemoteException e) {
1794         }
1795     }
1796
1797     private void updateOverlayDisplayDevicesOptions() {
1798         String value = Settings.Global.getString(getActivity().getContentResolver(),
1799                 Settings.Global.OVERLAY_DISPLAY_DEVICES);
1800         if (value == null) {
1801             value = "";
1802         }
1803
1804         CharSequence[] values = mOverlayDisplayDevices.getEntryValues();
1805         for (int i = 0; i < values.length; i++) {
1806             if (value.contentEquals(values[i])) {
1807                 mOverlayDisplayDevices.setValueIndex(i);
1808                 mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[i]);
1809                 return;
1810             }
1811         }
1812         mOverlayDisplayDevices.setValueIndex(0);
1813         mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[0]);
1814     }
1815
1816     private void writeOverlayDisplayDevicesOptions(Object newValue) {
1817         Settings.Global.putString(getActivity().getContentResolver(),
1818                 Settings.Global.OVERLAY_DISPLAY_DEVICES, (String) newValue);
1819         updateOverlayDisplayDevicesOptions();
1820     }
1821
1822     private void updateAppProcessLimitOptions() {
1823         try {
1824             int limit = ActivityManager.getService().getProcessLimit();
1825             CharSequence[] values = mAppProcessLimit.getEntryValues();
1826             for (int i = 0; i < values.length; i++) {
1827                 int val = Integer.parseInt(values[i].toString());
1828                 if (val >= limit) {
1829                     if (i != 0) {
1830                         mHaveDebugSettings = true;
1831                     }
1832                     mAppProcessLimit.setValueIndex(i);
1833                     mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]);
1834                     return;
1835                 }
1836             }
1837             mAppProcessLimit.setValueIndex(0);
1838             mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]);
1839         } catch (RemoteException e) {
1840         }
1841     }
1842
1843     private void writeAppProcessLimitOptions(Object newValue) {
1844         try {
1845             int limit = newValue != null ? Integer.parseInt(newValue.toString()) : -1;
1846             ActivityManager.getService().setProcessLimit(limit);
1847             updateAppProcessLimitOptions();
1848         } catch (RemoteException e) {
1849         }
1850     }
1851
1852     private void writeShowAllANRsOptions() {
1853         Settings.Secure.putInt(getActivity().getContentResolver(),
1854                 Settings.Secure.ANR_SHOW_BACKGROUND,
1855                 mShowAllANRs.isChecked() ? 1 : 0);
1856     }
1857
1858     private void updateShowAllANRsOptions() {
1859         updateSwitchPreference(mShowAllANRs, Settings.Secure.getInt(
1860                 getActivity().getContentResolver(), Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0);
1861     }
1862
1863     private void confirmEnableOemUnlock() {
1864         DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
1865             @Override
1866             public void onClick(DialogInterface dialog, int which) {
1867                 if (which == DialogInterface.BUTTON_POSITIVE) {
1868                     Utils.setOemUnlockEnabled(getActivity(), true);
1869                 }
1870             }
1871         };
1872
1873         DialogInterface.OnDismissListener onDismissListener =
1874                 new DialogInterface.OnDismissListener() {
1875                     @Override
1876                     public void onDismiss(DialogInterface dialog) {
1877                         if (getActivity() == null) {
1878                             return;
1879                         }
1880                         updateAllOptions();
1881                     }
1882                 };
1883
1884         new AlertDialog.Builder(getActivity())
1885                 .setTitle(R.string.confirm_enable_oem_unlock_title)
1886                 .setMessage(R.string.confirm_enable_oem_unlock_text)
1887                 .setPositiveButton(R.string.enable_text, onClickListener)
1888                 .setNegativeButton(android.R.string.cancel, null)
1889                 .setOnDismissListener(onDismissListener)
1890                 .create()
1891                 .show();
1892     }
1893
1894     @Override
1895     public void onSwitchChanged(Switch switchView, boolean isChecked) {
1896         if (switchView != mSwitchBar.getSwitch()) {
1897             return;
1898         }
1899         if (isChecked != mLastEnabledState) {
1900             if (isChecked) {
1901                 mDialogClicked = false;
1902                 if (mEnableDialog != null) dismissDialogs();
1903                 mEnableDialog = new AlertDialog.Builder(getActivity()).setMessage(
1904                         getActivity().getResources().getString(
1905                                 R.string.dev_settings_warning_message))
1906                         .setTitle(R.string.dev_settings_warning_title)
1907                         .setPositiveButton(android.R.string.yes, this)
1908                         .setNegativeButton(android.R.string.no, this)
1909                         .show();
1910                 mEnableDialog.setOnDismissListener(this);
1911             } else {
1912                 resetDangerousOptions();
1913                 Settings.Global.putInt(getActivity().getContentResolver(),
1914                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);
1915                 mLastEnabledState = isChecked;
1916                 setPrefsEnabledState(mLastEnabledState);
1917             }
1918         }
1919     }
1920
1921     @Override
1922     public void onActivityResult(int requestCode, int resultCode, Intent data) {
1923         if (requestCode == RESULT_DEBUG_APP) {
1924             if (resultCode == Activity.RESULT_OK) {
1925                 mDebugApp = data.getAction();
1926                 writeDebuggerOptions();
1927                 updateDebuggerOptions();
1928             }
1929         } else if (requestCode == RESULT_MOCK_LOCATION_APP) {
1930             if (resultCode == Activity.RESULT_OK) {
1931                 mMockLocationApp = data.getAction();
1932                 writeMockLocation();
1933                 updateMockLocation();
1934             }
1935         } else if (requestCode == REQUEST_CODE_ENABLE_OEM_UNLOCK) {
1936             if (resultCode == Activity.RESULT_OK) {
1937                 if (mEnableOemUnlock.isChecked()) {
1938                     confirmEnableOemUnlock();
1939                 } else {
1940                     Utils.setOemUnlockEnabled(getActivity(), false);
1941                 }
1942             }
1943         } else {
1944             super.onActivityResult(requestCode, resultCode, data);
1945         }
1946     }
1947
1948     @Override
1949     public boolean onPreferenceTreeClick(Preference preference) {
1950         if (Utils.isMonkeyRunning()) {
1951             return false;
1952         }
1953
1954         if (preference == mEnableAdb) {
1955             if (mEnableAdb.isChecked()) {
1956                 mDialogClicked = false;
1957                 if (mAdbDialog != null) dismissDialogs();
1958                 mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage(
1959                         getActivity().getResources().getString(R.string.adb_warning_message))
1960                         .setTitle(R.string.adb_warning_title)
1961                         .setPositiveButton(android.R.string.yes, this)
1962                         .setNegativeButton(android.R.string.no, this)
1963                         .show();
1964                 mAdbDialog.setOnDismissListener(this);
1965             } else {
1966                 Settings.Global.putInt(getActivity().getContentResolver(),
1967                         Settings.Global.ADB_ENABLED, 0);
1968                 mVerifyAppsOverUsb.setEnabled(false);
1969                 mVerifyAppsOverUsb.setChecked(false);
1970                 updateBugreportOptions();
1971             }
1972         } else if (preference == mClearAdbKeys) {
1973             if (mAdbKeysDialog != null) dismissDialogs();
1974             mAdbKeysDialog = new AlertDialog.Builder(getActivity())
1975                     .setMessage(R.string.adb_keys_warning_message)
1976                     .setPositiveButton(android.R.string.ok, this)
1977                     .setNegativeButton(android.R.string.cancel, null)
1978                     .show();
1979         } else if (preference == mEnableTerminal) {
1980             final PackageManager pm = getActivity().getPackageManager();
1981             pm.setApplicationEnabledSetting(TERMINAL_APP_PACKAGE,
1982                     mEnableTerminal.isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1983                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
1984         } else if (preference == mBugreportInPower) {
1985             Settings.Secure.putInt(getActivity().getContentResolver(),
1986                     Settings.Global.BUGREPORT_IN_POWER_MENU,
1987                     mBugreportInPower.isChecked() ? 1 : 0);
1988             setBugreportStorageProviderStatus();
1989         } else if (preference == mKeepScreenOn) {
1990             Settings.Global.putInt(getActivity().getContentResolver(),
1991                     Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
1992                     mKeepScreenOn.isChecked() ?
1993                             (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB
1994                                     | BatteryManager.BATTERY_PLUGGED_WIRELESS) : 0);
1995         } else if (preference == mBtHciSnoopLog) {
1996             writeBtHciSnoopLogOptions();
1997         } else if (preference == mEnableOemUnlock && mEnableOemUnlock.isEnabled()) {
1998             if (mEnableOemUnlock.isChecked()) {
1999                 if (!showKeyguardConfirmation(getResources(), REQUEST_CODE_ENABLE_OEM_UNLOCK)) {
2000                     confirmEnableOemUnlock();
2001                 }
2002             } else {
2003                 Utils.setOemUnlockEnabled(getActivity(), false);
2004             }
2005         } else if (preference == mMockLocationAppPref) {
2006             Intent intent = new Intent(getActivity(), AppPicker.class);
2007             intent.putExtra(AppPicker.EXTRA_REQUESTIING_PERMISSION,
2008                     Manifest.permission.ACCESS_MOCK_LOCATION);
2009             startActivityForResult(intent, RESULT_MOCK_LOCATION_APP);
2010         } else if (preference == mDebugViewAttributes) {
2011             Settings.Global.putInt(getActivity().getContentResolver(),
2012                     Settings.Global.DEBUG_VIEW_ATTRIBUTES,
2013                     mDebugViewAttributes.isChecked() ? 1 : 0);
2014         } else if (preference == mForceAllowOnExternal) {
2015             Settings.Global.putInt(getActivity().getContentResolver(),
2016                     Settings.Global.FORCE_ALLOW_ON_EXTERNAL,
2017                     mForceAllowOnExternal.isChecked() ? 1 : 0);
2018         } else if (preference == mDebugAppPref) {
2019             Intent intent = new Intent(getActivity(), AppPicker.class);
2020             intent.putExtra(AppPicker.EXTRA_DEBUGGABLE, true);
2021             startActivityForResult(intent, RESULT_DEBUG_APP);
2022         } else if (preference == mWaitForDebugger) {
2023             writeDebuggerOptions();
2024         } else if (preference == mVerifyAppsOverUsb) {
2025             writeVerifyAppsOverUsbOptions();
2026         } else if (preference == mOtaDisableAutomaticUpdate) {
2027             writeOtaDisableAutomaticUpdateOptions();
2028         } else if (preference == mStrictMode) {
2029             writeStrictModeVisualOptions();
2030         } else if (preference == mPointerLocation) {
2031             writePointerLocationOptions();
2032         } else if (preference == mShowTouches) {
2033             writeShowTouchesOptions();
2034         } else if (preference == mShowScreenUpdates) {
2035             writeShowUpdatesOption();
2036         } else if (preference == mDisableOverlays) {
2037             writeDisableOverlaysOption();
2038         } else if (preference == mImmediatelyDestroyActivities) {
2039             writeImmediatelyDestroyActivitiesOptions();
2040         } else if (preference == mShowAllANRs) {
2041             writeShowAllANRsOptions();
2042         } else if (preference == mForceHardwareUi) {
2043             writeHardwareUiOptions();
2044         } else if (preference == mForceMsaa) {
2045             writeMsaaOptions();
2046         } else if (preference == mShowHwScreenUpdates) {
2047             writeShowHwScreenUpdatesOptions();
2048         } else if (preference == mShowHwLayersUpdates) {
2049             writeShowHwLayersUpdatesOptions();
2050         } else if (preference == mDebugLayout) {
2051             writeDebugLayoutOptions();
2052         } else if (preference == mForceRtlLayout) {
2053             writeForceRtlOptions();
2054         } else if (preference == mWifiDisplayCertification) {
2055             writeWifiDisplayCertificationOptions();
2056         } else if (preference == mWifiVerboseLogging) {
2057             writeWifiVerboseLoggingOptions();
2058         } else if (preference == mWifiAggressiveHandover) {
2059             writeWifiAggressiveHandoverOptions();
2060         } else if (preference == mWifiAllowScansWithTraffic) {
2061             writeWifiAllowScansWithTrafficOptions();
2062         } else if (preference == mMobileDataAlwaysOn) {
2063             writeMobileDataAlwaysOnOptions();
2064         } else if (preference == mColorTemperaturePreference) {
2065             writeColorTemperature();
2066         } else if (preference == mUSBAudio) {
2067             writeUSBAudioOptions();
2068         } else if (preference == mForceResizable) {
2069             writeForceResizableOptions();
2070         } else if (INACTIVE_APPS_KEY.equals(preference.getKey())) {
2071             startInactiveAppsFragment();
2072         } else if (BACKGROUND_CHECK_KEY.equals(preference.getKey())) {
2073             startBackgroundCheckFragment();
2074         } else if (preference == mBluetoothDisableAbsVolume) {
2075             writeBluetoothDisableAbsVolumeOptions();
2076         } else if (preference == mWebViewMultiprocess) {
2077             writeWebViewMultiprocessOptions();
2078         } else if (SHORTCUT_MANAGER_RESET_KEY.equals(preference.getKey())) {
2079             resetShortcutManagerThrottling();
2080         } else {
2081             return super.onPreferenceTreeClick(preference);
2082         }
2083
2084         return false;
2085     }
2086
2087     private void startInactiveAppsFragment() {
2088         ((SettingsActivity) getActivity()).startPreferencePanel(
2089                 InactiveApps.class.getName(),
2090                 null, R.string.inactive_apps_title, null, null, 0);
2091     }
2092
2093     private void startBackgroundCheckFragment() {
2094         ((SettingsActivity) getActivity()).startPreferencePanel(
2095                 BackgroundCheckSummary.class.getName(),
2096                 null, R.string.background_check_title, null, null, 0);
2097     }
2098
2099     private boolean showKeyguardConfirmation(Resources resources, int requestCode) {
2100         return new ChooseLockSettingsHelper(getActivity(), this).launchConfirmationActivity(
2101                 requestCode, resources.getString(R.string.oem_unlock_enable));
2102     }
2103
2104     @Override
2105     public boolean onPreferenceChange(Preference preference, Object newValue) {
2106         if (HDCP_CHECKING_KEY.equals(preference.getKey())) {
2107             SystemProperties.set(HDCP_CHECKING_PROPERTY, newValue.toString());
2108             updateHdcpValues();
2109             pokeSystemProperties();
2110             return true;
2111         } else if (preference == mWebViewProvider) {
2112             if (newValue == null) {
2113                 Log.e(TAG, "Tried to set a null WebView provider");
2114                 return false;
2115             }
2116             if (writeWebViewProviderOptions(newValue)) {
2117                 return true;
2118             } else {
2119                 // The user chose a package that became invalid since the list was last updated,
2120                 // show a Toast to explain the situation.
2121                 Toast toast = Toast.makeText(getActivity(),
2122                         R.string.select_webview_provider_toast_text, Toast.LENGTH_SHORT);
2123                 toast.show();
2124             }
2125             return false;
2126         } else if (preference == mLogdSize) {
2127             writeLogdSizeOption(newValue);
2128             return true;
2129         } else if (preference == mLogpersist) {
2130             writeLogpersistOption(newValue, false);
2131             return true;
2132         } else if (preference == mUsbConfiguration) {
2133             writeUsbConfigurationOption(newValue);
2134             return true;
2135         } else if (preference == mWindowAnimationScale) {
2136             writeAnimationScaleOption(0, mWindowAnimationScale, newValue);
2137             return true;
2138         } else if (preference == mTransitionAnimationScale) {
2139             writeAnimationScaleOption(1, mTransitionAnimationScale, newValue);
2140             return true;
2141         } else if (preference == mAnimatorDurationScale) {
2142             writeAnimationScaleOption(2, mAnimatorDurationScale, newValue);
2143             return true;
2144         } else if (preference == mOverlayDisplayDevices) {
2145             writeOverlayDisplayDevicesOptions(newValue);
2146             return true;
2147         } else if (preference == mTrackFrameTime) {
2148             writeTrackFrameTimeOptions(newValue);
2149             return true;
2150         } else if (preference == mDebugHwOverdraw) {
2151             writeDebugHwOverdrawOptions(newValue);
2152             return true;
2153         } else if (preference == mShowNonRectClip) {
2154             writeShowNonRectClipOptions(newValue);
2155             return true;
2156         } else if (preference == mAppProcessLimit) {
2157             writeAppProcessLimitOptions(newValue);
2158             return true;
2159         } else if (preference == mSimulateColorSpace) {
2160             writeSimulateColorSpace(newValue);
2161             return true;
2162         }
2163         return false;
2164     }
2165
2166     private void dismissDialogs() {
2167         if (mAdbDialog != null) {
2168             mAdbDialog.dismiss();
2169             mAdbDialog = null;
2170         }
2171         if (mAdbKeysDialog != null) {
2172             mAdbKeysDialog.dismiss();
2173             mAdbKeysDialog = null;
2174         }
2175         if (mEnableDialog != null) {
2176             mEnableDialog.dismiss();
2177             mEnableDialog = null;
2178         }
2179         if (mLogpersistClearDialog != null) {
2180             mLogpersistClearDialog.dismiss();
2181             mLogpersistClearDialog = null;
2182         }
2183     }
2184
2185     public void onClick(DialogInterface dialog, int which) {
2186         if (dialog == mAdbDialog) {
2187             if (which == DialogInterface.BUTTON_POSITIVE) {
2188                 mDialogClicked = true;
2189                 Settings.Global.putInt(getActivity().getContentResolver(),
2190                         Settings.Global.ADB_ENABLED, 1);
2191                 mVerifyAppsOverUsb.setEnabled(true);
2192                 updateVerifyAppsOverUsbOptions();
2193                 updateBugreportOptions();
2194             } else {
2195                 // Reset the toggle
2196                 mEnableAdb.setChecked(false);
2197             }
2198         } else if (dialog == mAdbKeysDialog) {
2199             if (which == DialogInterface.BUTTON_POSITIVE) {
2200                 try {
2201                     IBinder b = ServiceManager.getService(Context.USB_SERVICE);
2202                     IUsbManager service = IUsbManager.Stub.asInterface(b);
2203                     service.clearUsbDebuggingKeys();
2204                 } catch (RemoteException e) {
2205                     Log.e(TAG, "Unable to clear adb keys", e);
2206                 }
2207             }
2208         } else if (dialog == mEnableDialog) {
2209             if (which == DialogInterface.BUTTON_POSITIVE) {
2210                 mDialogClicked = true;
2211                 Settings.Global.putInt(getActivity().getContentResolver(),
2212                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
2213                 mLastEnabledState = true;
2214                 setPrefsEnabledState(mLastEnabledState);
2215             } else {
2216                 // Reset the toggle
2217                 mSwitchBar.setChecked(false);
2218             }
2219         } else if (dialog == mLogpersistClearDialog) {
2220             if (which == DialogInterface.BUTTON_POSITIVE) {
2221                 setLogpersistOff(true);
2222             } else {
2223                 updateLogpersistValues();
2224             }
2225         }
2226     }
2227
2228     public void onDismiss(DialogInterface dialog) {
2229         // Assuming that onClick gets called first
2230         if (dialog == mAdbDialog) {
2231             if (!mDialogClicked) {
2232                 mEnableAdb.setChecked(false);
2233             }
2234             mAdbDialog = null;
2235         } else if (dialog == mEnableDialog) {
2236             if (!mDialogClicked) {
2237                 mSwitchBar.setChecked(false);
2238             }
2239             mEnableDialog = null;
2240         } else if (dialog == mLogpersistClearDialog) {
2241             mLogpersistClearDialog = null;
2242         }
2243     }
2244
2245     @Override
2246     public void onDestroy() {
2247         dismissDialogs();
2248         super.onDestroy();
2249     }
2250
2251     void pokeSystemProperties() {
2252         if (!mDontPokeProperties) {
2253             //noinspection unchecked
2254             (new SystemPropPoker()).execute();
2255         }
2256     }
2257
2258     private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
2259         @Override
2260         public void onReceive(Context context, Intent intent) {
2261             updateUsbConfigurationValues();
2262         }
2263     };
2264
2265     public static class SystemPropPoker extends AsyncTask<Void, Void, Void> {
2266         @Override
2267         protected Void doInBackground(Void... params) {
2268             String[] services = ServiceManager.listServices();
2269             for (String service : services) {
2270                 IBinder obj = ServiceManager.checkService(service);
2271                 if (obj != null) {
2272                     Parcel data = Parcel.obtain();
2273                     try {
2274                         obj.transact(IBinder.SYSPROPS_TRANSACTION, data, null, 0);
2275                     } catch (RemoteException e) {
2276                     } catch (Exception e) {
2277                         Log.i(TAG, "Someone wrote a bad service '" + service
2278                                 + "' that doesn't like to be poked: " + e);
2279                     }
2280                     data.recycle();
2281                 }
2282             }
2283             return null;
2284         }
2285     }
2286
2287     private static boolean isPackageInstalled(Context context, String packageName) {
2288         try {
2289             return context.getPackageManager().getPackageInfo(packageName, 0) != null;
2290         } catch (NameNotFoundException e) {
2291             return false;
2292         }
2293     }
2294
2295
2296     /**
2297      * For Search.
2298      */
2299     public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
2300             new BaseSearchIndexProvider() {
2301
2302                 private boolean isShowingDeveloperOptions(Context context) {
2303                     return context.getSharedPreferences(DevelopmentSettings.PREF_FILE,
2304                             Context.MODE_PRIVATE).getBoolean(
2305                             DevelopmentSettings.PREF_SHOW,
2306                             android.os.Build.TYPE.equals("eng"));
2307                 }
2308
2309                 @Override
2310                 public List<SearchIndexableResource> getXmlResourcesToIndex(
2311                         Context context, boolean enabled) {
2312
2313                     if (!isShowingDeveloperOptions(context)) {
2314                         return null;
2315                     }
2316
2317                     final SearchIndexableResource sir = new SearchIndexableResource(context);
2318                     sir.xmlResId = R.xml.development_prefs;
2319                     return Arrays.asList(sir);
2320                 }
2321
2322                 @Override
2323                 public List<String> getNonIndexableKeys(Context context) {
2324                     if (!isShowingDeveloperOptions(context)) {
2325                         return null;
2326                     }
2327
2328                     final List<String> keys = new ArrayList<String>();
2329                     if (!showEnableOemUnlockPreference()) {
2330                         keys.add(ENABLE_OEM_UNLOCK);
2331                     }
2332                     return keys;
2333                 }
2334             };
2335
2336     private void resetShortcutManagerThrottling() {
2337         final IShortcutService service = IShortcutService.Stub.asInterface(
2338                 ServiceManager.getService(Context.SHORTCUT_SERVICE));
2339         if (service != null) {
2340             try {
2341                 service.resetThrottling();
2342                 Toast.makeText(getActivity(), R.string.reset_shortcut_manager_throttling_complete,
2343                         Toast.LENGTH_SHORT).show();
2344             } catch (RemoteException e) {
2345                 Log.e(TAG, "Failed to reset rate limiting", e);
2346             }
2347         }
2348     }
2349
2350     private void updateOemUnlockSettingDescription() {
2351         if (mEnableOemUnlock != null) {
2352             int oemUnlockSummary = R.string.oem_unlock_enable_summary;
2353             if (isBootloaderUnlocked()) {
2354                 oemUnlockSummary = R.string.oem_unlock_enable_disabled_summary_bootloader_unlocked;
2355             } else if (isSimLockedDevice()) {
2356                 oemUnlockSummary = R.string.oem_unlock_enable_disabled_summary_sim_locked_device;
2357             } else if (!isOemUnlockAllowed()) {
2358                 // If the device isn't SIM-locked but OEM unlock is disabled by the system via the
2359                 // user restriction, this means either some other carrier restriction is in place or
2360                 // the device hasn't been able to confirm which restrictions (SIM-lock or otherwise)
2361                 // apply.
2362                 oemUnlockSummary =
2363                         R.string.oem_unlock_enable_disabled_summary_connectivity_or_locked;
2364             }
2365             mEnableOemUnlock.setSummary(getString(oemUnlockSummary));
2366         }
2367     }
2368
2369     /** Returns {@code true} if the device is SIM-locked. Otherwise, returns {@code false}. */
2370     private boolean isSimLockedDevice() {
2371         int phoneCount = mTelephonyManager.getPhoneCount();
2372         for (int i = 0; i < phoneCount; i++) {
2373             if (mTelephonyManager.getAllowedCarriers(i).size() > 0) {
2374                 return true;
2375             }
2376         }
2377         return false;
2378     }
2379
2380     /**
2381      * Returns {@code true} if the bootloader has been unlocked. Otherwise, returns {code false}.
2382      */
2383     private boolean isBootloaderUnlocked() {
2384         int flashLockState = PersistentDataBlockManager.FLASH_LOCK_UNKNOWN;
2385         if (mOemUnlockManager != null) {
2386             flashLockState = mOemUnlockManager.getFlashLockState();
2387         }
2388
2389         return flashLockState == PersistentDataBlockManager.FLASH_LOCK_UNLOCKED;
2390     }
2391
2392     /**
2393      * Returns {@code true} if OEM unlock is disallowed by user restriction
2394      * {@link UserManager#DISALLOW_FACTORY_RESET} or {@link UserManager#DISALLOW_OEM_UNLOCK}.
2395      * Otherwise, returns {@code false}.
2396      */
2397     private boolean isOemUnlockAllowed() {
2398         UserHandle userHandle = UserHandle.of(UserHandle.myUserId());
2399         return !(mUm.hasBaseUserRestriction(UserManager.DISALLOW_OEM_UNLOCK, userHandle)
2400                 || mUm.hasBaseUserRestriction(UserManager.DISALLOW_FACTORY_RESET, userHandle));
2401     }
2402 }