OSDN Git Service

Settings: move high touch sensitivity setting to Display
[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 defaultDensity = getDefaultDensity();
212                 int currentDensity = getCurrentDensity();
213                 if (currentDensity < 10 || currentDensity >= 1000) {
214                     // Unsupported value, force default
215                     currentDensity = defaultDensity;
216                 }
217
218                 int factor = defaultDensity >= 480 ? 40 : 20;
219                 int minimumDensity = defaultDensity - 4 * factor;
220                 int currentIndex = -1;
221                 String[] densityEntries = new String[7];
222                 String[] densityValues = new String[7];
223                 for (int idx = 0; idx < 7; ++idx) {
224                     int val = minimumDensity + factor * idx;
225                     int valueFormatResId = val == defaultDensity
226                             ? R.string.lcd_density_default_value_format
227                             : R.string.lcd_density_value_format;
228
229                     densityEntries[idx] = getString(valueFormatResId, val);
230                     densityValues[idx] = Integer.toString(val);
231                     if (currentDensity == val) {
232                         currentIndex = idx;
233                     }
234                 }
235                 mLcdDensityPreference.setEntries(densityEntries);
236                 mLcdDensityPreference.setEntryValues(densityValues);
237                 if (currentIndex != -1) {
238                     mLcdDensityPreference.setValueIndex(currentIndex);
239                 }
240                 mLcdDensityPreference.setOnPreferenceChangeListener(this);
241                 updateLcdDensityPreferenceDescription(currentDensity);
242             }
243         }
244
245         mFontSizePref = (FontDialogPreference) findPreference(KEY_FONT_SIZE);
246         mFontSizePref.setOnPreferenceChangeListener(this);
247         mFontSizePref.setOnPreferenceClickListener(this);
248
249         mAutoBrightnessPreference = (SwitchPreference) findPreference(KEY_AUTO_BRIGHTNESS);
250         if (mAutoBrightnessPreference != null && isAutomaticBrightnessAvailable(getResources())) {
251             mAutoBrightnessPreference.setOnPreferenceChangeListener(this);
252         } else {
253             if (displayPrefs != null && mAutoBrightnessPreference != null) {
254                 displayPrefs.removePreference(mAutoBrightnessPreference);
255                 mAutoBrightnessPreference = null;
256             }
257         }
258
259         mLiftToWakePreference = (SwitchPreference) findPreference(KEY_LIFT_TO_WAKE);
260         if (mLiftToWakePreference != null && isLiftToWakeAvailable(activity)) {
261             mLiftToWakePreference.setOnPreferenceChangeListener(this);
262         } else {
263             if (displayPrefs != null && mLiftToWakePreference != null) {
264                 displayPrefs.removePreference(mLiftToWakePreference);
265                 mLiftToWakePreference = null;
266             }
267         }
268
269         mDozePreference = (SwitchPreference) findPreference(KEY_DOZE);
270         if (mDozePreference != null && Utils.isDozeAvailable(activity)) {
271             mDozePreference.setOnPreferenceChangeListener(this);
272         } else {
273             if (displayPrefs != null && mDozePreference != null) {
274                 displayPrefs.removePreference(mDozePreference);
275             }
276         }
277
278         mCameraGesturePreference = (SwitchPreference) findPreference(KEY_CAMERA_GESTURE);
279         if (mCameraGesturePreference != null && isCameraGestureAvailable(getResources())) {
280             mCameraGesturePreference.setOnPreferenceChangeListener(this);
281         } else {
282             if (displayPrefs != null && mCameraGesturePreference != null) {
283                 displayPrefs.removePreference(mCameraGesturePreference);
284             }
285         }
286
287         mNightModePreference = (ListPreference) findPreference(KEY_NIGHT_MODE);
288         if (mNightModePreference != null) {
289             final UiModeManager uiManager = (UiModeManager) getSystemService(
290                     Context.UI_MODE_SERVICE);
291             final int currentNightMode = uiManager.getNightMode();
292             mNightModePreference.setValue(String.valueOf(currentNightMode));
293             mNightModePreference.setOnPreferenceChangeListener(this);
294         }
295
296         mTapToWakePreference = (SwitchPreference) findPreference(KEY_TAP_TO_WAKE);
297         if (mTapToWakePreference != null && isTapToWakeAvailable(getResources())) {
298             mTapToWakePreference.setOnPreferenceChangeListener(this);
299         } else {
300             if (displayPrefs != null && mTapToWakePreference != null) {
301                 displayPrefs.removePreference(mTapToWakePreference);
302             }
303         }
304
305         mHighTouchSensitivity = (SwitchPreference) findPreference(KEY_HIGH_TOUCH_SENSITIVITY);
306         if (!mHardware.isSupported(
307                 CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY)) {
308             displayPrefs.removePreference(mHighTouchSensitivity);
309             mHighTouchSensitivity = null;
310         } else {
311             mHighTouchSensitivity.setChecked(
312                     mHardware.get(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY));
313         }
314
315         mProximityCheckOnWakePreference = (SwitchPreference) findPreference(KEY_PROXIMITY_WAKE);
316         boolean proximityCheckOnWake = getResources().getBoolean(
317                 org.cyanogenmod.platform.internal.R.bool.config_proximityCheckOnWake);
318         if (!proximityCheckOnWake) {
319             if (displayPrefs != null && mProximityCheckOnWakePreference != null) {
320                 displayPrefs.removePreference(mProximityCheckOnWakePreference);
321             }
322             CMSettings.System.putInt(getContentResolver(), CMSettings.System.PROXIMITY_ON_WAKE, 0);
323         } else {
324             boolean proximityCheckOnWakeDefault = getResources().getBoolean(
325                     org.cyanogenmod.platform.internal.R.bool.config_proximityCheckOnWakeEnabledByDefault);
326             mProximityCheckOnWakePreference.setChecked(CMSettings.System.getInt(getContentResolver(),
327                     CMSettings.System.PROXIMITY_ON_WAKE,
328                     (proximityCheckOnWakeDefault ? 1 : 0)) == 1);
329         }
330
331         mWakeWhenPluggedOrUnplugged =
332                 (SwitchPreference) findPreference(KEY_WAKE_WHEN_PLUGGED_OR_UNPLUGGED);
333         initPulse((PreferenceCategory) findPreference(KEY_CATEGORY_LIGHTS));
334     }
335
336     private int getDefaultDensity() {
337         IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService(
338                 Context.WINDOW_SERVICE));
339         try {
340             return wm.getInitialDisplayDensity(Display.DEFAULT_DISPLAY);
341         } catch (RemoteException e) {
342             e.printStackTrace();
343         }
344         return DisplayMetrics.DENSITY_DEVICE;
345     }
346
347     private int getCurrentDensity() {
348         IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService(
349                 Context.WINDOW_SERVICE));
350         try {
351             return wm.getBaseDisplayDensity(Display.DEFAULT_DISPLAY);
352         } catch (RemoteException e) {
353             e.printStackTrace();
354         }
355         return DisplayMetrics.DENSITY_DEVICE;
356     }
357
358     private static boolean allowAllRotations(Context context) {
359         return Resources.getSystem().getBoolean(
360                 com.android.internal.R.bool.config_allowAllRotations);
361     }
362
363     private static boolean isLiftToWakeAvailable(Context context) {
364         SensorManager sensors = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
365         return sensors != null && sensors.getDefaultSensor(Sensor.TYPE_WAKE_GESTURE) != null;
366     }
367
368     private static boolean isTapToWakeAvailable(Resources res) {
369         return res.getBoolean(com.android.internal.R.bool.config_supportDoubleTapWake);
370     }
371
372     private static boolean isAutomaticBrightnessAvailable(Resources res) {
373         return res.getBoolean(com.android.internal.R.bool.config_automatic_brightness_available);
374     }
375
376     private void updateAccelerometerRotationSwitch() {
377         if (mAccelerometer != null) {
378             mAccelerometer.setChecked(!RotationPolicy.isRotationLocked(getActivity()));
379         }
380     }
381     private void updateDisplayRotationPreferenceDescription() {
382         if (mDisplayRotationPreference == null) {
383             // The preference was removed, do nothing
384             return;
385         }
386
387         // We have a preference, lets update the summary
388         boolean rotationEnabled = Settings.System.getInt(getContentResolver(),
389                 Settings.System.ACCELEROMETER_ROTATION, 0) != 0;
390
391         if (!rotationEnabled) {
392             mDisplayRotationPreference.setSummary(R.string.display_rotation_disabled);
393             return;
394         }
395
396         StringBuilder summary = new StringBuilder();
397         int mode = Settings.System.getInt(getContentResolver(),
398                 Settings.System.ACCELEROMETER_ROTATION_ANGLES,
399                 DisplayRotation.ROTATION_0_MODE
400                 | DisplayRotation.ROTATION_90_MODE
401                 | DisplayRotation.ROTATION_270_MODE);
402         ArrayList<String> rotationList = new ArrayList<String>();
403         String delim = "";
404
405         if ((mode & DisplayRotation.ROTATION_0_MODE) != 0) {
406             rotationList.add("0");
407         }
408         if ((mode & DisplayRotation.ROTATION_90_MODE) != 0) {
409             rotationList.add("90");
410         }
411         if ((mode & DisplayRotation.ROTATION_180_MODE) != 0) {
412             rotationList.add("180");
413         }
414         if ((mode & DisplayRotation.ROTATION_270_MODE) != 0) {
415             rotationList.add("270");
416         }
417         for (int i = 0; i < rotationList.size(); i++) {
418             summary.append(delim).append(rotationList.get(i));
419             if ((rotationList.size() - i) > 2) {
420                 delim = ", ";
421             } else {
422                 delim = " & ";
423             }
424         }
425         summary.append(" " + getString(R.string.display_rotation_unit));
426         mDisplayRotationPreference.setSummary(summary);
427     }
428
429     private static boolean isCameraGestureAvailable(Resources res) {
430         boolean configSet = res.getInteger(
431                 com.android.internal.R.integer.config_cameraLaunchGestureSensorType) != -1;
432         return configSet &&
433                 !SystemProperties.getBoolean("gesture.disable_camera_launch", false);
434     }
435
436     private void updateTimeoutPreferenceDescription(long currentTimeout) {
437         ListPreference preference = mScreenTimeoutPreference;
438         String summary;
439         if (currentTimeout < 0) {
440             // Unsupported value
441             summary = "";
442         } else {
443             final CharSequence[] entries = preference.getEntries();
444             final CharSequence[] values = preference.getEntryValues();
445             if (entries == null || entries.length == 0) {
446                 summary = "";
447             } else {
448                 int best = 0;
449                 for (int i = 0; i < values.length; i++) {
450                     long timeout = Long.parseLong(values[i].toString());
451                     if (currentTimeout >= timeout) {
452                         best = i;
453                     }
454                 }
455                 summary = preference.getContext().getString(R.string.screen_timeout_summary,
456                         entries[best]);
457             }
458         }
459         preference.setSummary(summary);
460     }
461
462     private void updateLcdDensityPreferenceDescription(int currentDensity) {
463         final int summaryResId = currentDensity == getDefaultDensity()
464                 ? R.string.lcd_density_default_value_format : R.string.lcd_density_value_format;
465         mLcdDensityPreference.setSummary(getString(summaryResId, currentDensity));
466     }
467
468     private void disableUnusableTimeouts(ListPreference screenTimeoutPreference) {
469         final DevicePolicyManager dpm =
470                 (DevicePolicyManager) getActivity().getSystemService(
471                 Context.DEVICE_POLICY_SERVICE);
472         final long maxTimeout = dpm != null ? dpm.getMaximumTimeToLock(null) : 0;
473         if (maxTimeout == 0) {
474             return; // policy not enforced
475         }
476         final CharSequence[] entries = screenTimeoutPreference.getEntries();
477         final CharSequence[] values = screenTimeoutPreference.getEntryValues();
478         ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
479         ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
480         for (int i = 0; i < values.length; i++) {
481             long timeout = Long.parseLong(values[i].toString());
482             if (timeout <= maxTimeout) {
483                 revisedEntries.add(entries[i]);
484                 revisedValues.add(values[i]);
485             }
486         }
487         if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
488             final int userPreference = Integer.parseInt(screenTimeoutPreference.getValue());
489             screenTimeoutPreference.setEntries(
490                     revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
491             screenTimeoutPreference.setEntryValues(
492                     revisedValues.toArray(new CharSequence[revisedValues.size()]));
493             if (userPreference <= maxTimeout) {
494                 screenTimeoutPreference.setValue(String.valueOf(userPreference));
495             } else if (revisedValues.size() > 0
496                     && Long.parseLong(revisedValues.get(revisedValues.size() - 1).toString())
497                     == maxTimeout) {
498                 // If the last one happens to be the same as the max timeout, select that
499                 screenTimeoutPreference.setValue(String.valueOf(maxTimeout));
500             } else {
501                 // There will be no highlighted selection since nothing in the list matches
502                 // maxTimeout. The user can still select anything less than maxTimeout.
503                 // TODO: maybe append maxTimeout to the list and mark selected.
504             }
505         }
506         screenTimeoutPreference.setEnabled(revisedEntries.size() > 0);
507     }
508
509     @Override
510     public void onResume() {
511         super.onResume();
512         updateDisplayRotationPreferenceDescription();
513
514         RotationPolicy.registerRotationPolicyListener(getActivity(),
515                 mRotationPolicyListener);
516
517         final ContentResolver resolver = getContentResolver();
518
519         // Display rotation observer
520         resolver.registerContentObserver(
521                 Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), true,
522                 mAccelerometerRotationObserver);
523
524         // Default value for wake-on-plug behavior from config.xml
525         boolean wakeUpWhenPluggedOrUnpluggedConfig = getResources().getBoolean(
526                 com.android.internal.R.bool.config_unplugTurnsOnScreen);
527
528         if (mWakeWhenPluggedOrUnplugged != null) {
529         mWakeWhenPluggedOrUnplugged.setChecked(CMSettings.Global.getInt(getContentResolver(),
530                 CMSettings.Global.WAKE_WHEN_PLUGGED_OR_UNPLUGGED,
531                 (wakeUpWhenPluggedOrUnpluggedConfig ? 1 : 0)) == 1);
532         }
533
534         updateState();
535         updateAccelerometerRotationSwitch();
536     }
537
538     @Override
539     public void onPause() {
540         super.onPause();
541
542         RotationPolicy.unregisterRotationPolicyListener(getActivity(),
543                 mRotationPolicyListener);
544
545         // Display rotation observer
546         getContentResolver().unregisterContentObserver(mAccelerometerRotationObserver);
547     }
548
549     @Override
550     public Dialog onCreateDialog(int dialogId) {
551         if (dialogId == DLG_GLOBAL_CHANGE_WARNING) {
552             return Utils.buildGlobalChangeWarningDialog(getActivity(),
553                     R.string.global_font_change_title,
554                     new Runnable() {
555                         public void run() {
556                             mFontSizePref.click();
557                         }
558                     });
559         }
560         return null;
561     }
562
563     private void updateState() {
564         readFontSizePreference(mFontSizePref);
565         updateScreenSaverSummary();
566
567         // Update auto brightness if it is available.
568         if (mAutoBrightnessPreference != null) {
569             int brightnessMode = Settings.System.getInt(getContentResolver(),
570                     SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
571             mAutoBrightnessPreference.setChecked(brightnessMode != SCREEN_BRIGHTNESS_MODE_MANUAL);
572         }
573
574         // Update lift-to-wake if it is available.
575         if (mLiftToWakePreference != null) {
576             int value = Settings.Secure.getInt(getContentResolver(), WAKE_GESTURE_ENABLED, 0);
577             mLiftToWakePreference.setChecked(value != 0);
578         }
579
580         // Update doze if it is available.
581         if (mDozePreference != null) {
582             int value = Settings.Secure.getInt(getContentResolver(), DOZE_ENABLED, 1);
583             mDozePreference.setChecked(value != 0);
584         }
585
586         // Update tap to wake if it is available.
587         if (mTapToWakePreference != null) {
588             int value = Settings.Secure.getInt(getContentResolver(), DOUBLE_TAP_TO_WAKE, 0);
589             mTapToWakePreference.setChecked(value != 0);
590         }
591
592         // Update camera gesture #1 if it is available.
593         if (mCameraGesturePreference != null) {
594             int value = Settings.Secure.getInt(getContentResolver(), CAMERA_GESTURE_DISABLED, 0);
595             mCameraGesturePreference.setChecked(value == 0);
596         }
597     }
598
599     private void updateScreenSaverSummary() {
600         if (mScreenSaverPreference != null) {
601             mScreenSaverPreference.setSummary(
602                     DreamSettings.getSummaryTextWithDreamName(getActivity()));
603         }
604     }
605
606     private void writeLcdDensityPreference(final Context context, final int density) {
607         final IActivityManager am = ActivityManagerNative.asInterface(
608                 ServiceManager.checkService("activity"));
609         final IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.checkService(
610                 Context.WINDOW_SERVICE));
611         AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
612             @Override
613             protected void onPreExecute() {
614                 ProgressDialog dialog = new ProgressDialog(context);
615                 dialog.setMessage(getResources().getString(R.string.restarting_ui));
616                 dialog.setCancelable(false);
617                 dialog.setIndeterminate(true);
618                 dialog.show();
619             }
620             @Override
621             protected Void doInBackground(Void... params) {
622                 // Give the user a second to see the dialog
623                 try {
624                     Thread.sleep(1000);
625                 } catch (InterruptedException e) {
626                     // Ignore
627                 }
628
629                 try {
630                     wm.setForcedDisplayDensity(Display.DEFAULT_DISPLAY, density);
631                 } catch (RemoteException e) {
632                     Log.e(TAG, "Failed to set density to " + density, e);
633                 }
634
635                 // Restart the UI
636                 try {
637                     am.restart();
638                 } catch (RemoteException e) {
639                     Log.e(TAG, "Failed to restart");
640                 }
641                 return null;
642             }
643         };
644         task.execute();
645     }
646
647     // === Pulse notification light ===
648
649     private void initPulse(PreferenceCategory parent) {
650         if (!getResources().getBoolean(
651                 com.android.internal.R.bool.config_intrusiveNotificationLed)) {
652             parent.removePreference(parent.findPreference(KEY_NOTIFICATION_LIGHT));
653         }
654         if (!getResources().getBoolean(
655                 com.android.internal.R.bool.config_intrusiveBatteryLed)
656                 || UserHandle.myUserId() != UserHandle.USER_OWNER) {
657             parent.removePreference(parent.findPreference(KEY_BATTERY_LIGHT));
658         }
659         if (parent.getPreferenceCount() == 0) {
660             getPreferenceScreen().removePreference(parent);
661         }
662     }
663     /**
664      * Reads the current font size and sets the value in the summary text
665      */
666     public void readFontSizePreference(Preference pref) {
667         try {
668             mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
669         } catch (RemoteException e) {
670             Log.w(TAG, "Unable to retrieve font size");
671         }
672
673         // report the current size in the summary text
674         final Resources res = getResources();
675         String fontDesc = FontDialogPreference.getFontSizeDescription(res, mCurConfig.fontScale);
676         pref.setSummary(getString(R.string.summary_font_size, fontDesc));
677     }
678
679     public void writeFontSizePreference(Object objValue) {
680         try {
681             mCurConfig.fontScale = Float.parseFloat(objValue.toString());
682             ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
683         } catch (RemoteException e) {
684             Log.w(TAG, "Unable to save font size");
685         }
686     }
687
688     @Override
689     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
690         if (preference == mWakeWhenPluggedOrUnplugged) {
691             CMSettings.Global.putInt(getContentResolver(),
692                     CMSettings.Global.WAKE_WHEN_PLUGGED_OR_UNPLUGGED,
693                     mWakeWhenPluggedOrUnplugged.isChecked() ? 1 : 0);
694             return true;
695         } else if (preference == mAccelerometer) {
696             RotationPolicy.setRotationLockForAccessibility(getActivity(),
697                     !mAccelerometer.isChecked());
698         } else if (preference == mHighTouchSensitivity) {
699             boolean mHighTouchSensitivityEnable = mHighTouchSensitivity.isChecked();
700             CMSettings.System.putInt(getActivity().getContentResolver(),
701                     CMSettings.System.HIGH_TOUCH_SENSITIVITY_ENABLE,
702                     mHighTouchSensitivityEnable ? 1 : 0);
703             return true;
704         }
705
706         return super.onPreferenceTreeClick(preferenceScreen, preference);
707     }
708
709     @Override
710     public boolean onPreferenceChange(Preference preference, Object objValue) {
711         final String key = preference.getKey();
712         if (KEY_SCREEN_TIMEOUT.equals(key)) {
713             try {
714                 int value = Integer.parseInt((String) objValue);
715                 Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, value);
716                 updateTimeoutPreferenceDescription(value);
717             } catch (NumberFormatException e) {
718                 Log.e(TAG, "could not persist screen timeout setting", e);
719             }
720         }
721         if (KEY_LCD_DENSITY.equals(key)) {
722             String newValue = (String) objValue;
723             String oldValue = mLcdDensityPreference.getValue();
724             if (!TextUtils.equals(newValue, oldValue)) {
725                 showLcdConfirmationDialog((String) objValue);
726             }
727             return false;
728         }
729         if (KEY_FONT_SIZE.equals(key)) {
730             writeFontSizePreference(objValue);
731         }
732         if (preference == mAutoBrightnessPreference) {
733             boolean auto = (Boolean) objValue;
734             Settings.System.putInt(getContentResolver(), SCREEN_BRIGHTNESS_MODE,
735                     auto ? SCREEN_BRIGHTNESS_MODE_AUTOMATIC : SCREEN_BRIGHTNESS_MODE_MANUAL);
736         }
737         if (preference == mLiftToWakePreference) {
738             boolean value = (Boolean) objValue;
739             Settings.Secure.putInt(getContentResolver(), WAKE_GESTURE_ENABLED, value ? 1 : 0);
740         }
741         if (preference == mDozePreference) {
742             boolean value = (Boolean) objValue;
743             Settings.Secure.putInt(getContentResolver(), DOZE_ENABLED, value ? 1 : 0);
744         }
745         if (preference == mTapToWakePreference) {
746             boolean value = (Boolean) objValue;
747             Settings.Secure.putInt(getContentResolver(), DOUBLE_TAP_TO_WAKE, value ? 1 : 0);
748         }
749         if (preference == mCameraGesturePreference) {
750             boolean value = (Boolean) objValue;
751             Settings.Secure.putInt(getContentResolver(), CAMERA_GESTURE_DISABLED,
752                     value ? 0 : 1 /* Backwards because setting is for disabling */);
753         }
754         if (preference == mNightModePreference) {
755             try {
756                 final int value = Integer.parseInt((String) objValue);
757                 final UiModeManager uiManager = (UiModeManager) getSystemService(
758                         Context.UI_MODE_SERVICE);
759                 uiManager.setNightMode(value);
760             } catch (NumberFormatException e) {
761                 Log.e(TAG, "could not persist night mode setting", e);
762             }
763         }
764         return true;
765     }
766
767     private void showLcdConfirmationDialog(final String lcdDensity) {
768         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
769         builder.setTitle(R.string.lcd_density);
770         builder.setMessage(R.string.lcd_density_prompt_message);
771         builder.setPositiveButton(R.string.print_restart,
772                 new DialogInterface.OnClickListener() {
773             public void onClick(DialogInterface dialog, int id) {
774                 try {
775                     int value = Integer.parseInt(lcdDensity);
776                     writeLcdDensityPreference(getActivity(), value);
777                     updateLcdDensityPreferenceDescription(value);
778                 } catch (NumberFormatException e) {
779                     Log.e(TAG, "could not persist display density setting", e);
780                 }
781             }
782         });
783         builder.setNegativeButton(android.R.string.cancel, null);
784         builder.show();
785     }
786
787     @Override
788     public boolean onPreferenceClick(Preference preference) {
789         if (preference == mFontSizePref) {
790             if (Utils.hasMultipleUsers(getActivity())) {
791                 showDialog(DLG_GLOBAL_CHANGE_WARNING);
792                 return true;
793             } else {
794                 mFontSizePref.click();
795             }
796         }
797         return false;
798     }
799
800     @Override
801     protected int getHelpResource() {
802         return R.string.help_uri_display;
803     }
804
805     public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
806             new BaseSearchIndexProvider() {
807
808                 @Override
809                 public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
810                         boolean enabled) {
811                     ArrayList<SearchIndexableResource> result =
812                             new ArrayList<SearchIndexableResource>();
813
814                     SearchIndexableResource sir = new SearchIndexableResource(context);
815                     sir.xmlResId = R.xml.display;
816                     result.add(sir);
817
818                     return result;
819                 }
820
821                 @Override
822                 public List<String> getNonIndexableKeys(Context context) {
823                     final CMHardwareManager hardware = CMHardwareManager.getInstance(context);
824
825                     ArrayList<String> result = new ArrayList<String>();
826                     if (!context.getResources().getBoolean(
827                             com.android.internal.R.bool.config_dreamsSupported)) {
828                         result.add(KEY_SCREEN_SAVER);
829                     }
830                     if (!context.getResources().getBoolean(
831                             com.android.internal.R.bool.config_intrusiveNotificationLed)) {
832                         result.add(KEY_NOTIFICATION_LIGHT);
833                     }
834                     if (!context.getResources().getBoolean(
835                             com.android.internal.R.bool.config_intrusiveBatteryLed)) {
836                         result.add(KEY_BATTERY_LIGHT);
837                     }
838                     if (!isAutomaticBrightnessAvailable(context.getResources())) {
839                         result.add(KEY_AUTO_BRIGHTNESS);
840                     }
841                     if (!isLiftToWakeAvailable(context)) {
842                         result.add(KEY_LIFT_TO_WAKE);
843                     }
844                     if (!Utils.isDozeAvailable(context)) {
845                         result.add(KEY_DOZE);
846                     }
847                     if (!isTapToWakeAvailable(context.getResources())) {
848                         result.add(KEY_TAP_TO_WAKE);
849                     }
850                     if (!context.getResources().getBoolean(
851                             org.cyanogenmod.platform.internal.R.bool.config_proximityCheckOnWake)) {
852                         result.add(KEY_PROXIMITY_WAKE);
853                     }
854                     if (!isCameraGestureAvailable(context.getResources())) {
855                         result.add(KEY_CAMERA_GESTURE);
856                     }
857                     if (hardware.isSupported(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY)) {
858                         result.add(KEY_HIGH_TOUCH_SENSITIVITY);
859                     }
860                     return result;
861                 }
862             };
863
864     public static void restore(Context context) {
865         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
866         final CMHardwareManager hardware = CMHardwareManager.getInstance(context);
867         if (hardware.isSupported(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY)) {
868             final boolean enabled = prefs.getBoolean(KEY_HIGH_TOUCH_SENSITIVITY,
869                     hardware.get(CMHardwareManager.FEATURE_HIGH_TOUCH_SENSITIVITY));
870             CMSettings.System.putInt(context.getContentResolver(),
871                     CMSettings.System.HIGH_TOUCH_SENSITIVITY_ENABLE,
872                     enabled ? 1 : 0);
873         }
874     }
875
876 }