OSDN Git Service

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