summaryrefslogtreecommitdiffstats
path: root/src/com/android/settings/livedisplay/DisplayGamma.java
blob: 2b44cea111a0d520ad84e3853b2dfbb672909a23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
 * Copyright (C) 2013-2015 The CyanogenMod Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.livedisplay;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import com.android.settings.R;

import cyanogenmod.hardware.CMHardwareManager;
import cyanogenmod.providers.CMSettings;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Special preference type that allows configuration of Gamma settings
 */
public class DisplayGamma extends DialogPreference {
    private static final String TAG = "GammaCalibration";

    private static final int[] BAR_COLORS = new int[] {
        R.string.color_red_title,
        R.string.color_green_title,
        R.string.color_blue_title
    };

    private GammaSeekBar[][] mSeekBars;

    private int[][] mCurrentColors;
    private int[][] mOriginalColors;
    private int mNumberOfControls;
    private CMHardwareManager mHardware;

    public DisplayGamma(Context context, AttributeSet attrs) {
        super(context, attrs);

        mHardware = CMHardwareManager.getInstance(context);
        if (!mHardware.isSupported(CMHardwareManager.FEATURE_DISPLAY_GAMMA_CALIBRATION)) {
            return;
        }

        mNumberOfControls = mHardware.getNumGammaControls();
        mSeekBars = new GammaSeekBar[mNumberOfControls][BAR_COLORS.length];

        mOriginalColors = new int[mNumberOfControls][];
        mCurrentColors = new int[mNumberOfControls][];

        setDialogLayoutResource(R.layout.display_gamma_calibration);
    }

    @Override
    protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
        builder.setNeutralButton(R.string.settings_reset_button,
                new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
    }

    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);

        final ViewGroup container = (ViewGroup) view.findViewById(R.id.gamma_container);
        final LayoutInflater inflater = LayoutInflater.from(getContext());
        final SharedPreferences prefs = getSharedPreferences();
        final Resources res = container.getResources();
        final String[] gammaDescriptors = res.getStringArray(R.array.gamma_descriptors);

        // Create multiple sets of seekbars, depending on the
        // number of controls the device has
        for (int index = 0; index < mNumberOfControls; index++) {
            mOriginalColors[index] = mHardware.getDisplayGammaCalibration(index);
            mCurrentColors[index] = Arrays.copyOf(mOriginalColors[index],
                    mOriginalColors[index].length);

            final String defaultKey = "display_gamma_default_" + index;
            if (!prefs.contains(defaultKey)) {
                prefs.edit()
                        .putString(defaultKey, buildPreferenceValue(mOriginalColors[index]))
                        .apply();
            }

            if (mNumberOfControls != 1) {
                TextView header = (TextView) inflater.inflate(
                        R.layout.display_gamma_calibration_header, container, false);

                if (index < gammaDescriptors.length) {
                    header.setText(gammaDescriptors[index]);
                } else {
                    header.setText(res.getString(
                            R.string.gamma_tuning_control_set_header, index + 1));
                }
                container.addView(header);
            }

            int min = mHardware.getDisplayGammaCalibrationMin();
            int max = mHardware.getDisplayGammaCalibrationMax();
            for (int color = 0; color < BAR_COLORS.length; color++) {
                ViewGroup item = (ViewGroup) inflater.inflate(
                        R.layout.display_gamma_calibration_item, container, false);

                mSeekBars[index][color] = new GammaSeekBar(index, color, item, min, max);
                mSeekBars[index][color].setGamma(mCurrentColors[index][color]);
                // make sure to add the seekbar group to the container _after_
                // creating GammaSeekBar, so that GammaSeekBar has a chance to
                // get the correct subviews without getting confused by duplicate IDs
                container.addView(item);
            }
        }
    }

    @Override
    protected void showDialog(Bundle state) {
        super.showDialog(state);

        // can't use onPrepareDialogBuilder for this as we want the dialog
        // to be kept open on click
        AlertDialog d = (AlertDialog) getDialog();
        Button defaultsButton = d.getButton(DialogInterface.BUTTON_NEUTRAL);
        defaultsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int index = 0; index < mSeekBars.length; index++) {
                    final SharedPreferences prefs = getSharedPreferences();
                    final String defaultKey = "display_gamma_default_" + index;
                    // this key is guaranteed to be present, as we have
                    // created it in onBindDialogView()
                    final String value = prefs.getString(defaultKey, null);
                    final String[] defaultColors = value.split(" ");

                    for (int color = 0; color < BAR_COLORS.length; color++) {
                        int val = Integer.valueOf(defaultColors[color]);
                        mSeekBars[index][color].setGamma(val);
                        mCurrentColors[index][color] = val;
                    }
                    writeDisplayGamma(getContext(), index, mCurrentColors[index]);
                }
            }
       });
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        if (positiveResult) {
            Editor editor = getEditor();
            for (int i = 0; i < mNumberOfControls; i++) {
                editor.putString("display_gamma_" + i,
                        buildPreferenceValue(mHardware.getDisplayGammaCalibration(i)));
            }
            editor.apply();
        } else if (mOriginalColors != null) {
            for (int i = 0; i < mNumberOfControls; i++) {
                writeDisplayGamma(getContext(), i, mOriginalColors[i]);
            }
        }
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        final Parcelable superState = super.onSaveInstanceState();
        if (getDialog() == null || !getDialog().isShowing()) {
            return superState;
        }

        // Save the dialog state
        final SavedState myState = new SavedState(superState);
        myState.controlCount = mNumberOfControls;
        myState.currentColors = mCurrentColors;
        myState.originalColors = mOriginalColors;

        // Restore the old state when the activity or dialog is being paused
        for (int i = 0; i < mNumberOfControls; i++) {
            writeDisplayGamma(getContext(), i, mOriginalColors[i]);
        }
        mOriginalColors = null;

        return myState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state == null || !state.getClass().equals(SavedState.class)) {
            // Didn't save state for us in onSaveInstanceState
            super.onRestoreInstanceState(state);
            return;
        }

        SavedState myState = (SavedState) state;
        super.onRestoreInstanceState(myState.getSuperState());
        mNumberOfControls = myState.controlCount;
        mOriginalColors = myState.originalColors;
        mCurrentColors = myState.currentColors;

        for (int index = 0; index < mNumberOfControls; index++) {
            for (int color = 0; color < BAR_COLORS.length; color++) {
                mSeekBars[index][color].setGamma(mCurrentColors[index][color]);
            }
            writeDisplayGamma(getContext(), index, mCurrentColors[index]);
        }
    }

    private String buildPreferenceValue(int[] colorValues) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < colorValues.length; i++) {
            if (i != 0) {
                builder.append(" ");
            }
            builder.append(colorValues[i]);
        }
        return builder.toString();
    }

    public static void restore(Context context) {
        final CMHardwareManager hardware = CMHardwareManager.getInstance(context);
        if (!hardware.isSupported(CMHardwareManager.FEATURE_DISPLAY_GAMMA_CALIBRATION)) {
            return;
        }

        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        int[] rgb = new int[3];
        for (int i = 0; i < hardware.getNumGammaControls(); i++) {
            final String value = prefs.getString("display_gamma_" + i, null);
            if (value != null) {
                final String[] values = value.split(" ");
                rgb[0] = Integer.valueOf(values[0]);
                rgb[1] = Integer.valueOf(values[1]);
                rgb[2] = Integer.valueOf(values[2]);
                writeDisplayGamma(context, i, rgb);
            }
        }
    }

    private static class SavedState extends BaseSavedState {
        int controlCount;
        int[][] originalColors;
        int[][] currentColors;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        public SavedState(Parcel source) {
            super(source);
            controlCount = source.readInt();
            originalColors = new int[controlCount][];
            currentColors = new int[controlCount][];
            for (int i = 0; i < controlCount; i++) {
                originalColors[i] = source.createIntArray();
            }
            for (int i = 0; i < controlCount; i++) {
                currentColors[i] = source.createIntArray();
            }
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(controlCount);
            for (int i = 0; i < controlCount; i++) {
                dest.writeIntArray(originalColors[i]);
            }
            for (int i = 0; i < controlCount; i++) {
                dest.writeIntArray(currentColors[i]);
            }
        }

        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {

            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

    private static void writeDisplayGamma(Context context, int index, int[] entries) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < entries.length; i++) {
            builder.append(i);
            if (i != entries.length - 1) {
                builder.append("|");
            }
        }
        CMSettings.Secure.putString(context.getContentResolver(),
                CMSettings.Secure.DISPLAY_GAMMA_CALIBRATION_PREFIX + index,
                builder.toString());
    }

    private class GammaSeekBar implements SeekBar.OnSeekBarChangeListener {
        private int mControlIndex;
        private int mColorIndex;
        private int mOriginal;
        private int mMin;
        private int mMax;
        private SeekBar mSeekBar;
        private TextView mValue;

        public GammaSeekBar(int controlIndex, int colorIndex, ViewGroup container,
                int min, int max) {
            mControlIndex = controlIndex;
            mColorIndex = colorIndex;

            mMin = min;
            mMax = max;

            mValue = (TextView) container.findViewById(R.id.color_value);
            mSeekBar = (SeekBar) container.findViewById(R.id.color_seekbar);

            TextView label = (TextView) container.findViewById(R.id.color_text);
            label.setText(container.getContext().getString(BAR_COLORS[colorIndex]));

            mSeekBar.setMax(mMax - mMin);
            mSeekBar.setProgress(0);
            mValue.setText(String.valueOf(mSeekBar.getProgress() + mMin));

            // this must be done last, we don't want to apply our initial value to the hardware
            mSeekBar.setOnSeekBarChangeListener(this);
        }

        public void setGamma(int gamma) {
            mSeekBar.setProgress(gamma - mMin);
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                mCurrentColors[mControlIndex][mColorIndex] = progress + mMin;
                writeDisplayGamma(getContext(), mControlIndex, mCurrentColors[mControlIndex]);
            }
            mValue.setText(String.valueOf(progress + mMin));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // Do nothing
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // Do nothing
        }
    }
}