OSDN Git Service

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