OSDN Git Service

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