OSDN Git Service

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