DisplaySettings.java revision 698c24fcf0577888116e60c52892318feadc836a
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings;
18
19import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
20
21import android.app.ActivityManagerNative;
22import android.app.admin.DevicePolicyManager;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.res.Configuration;
26import android.content.res.Resources;
27import android.database.ContentObserver;
28import android.os.Bundle;
29import android.os.Handler;
30import android.os.RemoteException;
31import android.preference.CheckBoxPreference;
32import android.preference.ListPreference;
33import android.preference.Preference;
34import android.preference.PreferenceScreen;
35import android.provider.Settings;
36import android.util.Log;
37
38import java.util.ArrayList;
39
40public class DisplaySettings extends SettingsPreferenceFragment implements
41        Preference.OnPreferenceChangeListener {
42    private static final String TAG = "DisplaySettings";
43
44    /** If there is no setting in the provider, use this. */
45    private static final int FALLBACK_SCREEN_TIMEOUT_VALUE = 30000;
46
47    private static final String KEY_SCREEN_TIMEOUT = "screen_timeout";
48    private static final String KEY_ACCELEROMETER = "accelerometer";
49    private static final String KEY_FONT_SIZE = "font_size";
50
51    private CheckBoxPreference mAccelerometer;
52    private ListPreference mFontSizePref;
53
54    private final Configuration mCurConfig = new Configuration();
55
56    private ListPreference mScreenTimeoutPreference;
57
58    private ContentObserver mAccelerometerRotationObserver = new ContentObserver(new Handler()) {
59        @Override
60        public void onChange(boolean selfChange) {
61            updateAccelerometerRotationCheckbox();
62        }
63    };
64
65    @Override
66    public void onCreate(Bundle savedInstanceState) {
67        super.onCreate(savedInstanceState);
68        ContentResolver resolver = getActivity().getContentResolver();
69
70        addPreferencesFromResource(R.xml.display_settings);
71
72        mAccelerometer = (CheckBoxPreference) findPreference(KEY_ACCELEROMETER);
73        mAccelerometer.setPersistent(false);
74
75        mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT);
76        final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT,
77                FALLBACK_SCREEN_TIMEOUT_VALUE);
78        mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout));
79        mScreenTimeoutPreference.setOnPreferenceChangeListener(this);
80        disableUnusableTimeouts(mScreenTimeoutPreference);
81        updateTimeoutPreferenceDescription(currentTimeout);
82
83        mFontSizePref = (ListPreference) findPreference(KEY_FONT_SIZE);
84        mFontSizePref.setOnPreferenceChangeListener(this);
85    }
86
87    private void updateTimeoutPreferenceDescription(long currentTimeout) {
88        ListPreference preference = mScreenTimeoutPreference;
89        String summary;
90        if (currentTimeout < 0) {
91            // Unsupported value
92            summary = "";
93        } else {
94            final CharSequence[] entries = preference.getEntries();
95            final CharSequence[] values = preference.getEntryValues();
96            int best = 0;
97            for (int i = 0; i < values.length; i++) {
98                long timeout = Long.parseLong(values[i].toString());
99                if (currentTimeout >= timeout) {
100                    best = i;
101                }
102            }
103            summary = preference.getContext().getString(R.string.screen_timeout_summary,
104                    entries[best]);
105        }
106        preference.setSummary(summary);
107    }
108
109    private void disableUnusableTimeouts(ListPreference screenTimeoutPreference) {
110        final DevicePolicyManager dpm =
111                (DevicePolicyManager) getActivity().getSystemService(
112                Context.DEVICE_POLICY_SERVICE);
113        final long maxTimeout = dpm != null ? dpm.getMaximumTimeToLock(null) : 0;
114        if (maxTimeout == 0) {
115            return; // policy not enforced
116        }
117        final CharSequence[] entries = screenTimeoutPreference.getEntries();
118        final CharSequence[] values = screenTimeoutPreference.getEntryValues();
119        ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
120        ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
121        for (int i = 0; i < values.length; i++) {
122            long timeout = Long.parseLong(values[i].toString());
123            if (timeout <= maxTimeout) {
124                revisedEntries.add(entries[i]);
125                revisedValues.add(values[i]);
126            }
127        }
128        if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
129            screenTimeoutPreference.setEntries(
130                    revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
131            screenTimeoutPreference.setEntryValues(
132                    revisedValues.toArray(new CharSequence[revisedValues.size()]));
133            final int userPreference = Integer.parseInt(screenTimeoutPreference.getValue());
134            if (userPreference <= maxTimeout) {
135                screenTimeoutPreference.setValue(String.valueOf(userPreference));
136            } else {
137                // There will be no highlighted selection since nothing in the list matches
138                // maxTimeout. The user can still select anything less than maxTimeout.
139                // TODO: maybe append maxTimeout to the list and mark selected.
140            }
141        }
142        screenTimeoutPreference.setEnabled(revisedEntries.size() > 0);
143    }
144
145    int floatToIndex(float val) {
146        String[] indices = getResources().getStringArray(R.array.entryvalues_font_size);
147        float lastVal = Float.parseFloat(indices[0]);
148        for (int i=1; i<indices.length; i++) {
149            float thisVal = Float.parseFloat(indices[i]);
150            if (val < (lastVal + (thisVal-lastVal)*.5f)) {
151                return i-1;
152            }
153            lastVal = thisVal;
154        }
155        return indices.length-1;
156    }
157
158    public void readFontSizePreference(ListPreference pref) {
159        try {
160            mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
161        } catch (RemoteException e) {
162            Log.w(TAG, "Unable to retrieve font size");
163        }
164
165        // mark the appropriate item in the preferences list
166        int index = floatToIndex(mCurConfig.fontScale);
167        pref.setValueIndex(index);
168
169        // report the current size in the summary text
170        final Resources res = getResources();
171        String[] fontSizeNames = res.getStringArray(R.array.entries_font_size);
172        pref.setSummary(String.format(res.getString(R.string.summary_font_size),
173                fontSizeNames[index]));
174    }
175
176    @Override
177    public void onResume() {
178        super.onResume();
179
180        updateState();
181        getContentResolver().registerContentObserver(
182                Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), true,
183                mAccelerometerRotationObserver);
184    }
185
186    @Override
187    public void onPause() {
188        super.onPause();
189
190        getContentResolver().unregisterContentObserver(mAccelerometerRotationObserver);
191    }
192
193    private void updateState() {
194        updateAccelerometerRotationCheckbox();
195        readFontSizePreference(mFontSizePref);
196    }
197
198    private void updateAccelerometerRotationCheckbox() {
199        mAccelerometer.setChecked(Settings.System.getInt(
200                getContentResolver(),
201                Settings.System.ACCELEROMETER_ROTATION, 0) != 0);
202    }
203
204    public void writeFontSizePreference(Object objValue) {
205        try {
206            mCurConfig.fontScale = Float.parseFloat(objValue.toString());
207            ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
208        } catch (RemoteException e) {
209            Log.w(TAG, "Unable to save font size");
210        }
211    }
212
213    @Override
214    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
215        if (preference == mAccelerometer) {
216            Settings.System.putInt(getContentResolver(),
217                    Settings.System.ACCELEROMETER_ROTATION,
218                    mAccelerometer.isChecked() ? 1 : 0);
219        }
220        return super.onPreferenceTreeClick(preferenceScreen, preference);
221    }
222
223    public boolean onPreferenceChange(Preference preference, Object objValue) {
224        final String key = preference.getKey();
225        if (KEY_SCREEN_TIMEOUT.equals(key)) {
226            int value = Integer.parseInt((String) objValue);
227            try {
228                Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, value);
229                updateTimeoutPreferenceDescription(value);
230            } catch (NumberFormatException e) {
231                Log.e(TAG, "could not persist screen timeout setting", e);
232            }
233        }
234        if (KEY_FONT_SIZE.equals(key)) {
235            writeFontSizePreference(objValue);
236        }
237
238        return true;
239    }
240}
241