OSDN Git Service

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