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