OSDN Git Service

3c85024e5a2ddb99fe9b485efac422e09b155bc2
[android-x86/packages-apps-Settings.git] / src / com / android / settings / DisplaySettings.java
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  * Copyright (C) 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 import com.android.internal.logging.MetricsLogger;
20
21 import android.app.AlertDialog;
22 import android.content.DialogInterface;
23 import android.content.SharedPreferences;
24 import android.preference.CheckBoxPreference;
25
26 import android.os.UserHandle;
27 import android.view.Display;
28 import android.view.IWindowManager;
29 import android.view.WindowManager;
30 import android.view.WindowManagerGlobal;
31 import android.view.WindowManagerImpl;
32 import android.widget.Toast;
33 import com.android.internal.view.RotationPolicy;
34 import com.android.settings.DropDownPreference.Callback;
35 import com.android.settings.search.BaseSearchIndexProvider;
36 import com.android.settings.search.Indexable;
37
38 import static android.provider.Settings.Secure.CAMERA_GESTURE_DISABLED;
39 import static android.provider.Settings.Secure.DOUBLE_TAP_TO_WAKE;
40 import static android.provider.Settings.Secure.DOZE_ENABLED;
41 import static android.provider.Settings.Secure.WAKE_GESTURE_ENABLED;
42 import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
43 import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
44 import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
45 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
46
47 import android.app.Activity;
48 import android.app.ActivityManagerNative;
49 import android.app.Dialog;
50 import android.app.IActivityManager;
51 import android.app.ProgressDialog;
52 import android.app.UiModeManager;
53 import android.app.admin.DevicePolicyManager;
54 import android.content.ContentResolver;
55 import android.content.Context;
56 import android.content.res.Configuration;
57 import android.content.res.Resources;
58 import android.hardware.Sensor;
59 import android.hardware.SensorManager;
60 import android.os.AsyncTask;
61 import android.os.Build;
62 import android.database.ContentObserver;
63 import android.os.Bundle;
64 import android.os.Handler;
65 import android.os.RemoteException;
66 import android.os.ServiceManager;
67 import android.os.SystemProperties;
68 import android.preference.ListPreference;
69 import android.preference.Preference;
70 import android.preference.PreferenceManager;
71 import android.preference.Preference.OnPreferenceClickListener;
72 import android.preference.PreferenceCategory;
73 import android.preference.PreferenceManager;
74 import android.preference.PreferenceScreen;
75 import android.preference.SwitchPreference;
76 import android.provider.SearchIndexableResource;
77 import android.provider.Settings;
78 import android.text.TextUtils;
79 import android.util.DisplayMetrics;
80 import android.util.Log;
81
82 import java.util.ArrayList;
83 import java.util.List;
84 import com.android.settings.Utils;
85 import com.android.settings.cyanogenmod.DisplayRotation;
86
87 import cyanogenmod.hardware.CMHardwareManager;
88 import cyanogenmod.hardware.LiveDisplayManager;
89 import cyanogenmod.providers.CMSettings;
90
91 public class DisplaySettings extends SettingsPreferenceFragment implements
92         Preference.OnPreferenceChangeListener, OnPreferenceClickListener, Indexable {
93     private static final String TAG = "DisplaySettings";
94
95     /** If there is no setting in the provider, use this. */
96     private static final int FALLBACK_SCREEN_TIMEOUT_VALUE = 30000;
97
98     private static final String KEY_CATEGORY_LIGHTS = "lights";
99     private static final String KEY_CATEGORY_DISPLAY = "display";
100     private static final String KEY_CATEGORY_INTERFACE = "interface";
101     private static final String KEY_SCREEN_TIMEOUT = "screen_timeout";
102     private static final String KEY_LCD_DENSITY = "lcd_density";
103     private static final String KEY_FONT_SIZE = "font_size";
104     private static final String KEY_SCREEN_SAVER = "screensaver";
105     private static final String KEY_LIFT_TO_WAKE = "lift_to_wake";
106     private static final String KEY_DOZE = "doze";
107     private static final String KEY_TAP_TO_WAKE = "tap_to_wake";
108     private static final String KEY_AUTO_BRIGHTNESS = "auto_brightness";
109     private static final String KEY_AUTO_ROTATE = "auto_rotate";
110     private static final String KEY_NIGHT_MODE = "night_mode";
111     private static final String KEY_CAMERA_GESTURE = "camera_gesture";
112     private static final String KEY_PROXIMITY_WAKE = "proximity_on_wake";
113     private static final String KEY_DISPLAY_ROTATION = "display_rotation";
114     private static final String KEY_WAKE_WHEN_PLUGGED_OR_UNPLUGGED = "wake_when_plugged_or_unplugged";
115     private static final String KEY_NOTIFICATION_LIGHT = "notification_light";
116     private static final String KEY_BATTERY_LIGHT = "battery_light";
117     private static final String KEY_LIVEDISPLAY = "live_display";
118     private static final String KEY_HIGH_TOUCH_SENSITIVITY = "high_touch_sensitivity";
119
120     private static final int DLG_GLOBAL_CHANGE_WARNING = 1;
121
122     private ListPreference mLcdDensityPreference;
123     private FontDialogPreference mFontSizePref;
124     private PreferenceScreen mDisplayRotationPreference;
125     private PreferenceScreen mLiveDisplayPreference;
126
127     private final Configuration mCurConfig = new Configuration();
128
129     private ListPreference mScreenTimeoutPreference;
130     private ListPreference mNightModePreference;
131     private Preference mScreenSaverPreference;
132     private SwitchPreference mAccelerometer;
133     private SwitchPreference mLiftToWakePreference;
134     private SwitchPreference mDozePreference;
135     private SwitchPreference mTapToWakePreference;
136     private SwitchPreference mHighTouchSensitivity;
137     private SwitchPreference mProximityCheckOnWakePreference;
138     private SwitchPreference mAutoBrightnessPreference;
139     private SwitchPreference mWakeWhenPluggedOrUnplugged;
140
141     private CMHardwareManager mHardware;
142
143     private ContentObserver mAccelerometerRotationObserver =
144             new ContentObserver(new Handler()) {
145         @Override
146         public void onChange(boolean selfChange) {
147             updateDisplayRotationPreferenceDescription();
148             updateAccelerometerRotationSwitch();
149         }
150     };
151
152     private final RotationPolicy.RotationPolicyListener mRotationPolicyListener =
153             new RotationPolicy.RotationPolicyListener() {
154         @Override
155         public void onChange() {
156             updateDisplayRotationPreferenceDescription();
157         }
158     };
159     private SwitchPreference mCameraGesturePreference;
160
161     @Override
162     protected int getMetricsCategory() {
163         return MetricsLogger.DISPLAY;
164     }
165
166     @Override
167     public void onCreate(Bundle savedInstanceState) {
168         super.onCreate(savedInstanceState);
169         final Activity activity = getActivity();
170         final ContentResolver resolver = activity.getContentResolver();
171         addPreferencesFromResource(R.xml.display);
172
173         mHardware = CMHardwareManager.getInstance(activity);
174
175         PreferenceCategory displayPrefs = (PreferenceCategory)
176                 findPreference(KEY_CATEGORY_DISPLAY);
177         PreferenceCategory interfacePrefs = (PreferenceCategory)
178                 findPreference(KEY_CATEGORY_INTERFACE);
179         mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION);
180         mAccelerometer = (SwitchPreference) findPreference(DisplayRotation.KEY_ACCELEROMETER);
181         if (mAccelerometer != null) {
182             mAccelerometer.setPersistent(false);
183         }
184
185         mLiveDisplayPreference = (PreferenceScreen) findPreference(KEY_LIVEDISPLAY);
186         if (!LiveDisplayManager.getInstance(getActivity()).getConfig().isAvailable()) {
187             displayPrefs.removePreference(mLiveDisplayPreference);
188         }
189
190         mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER);
191         if (mScreenSaverPreference != null
192                 && getResources().getBoolean(
193                         com.android.internal.R.bool.config_dreamsSupported) == false) {
194             interfacePrefs.removePreference(mScreenSaverPreference);
195         }
196
197         mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT);
198         final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT,
199                 FALLBACK_SCREEN_TIMEOUT_VALUE);
200         mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout));
201         mScreenTimeoutPreference.setOnPreferenceChangeListener(this);
202         disableUnusableTimeouts(mScreenTimeoutPreference);
203         updateTimeoutPreferenceDescription(currentTimeout);
204         updateDisplayRotationPreferenceDescription();
205
206         mLcdDensityPreference = (ListPreference) findPreference(KEY_LCD_DENSITY);
207         if (mLcdDensityPreference != null) {
208             if (UserHandle.myUserId() != UserHandle.USER_OWNER) {
209                 interfacePrefs.removePreference(mLcdDensityPreference);
210             } else {
211                 int currentDensity = getCurrentDensity();
212                 if (currentDensity < 10 || currentDensity >= 1000) {
213                     // Unsupported value, force 160 DPI
214                     currentDensity = 160;
215                 }
216
217                 int factor = currentDensity >= 480 ? 40 : 20;
218                 int minimumDensity = currentDensity - 5 * factor;
219                 int currentIndex = -1;
220                 String[] densityEntries = new String[9];
221                 String[] densityValues = new String[9];
222                 if (minimumDensity < 60) {
223                     minimumDensity = 60;
224                 }
225                 for (int idx = 0; idx < 11; ++idx) {
226                     int val = minimumDensity + factor * idx;
227
228                     densityEntries[idx] = getString(R.string.lcd_density_value_format, val);
229                     densityValues[idx] = Integer.toString(val);
230                     if (currentDensity == val) {
231                         currentIndex = idx;
232                     }
233                 }
234                 mLcdDensityPreference.setEntries(densityEntries);
235                 mLcdDensityPreference.setEntryValues(densityValues);
236                 if (currentIndex != -1) {
237                     mLcdDensityPreference.setValueIndex(currentIndex);
238                 }
239                 mLcdDensityPreference.setOnPreferenceChangeListener(this);
240                 updateLcdDensityPreferenceDescription(currentDensity);
241             }
242         }
243
244         mFontSizePref = (FontDialogPreference) findPreference(KEY_FONT_SIZE);
245         mFontSizePref.setOnPreferenceChangeListener(this);
246         mFontSizePref.setOnPreferenceClickListener(this);
247
248         mAutoBrightnessPreference = (SwitchPreference) findPreference(KEY_AUTO_BRIGHTNESS);
249         if (mAutoBrightnessPreference != null && isAutomaticBrightnessAvailable(getResources())) {
250             mAutoBrightnessPreference.setOnPreferenceChangeListener(this);
251         } else {
252             if (displayPrefs != null && mAutoBrightnessPreference != null) {
253                 displayPrefs.removePreference(mAutoBrightnessPreference);
254                 mAutoBrightnessPreference = null;
255             }
256         }
257
258         mLiftToWakePreference = (SwitchPreference) findPreference(KEY_LIFT_TO_WAKE);
259         if (mLiftToWakePreference != null && isLiftToWakeAvailable(activity)) {
260             mLiftToWakePreference.setOnPreferenceChangeListener(this);
261         } else {
262             if (displayPrefs != null && mLiftToWakePreference != null) {
263                 displayPrefs.removePreference(mLiftToWakePreference);
264                 mLiftToWakePreference = null;
265             }
266         }
267
268         mDozePreference = (SwitchPreference) findPreference(KEY_DOZE);
269         if (mDozePreference != null && Utils.isDozeAvailable(activity)) {
270             mDozePreference.setOnPreferenceChangeListener(this);
271         } else {
272             if (displayPrefs != null && mDozePreference != null) {
273                 displayPrefs.removePreference(mDozePreference);
274             }
275         }
276
277         mCameraGesturePreference = (SwitchPreference) findPreference(KEY_CAMERA_GESTURE);
278         if (mCameraGesturePreference != null && isCameraGestureAvailable(getResources())) {
279             mCameraGesturePreference.setOnPreferenceChangeListener(this);
280         } else {
281             if (displayPrefs != null && mCameraGesturePreference != null) {
282                 displayPrefs.removePreference(mCameraGesturePreference);
283             }
284         }
285
286         mNightModePreference = (ListPreference) findPreference(KEY_NIGHT_MODE);
287         if (mNightModePreference != null) {
288             final UiModeManager uiManager = (UiModeManager) getSystemService(
289                     Context.UI_MODE_SERVICE);
290             final int currentNightMode = uiManager.getNightMode();
291             mNightModePreference.setValue(String.valueOf(currentNightMode));
292             mNightModePreference.setOnPreferenceChangeListener(this);
293         }
294
295         mTapToWakePreference = (SwitchPreference) findPreference(KEY_TAP_TO_WAKE);
296         if (mTapToWakePreference != null && isTapToWakeAvailable(getResources())) {
297             mTapToWakePreference.setOnPreferenceChangeListener(this);
298         } else {
299             if (displayPrefs != null && mTapToWakePreference != null) {
300                 displayPrefs.removePreference(mTapToWakePreference);
301             }
302         }
303
304         mHighTouchSensitivity = (SwitchPreference) findPreference(KEY_HIGH_TOUCH_SENSITIVITY);
305         if (!mHardware.isSupported(
306                 CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY)) {
307             displayPrefs.removePreference(mHighTouchSensitivity);
308             mHighTouchSensitivity = null;
309         } else {
310             mHighTouchSensitivity.setChecked(
311                     mHardware.get(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY));
312         }
313
314         mProximityCheckOnWakePreference = (SwitchPreference) findPreference(KEY_PROXIMITY_WAKE);
315         boolean proximityCheckOnWake = getResources().getBoolean(
316                 org.cyanogenmod.platform.internal.R.bool.config_proximityCheckOnWake);
317         if (!proximityCheckOnWake) {
318             if (displayPrefs != null && mProximityCheckOnWakePreference != null) {
319                 displayPrefs.removePreference(mProximityCheckOnWakePreference);
320             }
321             CMSettings.System.putInt(getContentResolver(), CMSettings.System.PROXIMITY_ON_WAKE, 0);
322         } else {
323             boolean proximityCheckOnWakeDefault = getResources().getBoolean(
324                     org.cyanogenmod.platform.internal.R.bool.config_proximityCheckOnWakeEnabledByDefault);
325             mProximityCheckOnWakePreference.setChecked(CMSettings.System.getInt(getContentResolver(),
326                     CMSettings.System.PROXIMITY_ON_WAKE,
327                     (proximityCheckOnWakeDefault ? 1 : 0)) == 1);
328         }
329
330         mWakeWhenPluggedOrUnplugged =
331                 (SwitchPreference) findPreference(KEY_WAKE_WHEN_PLUGGED_OR_UNPLUGGED);
332         initPulse((PreferenceCategory) findPreference(KEY_CATEGORY_LIGHTS));
333     }
334
335     private int getCurrentDensity() {
336         IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService(
337                 Context.WINDOW_SERVICE));
338         try {
339             return wm.getBaseDisplayDensity(Display.DEFAULT_DISPLAY);
340         } catch (RemoteException e) {
341             e.printStackTrace();
342         }
343         return DisplayMetrics.DENSITY_DEVICE;
344     }
345
346     private static boolean allowAllRotations(Context context) {
347         return Resources.getSystem().getBoolean(
348                 com.android.internal.R.bool.config_allowAllRotations);
349     }
350
351     private static boolean isLiftToWakeAvailable(Context context) {
352         SensorManager sensors = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
353         return sensors != null && sensors.getDefaultSensor(Sensor.TYPE_WAKE_GESTURE) != null;
354     }
355
356     private static boolean isTapToWakeAvailable(Resources res) {
357         return res.getBoolean(com.android.internal.R.bool.config_supportDoubleTapWake);
358     }
359
360     private static boolean isAutomaticBrightnessAvailable(Resources res) {
361         return res.getBoolean(com.android.internal.R.bool.config_automatic_brightness_available);
362     }
363
364     private void updateAccelerometerRotationSwitch() {
365         if (mAccelerometer != null) {
366             mAccelerometer.setChecked(!RotationPolicy.isRotationLocked(getActivity()));
367         }
368     }
369     private void updateDisplayRotationPreferenceDescription() {
370         if (mDisplayRotationPreference == null) {
371             // The preference was removed, do nothing
372             return;
373         }
374
375         // We have a preference, lets update the summary
376         boolean rotationEnabled = Settings.System.getInt(getContentResolver(),
377                 Settings.System.ACCELEROMETER_ROTATION, 0) != 0;
378
379         if (!rotationEnabled) {
380             mDisplayRotationPreference.setSummary(R.string.display_rotation_disabled);
381             return;
382         }
383
384         StringBuilder summary = new StringBuilder();
385         int mode = Settings.System.getInt(getContentResolver(),
386                 Settings.System.ACCELEROMETER_ROTATION_ANGLES,
387                 DisplayRotation.ROTATION_0_MODE
388                 | DisplayRotation.ROTATION_90_MODE
389                 | DisplayRotation.ROTATION_270_MODE);
390         ArrayList<String> rotationList = new ArrayList<String>();
391         String delim = "";
392
393         if ((mode & DisplayRotation.ROTATION_0_MODE) != 0) {
394             rotationList.add("0");
395         }
396         if ((mode & DisplayRotation.ROTATION_90_MODE) != 0) {
397             rotationList.add("90");
398         }
399         if ((mode & DisplayRotation.ROTATION_180_MODE) != 0) {
400             rotationList.add("180");
401         }
402         if ((mode & DisplayRotation.ROTATION_270_MODE) != 0) {
403             rotationList.add("270");
404         }
405         for (int i = 0; i < rotationList.size(); i++) {
406             summary.append(delim).append(rotationList.get(i));
407             if ((rotationList.size() - i) > 2) {
408                 delim = ", ";
409             } else {
410                 delim = " & ";
411             }
412         }
413         summary.append(" " + getString(R.string.display_rotation_unit));
414         mDisplayRotationPreference.setSummary(summary);
415     }
416
417     private static boolean isCameraGestureAvailable(Resources res) {
418         boolean configSet = res.getInteger(
419                 com.android.internal.R.integer.config_cameraLaunchGestureSensorType) != -1;
420         return configSet &&
421                 !SystemProperties.getBoolean("gesture.disable_camera_launch", false);
422     }
423
424     private void updateTimeoutPreferenceDescription(long currentTimeout) {
425         ListPreference preference = mScreenTimeoutPreference;
426         String summary;
427         if (currentTimeout < 0) {
428             // Unsupported value
429             summary = "";
430         } else {
431             final CharSequence[] entries = preference.getEntries();
432             final CharSequence[] values = preference.getEntryValues();
433             if (entries == null || entries.length == 0) {
434                 summary = "";
435             } else {
436                 int best = 0;
437                 for (int i = 0; i < values.length; i++) {
438                     long timeout = Long.parseLong(values[i].toString());
439                     if (currentTimeout >= timeout) {
440                         best = i;
441                     }
442                 }
443                 summary = preference.getContext().getString(R.string.screen_timeout_summary,
444                         entries[best]);
445             }
446         }
447         preference.setSummary(summary);
448     }
449
450     private void updateLcdDensityPreferenceDescription(int currentDensity) {
451         mLcdDensityPreference.setSummary(getString(R.string.lcd_density_value_format, currentDensity));
452     }
453
454     private void disableUnusableTimeouts(ListPreference screenTimeoutPreference) {
455         final DevicePolicyManager dpm =
456                 (DevicePolicyManager) getActivity().getSystemService(
457                 Context.DEVICE_POLICY_SERVICE);
458         final long maxTimeout = dpm != null ? dpm.getMaximumTimeToLock(null) : 0;
459         if (maxTimeout == 0) {
460             return; // policy not enforced
461         }
462         final CharSequence[] entries = screenTimeoutPreference.getEntries();
463         final CharSequence[] values = screenTimeoutPreference.getEntryValues();
464         ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
465         ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
466         for (int i = 0; i < values.length; i++) {
467             long timeout = Long.parseLong(values[i].toString());
468             if (timeout <= maxTimeout) {
469                 revisedEntries.add(entries[i]);
470                 revisedValues.add(values[i]);
471             }
472         }
473         if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
474             final int userPreference = Integer.parseInt(screenTimeoutPreference.getValue());
475             screenTimeoutPreference.setEntries(
476                     revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
477             screenTimeoutPreference.setEntryValues(
478                     revisedValues.toArray(new CharSequence[revisedValues.size()]));
479             if (userPreference <= maxTimeout) {
480                 screenTimeoutPreference.setValue(String.valueOf(userPreference));
481             } else if (revisedValues.size() > 0
482                     && Long.parseLong(revisedValues.get(revisedValues.size() - 1).toString())
483                     == maxTimeout) {
484                 // If the last one happens to be the same as the max timeout, select that
485                 screenTimeoutPreference.setValue(String.valueOf(maxTimeout));
486             } else {
487                 // There will be no highlighted selection since nothing in the list matches
488                 // maxTimeout. The user can still select anything less than maxTimeout.
489                 // TODO: maybe append maxTimeout to the list and mark selected.
490             }
491         }
492         screenTimeoutPreference.setEnabled(revisedEntries.size() > 0);
493     }
494
495     @Override
496     public void onResume() {
497         super.onResume();
498         updateDisplayRotationPreferenceDescription();
499
500         RotationPolicy.registerRotationPolicyListener(getActivity(),
501                 mRotationPolicyListener);
502
503         final ContentResolver resolver = getContentResolver();
504
505         // Display rotation observer
506         resolver.registerContentObserver(
507                 Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), true,
508                 mAccelerometerRotationObserver);
509
510         // Default value for wake-on-plug behavior from config.xml
511         boolean wakeUpWhenPluggedOrUnpluggedConfig = getResources().getBoolean(
512                 com.android.internal.R.bool.config_unplugTurnsOnScreen);
513
514         if (mWakeWhenPluggedOrUnplugged != null) {
515         mWakeWhenPluggedOrUnplugged.setChecked(CMSettings.Global.getInt(getContentResolver(),
516                 CMSettings.Global.WAKE_WHEN_PLUGGED_OR_UNPLUGGED,
517                 (wakeUpWhenPluggedOrUnpluggedConfig ? 1 : 0)) == 1);
518         }
519
520         updateState();
521         updateAccelerometerRotationSwitch();
522     }
523
524     @Override
525     public void onPause() {
526         super.onPause();
527
528         RotationPolicy.unregisterRotationPolicyListener(getActivity(),
529                 mRotationPolicyListener);
530
531         // Display rotation observer
532         getContentResolver().unregisterContentObserver(mAccelerometerRotationObserver);
533     }
534
535     @Override
536     public Dialog onCreateDialog(int dialogId) {
537         if (dialogId == DLG_GLOBAL_CHANGE_WARNING) {
538             return Utils.buildGlobalChangeWarningDialog(getActivity(),
539                     R.string.global_font_change_title,
540                     new Runnable() {
541                         public void run() {
542                             mFontSizePref.click();
543                         }
544                     });
545         }
546         return null;
547     }
548
549     private void updateState() {
550         readFontSizePreference(mFontSizePref);
551         updateScreenSaverSummary();
552
553         // Update auto brightness if it is available.
554         if (mAutoBrightnessPreference != null) {
555             int brightnessMode = Settings.System.getInt(getContentResolver(),
556                     SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
557             mAutoBrightnessPreference.setChecked(brightnessMode != SCREEN_BRIGHTNESS_MODE_MANUAL);
558         }
559
560         // Update lift-to-wake if it is available.
561         if (mLiftToWakePreference != null) {
562             int value = Settings.Secure.getInt(getContentResolver(), WAKE_GESTURE_ENABLED, 0);
563             mLiftToWakePreference.setChecked(value != 0);
564         }
565
566         // Update doze if it is available.
567         if (mDozePreference != null) {
568             int value = Settings.Secure.getInt(getContentResolver(), DOZE_ENABLED, 1);
569             mDozePreference.setChecked(value != 0);
570         }
571
572         // Update tap to wake if it is available.
573         if (mTapToWakePreference != null) {
574             int value = Settings.Secure.getInt(getContentResolver(), DOUBLE_TAP_TO_WAKE, 0);
575             mTapToWakePreference.setChecked(value != 0);
576         }
577
578         // Update camera gesture #1 if it is available.
579         if (mCameraGesturePreference != null) {
580             int value = Settings.Secure.getInt(getContentResolver(), CAMERA_GESTURE_DISABLED, 0);
581             mCameraGesturePreference.setChecked(value == 0);
582         }
583     }
584
585     private void updateScreenSaverSummary() {
586         if (mScreenSaverPreference != null) {
587             mScreenSaverPreference.setSummary(
588                     DreamSettings.getSummaryTextWithDreamName(getActivity()));
589         }
590     }
591
592     private void writeLcdDensityPreference(final Context context, final int density) {
593         final IActivityManager am = ActivityManagerNative.asInterface(
594                 ServiceManager.checkService("activity"));
595         final IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService(
596                 Context.WINDOW_SERVICE));
597         AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
598             @Override
599             protected void onPreExecute() {
600                 ProgressDialog dialog = new ProgressDialog(context);
601                 dialog.setMessage(getResources().getString(R.string.restarting_ui));
602                 dialog.setCancelable(false);
603                 dialog.setIndeterminate(true);
604                 dialog.show();
605             }
606             @Override
607             protected Void doInBackground(Void... params) {
608                 // Give the user a second to see the dialog
609                 try {
610                     Thread.sleep(1000);
611                 } catch (InterruptedException e) {
612                     // Ignore
613                 }
614
615                 try {
616                     wm.setForcedDisplayDensity(Display.DEFAULT_DISPLAY, density);
617                 } catch (RemoteException e) {
618                     Log.e(TAG, "Failed to set density to " + density, e);
619                 }
620
621                 // Restart the UI
622                 try {
623                     am.restart();
624                 } catch (RemoteException e) {
625                     Log.e(TAG, "Failed to restart");
626                 }
627                 return null;
628             }
629         };
630         task.execute();
631     }
632
633     // === Pulse notification light ===
634
635     private void initPulse(PreferenceCategory parent) {
636         if (!getResources().getBoolean(
637                 com.android.internal.R.bool.config_intrusiveNotificationLed)) {
638             parent.removePreference(parent.findPreference(KEY_NOTIFICATION_LIGHT));
639         }
640         if (!getResources().getBoolean(
641                 com.android.internal.R.bool.config_intrusiveBatteryLed)
642                 || UserHandle.myUserId() != UserHandle.USER_OWNER) {
643             parent.removePreference(parent.findPreference(KEY_BATTERY_LIGHT));
644         }
645         if (parent.getPreferenceCount() == 0) {
646             getPreferenceScreen().removePreference(parent);
647         }
648     }
649     /**
650      * Reads the current font size and sets the value in the summary text
651      */
652     public void readFontSizePreference(Preference pref) {
653         try {
654             mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
655         } catch (RemoteException e) {
656             Log.w(TAG, "Unable to retrieve font size");
657         }
658
659         // report the current size in the summary text
660         final Resources res = getResources();
661         String fontDesc = FontDialogPreference.getFontSizeDescription(res, mCurConfig.fontScale);
662         pref.setSummary(getString(R.string.summary_font_size, fontDesc));
663     }
664
665     public void writeFontSizePreference(Object objValue) {
666         try {
667             mCurConfig.fontScale = Float.parseFloat(objValue.toString());
668             ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
669         } catch (RemoteException e) {
670             Log.w(TAG, "Unable to save font size");
671         }
672     }
673
674     @Override
675     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
676         if (preference == mWakeWhenPluggedOrUnplugged) {
677             CMSettings.Global.putInt(getContentResolver(),
678                     CMSettings.Global.WAKE_WHEN_PLUGGED_OR_UNPLUGGED,
679                     mWakeWhenPluggedOrUnplugged.isChecked() ? 1 : 0);
680             return true;
681         } else if (preference == mAccelerometer) {
682             RotationPolicy.setRotationLockForAccessibility(getActivity(),
683                     !mAccelerometer.isChecked());
684         } else if (preference == mHighTouchSensitivity) {
685             boolean mHighTouchSensitivityEnable = mHighTouchSensitivity.isChecked();
686             CMSettings.System.putInt(getActivity().getContentResolver(),
687                     CMSettings.System.HIGH_TOUCH_SENSITIVITY_ENABLE,
688                     mHighTouchSensitivityEnable ? 1 : 0);
689             return true;
690         }
691
692         return super.onPreferenceTreeClick(preferenceScreen, preference);
693     }
694
695     @Override
696     public boolean onPreferenceChange(Preference preference, Object objValue) {
697         final String key = preference.getKey();
698         if (KEY_SCREEN_TIMEOUT.equals(key)) {
699             try {
700                 int value = Integer.parseInt((String) objValue);
701                 Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, value);
702                 updateTimeoutPreferenceDescription(value);
703             } catch (NumberFormatException e) {
704                 Log.e(TAG, "could not persist screen timeout setting", e);
705             }
706         }
707         if (KEY_LCD_DENSITY.equals(key)) {
708             String newValue = (String) objValue;
709             String oldValue = mLcdDensityPreference.getValue();
710             if (!TextUtils.equals(newValue, oldValue)) {
711                 showLcdConfirmationDialog((String) objValue);
712             }
713             return false;
714         }
715         if (KEY_FONT_SIZE.equals(key)) {
716             writeFontSizePreference(objValue);
717         }
718         if (preference == mAutoBrightnessPreference) {
719             boolean auto = (Boolean) objValue;
720             Settings.System.putInt(getContentResolver(), SCREEN_BRIGHTNESS_MODE,
721                     auto ? SCREEN_BRIGHTNESS_MODE_AUTOMATIC : SCREEN_BRIGHTNESS_MODE_MANUAL);
722         }
723         if (preference == mLiftToWakePreference) {
724             boolean value = (Boolean) objValue;
725             Settings.Secure.putInt(getContentResolver(), WAKE_GESTURE_ENABLED, value ? 1 : 0);
726         }
727         if (preference == mDozePreference) {
728             boolean value = (Boolean) objValue;
729             Settings.Secure.putInt(getContentResolver(), DOZE_ENABLED, value ? 1 : 0);
730         }
731         if (preference == mTapToWakePreference) {
732             boolean value = (Boolean) objValue;
733             Settings.Secure.putInt(getContentResolver(), DOUBLE_TAP_TO_WAKE, value ? 1 : 0);
734         }
735         if (preference == mCameraGesturePreference) {
736             boolean value = (Boolean) objValue;
737             Settings.Secure.putInt(getContentResolver(), CAMERA_GESTURE_DISABLED,
738                     value ? 0 : 1 /* Backwards because setting is for disabling */);
739         }
740         if (preference == mNightModePreference) {
741             try {
742                 final int value = Integer.parseInt((String) objValue);
743                 final UiModeManager uiManager = (UiModeManager) getSystemService(
744                         Context.UI_MODE_SERVICE);
745                 uiManager.setNightMode(value);
746             } catch (NumberFormatException e) {
747                 Log.e(TAG, "could not persist night mode setting", e);
748             }
749         }
750         return true;
751     }
752
753     private void showLcdConfirmationDialog(final String lcdDensity) {
754         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
755         builder.setTitle(R.string.lcd_density);
756         builder.setMessage(R.string.lcd_density_prompt_message);
757         builder.setPositiveButton(R.string.print_restart,
758                 new DialogInterface.OnClickListener() {
759             public void onClick(DialogInterface dialog, int id) {
760                 try {
761                     int value = Integer.parseInt(lcdDensity);
762                     writeLcdDensityPreference(getActivity(), value);
763                     updateLcdDensityPreferenceDescription(value);
764                 } catch (NumberFormatException e) {
765                     Log.e(TAG, "could not persist display density setting", e);
766                 }
767             }
768         });
769         builder.setNegativeButton(android.R.string.cancel, null);
770         builder.show();
771     }
772
773     @Override
774     public boolean onPreferenceClick(Preference preference) {
775         if (preference == mFontSizePref) {
776             if (Utils.hasMultipleUsers(getActivity())) {
777                 showDialog(DLG_GLOBAL_CHANGE_WARNING);
778                 return true;
779             } else {
780                 mFontSizePref.click();
781             }
782         }
783         return false;
784     }
785
786     @Override
787     protected int getHelpResource() {
788         return R.string.help_uri_display;
789     }
790
791     public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
792             new BaseSearchIndexProvider() {
793
794                 @Override
795                 public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
796                         boolean enabled) {
797                     ArrayList<SearchIndexableResource> result =
798                             new ArrayList<SearchIndexableResource>();
799
800                     SearchIndexableResource sir = new SearchIndexableResource(context);
801                     sir.xmlResId = R.xml.display;
802                     result.add(sir);
803
804                     return result;
805                 }
806
807                 @Override
808                 public List<String> getNonIndexableKeys(Context context) {
809                     final CMHardwareManager hardware = CMHardwareManager.getInstance(context);
810
811                     ArrayList<String> result = new ArrayList<String>();
812                     if (!context.getResources().getBoolean(
813                             com.android.internal.R.bool.config_dreamsSupported)) {
814                         result.add(KEY_SCREEN_SAVER);
815                     }
816                     if (!context.getResources().getBoolean(
817                             com.android.internal.R.bool.config_intrusiveNotificationLed)) {
818                         result.add(KEY_NOTIFICATION_LIGHT);
819                     }
820                     if (!context.getResources().getBoolean(
821                             com.android.internal.R.bool.config_intrusiveBatteryLed)) {
822                         result.add(KEY_BATTERY_LIGHT);
823                     }
824                     if (!isAutomaticBrightnessAvailable(context.getResources())) {
825                         result.add(KEY_AUTO_BRIGHTNESS);
826                     }
827                     if (!isLiftToWakeAvailable(context)) {
828                         result.add(KEY_LIFT_TO_WAKE);
829                     }
830                     if (!Utils.isDozeAvailable(context)) {
831                         result.add(KEY_DOZE);
832                     }
833                     if (!isTapToWakeAvailable(context.getResources())) {
834                         result.add(KEY_TAP_TO_WAKE);
835                     }
836                     if (!context.getResources().getBoolean(
837                             org.cyanogenmod.platform.internal.R.bool.config_proximityCheckOnWake)) {
838                         result.add(KEY_PROXIMITY_WAKE);
839                     }
840                     if (!isCameraGestureAvailable(context.getResources())) {
841                         result.add(KEY_CAMERA_GESTURE);
842                     }
843                     if (hardware.isSupported(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY)) {
844                         result.add(KEY_HIGH_TOUCH_SENSITIVITY);
845                     }
846                     return result;
847                 }
848             };
849
850     public static void restore(Context context) {
851         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
852         final CMHardwareManager hardware = CMHardwareManager.getInstance(context);
853         if (hardware.isSupported(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY)) {
854             final boolean enabled = prefs.getBoolean(KEY_HIGH_TOUCH_SENSITIVITY,
855                     hardware.get(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY));
856             CMSettings.System.putInt(context.getContentResolver(),
857                     CMSettings.System.HIGH_TOUCH_SENSITIVITY_ENABLE,
858                     enabled ? 1 : 0);
859         }
860     }
861
862 }