blob: 7fb5b191a9b04ddc13b53ed616abad5e07615ee0 [file] [log] [blame]
Justin Klaassen911e8892016-06-21 18:24:24 -07001/*
2 * Copyright (C) 2016 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
Christine Franks0ada2772019-02-25 13:54:57 -080017package com.android.server.display.color;
Justin Klaassen911e8892016-06-21 18:24:24 -070018
Christine Franks83cc5412018-07-03 14:46:07 -070019import static android.hardware.display.ColorDisplayManager.AUTO_MODE_CUSTOM_TIME;
20import static android.hardware.display.ColorDisplayManager.AUTO_MODE_DISABLED;
21import static android.hardware.display.ColorDisplayManager.AUTO_MODE_TWILIGHT;
Christine Franksd154fe52019-01-04 17:17:45 -080022import static android.hardware.display.ColorDisplayManager.COLOR_MODE_AUTOMATIC;
23import static android.hardware.display.ColorDisplayManager.COLOR_MODE_BOOSTED;
24import static android.hardware.display.ColorDisplayManager.COLOR_MODE_NATURAL;
25import static android.hardware.display.ColorDisplayManager.COLOR_MODE_SATURATED;
Christine Franks531c0612019-05-16 14:29:14 -070026import static android.hardware.display.ColorDisplayManager.VENDOR_COLOR_MODE_RANGE_MAX;
27import static android.hardware.display.ColorDisplayManager.VENDOR_COLOR_MODE_RANGE_MIN;
Christine Franksa4ed3762019-01-24 15:37:04 -080028
Christine Franks0ada2772019-02-25 13:54:57 -080029import static com.android.server.display.color.DisplayTransformManager.LEVEL_COLOR_MATRIX_NIGHT_DISPLAY;
Christine Franks39b03112018-07-03 14:46:07 -070030
Christine Franks09c229e2018-12-14 10:37:40 -080031import android.Manifest;
Justin Klaassen639214e2016-07-14 21:00:06 -070032import android.animation.Animator;
33import android.animation.AnimatorListenerAdapter;
34import android.animation.TypeEvaluator;
35import android.animation.ValueAnimator;
Justin Klaassen4346f632016-08-08 15:01:47 -070036import android.annotation.NonNull;
Justin Klaassen908b86c2016-08-08 09:18:42 -070037import android.annotation.Nullable;
Christine Franksf3529b22019-01-03 13:20:17 -080038import android.annotation.Size;
Christine Franks55194dc2019-01-15 13:47:06 -080039import android.annotation.UserIdInt;
Justin Klaassen911e8892016-06-21 18:24:24 -070040import android.app.AlarmManager;
41import android.content.BroadcastReceiver;
42import android.content.ContentResolver;
43import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
Christine Franks09c229e2018-12-14 10:37:40 -080046import android.content.pm.PackageManager;
Daniel Solomon8b72c5b2018-11-25 11:07:13 -080047import android.content.res.Resources;
Justin Klaassen2696d992016-07-11 21:26:46 -070048import android.database.ContentObserver;
Christine Franksf3529b22019-01-03 13:20:17 -080049import android.hardware.display.ColorDisplayManager;
Christine Franks83cc5412018-07-03 14:46:07 -070050import android.hardware.display.ColorDisplayManager.AutoMode;
Christine Franksd154fe52019-01-04 17:17:45 -080051import android.hardware.display.ColorDisplayManager.ColorMode;
Christine Franks39b03112018-07-03 14:46:07 -070052import android.hardware.display.IColorDisplayManager;
Christine Franks83cc5412018-07-03 14:46:07 -070053import android.hardware.display.Time;
Justin Klaassen2696d992016-07-11 21:26:46 -070054import android.net.Uri;
Justin Klaassen639214e2016-07-14 21:00:06 -070055import android.opengl.Matrix;
Christine Franks39b03112018-07-03 14:46:07 -070056import android.os.Binder;
Justin Klaassen911e8892016-06-21 18:24:24 -070057import android.os.Handler;
58import android.os.Looper;
Christine Franks09c229e2018-12-14 10:37:40 -080059import android.os.Message;
Christine Franksd154fe52019-01-04 17:17:45 -080060import android.os.SystemProperties;
Justin Klaassen911e8892016-06-21 18:24:24 -070061import android.os.UserHandle;
62import android.provider.Settings.Secure;
Christine Franks57fdde82018-07-03 14:46:07 -070063import android.provider.Settings.System;
Justin Klaassen639214e2016-07-14 21:00:06 -070064import android.util.MathUtils;
Justin Klaassen911e8892016-06-21 18:24:24 -070065import android.util.Slog;
Daniel Solomon41ee35f2019-07-11 16:29:33 -070066import android.util.SparseIntArray;
67import android.view.Display;
Christine Franks55194dc2019-01-15 13:47:06 -080068import android.view.SurfaceControl;
Christine Franks9114f462019-01-04 11:27:30 -080069import android.view.accessibility.AccessibilityManager;
Justin Klaassen639214e2016-07-14 21:00:06 -070070import android.view.animation.AnimationUtils;
Daniel Solomona4ab5672019-01-22 19:35:55 -080071
Christine Franks39b03112018-07-03 14:46:07 -070072import com.android.internal.R;
Christine Franks57fdde82018-07-03 14:46:07 -070073import com.android.internal.annotations.VisibleForTesting;
Christine Franksf3529b22019-01-03 13:20:17 -080074import com.android.internal.util.DumpUtils;
Christine Franks57fdde82018-07-03 14:46:07 -070075import com.android.server.DisplayThread;
Justin Klaassen911e8892016-06-21 18:24:24 -070076import com.android.server.SystemService;
77import com.android.server.twilight.TwilightListener;
78import com.android.server.twilight.TwilightManager;
79import com.android.server.twilight.TwilightState;
Christine Franksa4ed3762019-01-24 15:37:04 -080080
Christine Franksf3529b22019-01-03 13:20:17 -080081import java.io.FileDescriptor;
Daniel Solomon8b72c5b2018-11-25 11:07:13 -080082import java.io.PrintWriter;
Christine Franksf3529b22019-01-03 13:20:17 -080083import java.lang.ref.WeakReference;
Christine Franks57fdde82018-07-03 14:46:07 -070084import java.time.DateTimeException;
85import java.time.Instant;
Christine Franks03213462017-08-25 13:57:26 -070086import java.time.LocalDateTime;
87import java.time.LocalTime;
88import java.time.ZoneId;
Christine Franks57fdde82018-07-03 14:46:07 -070089import java.time.format.DateTimeParseException;
Christine Franks8ad71492017-10-24 19:04:22 -070090
Justin Klaassen911e8892016-06-21 18:24:24 -070091/**
Christine Franks39b03112018-07-03 14:46:07 -070092 * Controls the display's color transforms.
Justin Klaassen911e8892016-06-21 18:24:24 -070093 */
Christine Franks57fdde82018-07-03 14:46:07 -070094public final class ColorDisplayService extends SystemService {
Justin Klaassen911e8892016-06-21 18:24:24 -070095
Christine Franks7119e992019-03-14 17:28:21 -070096 static final String TAG = "ColorDisplayService";
Christine Franks7b83b4282017-01-18 14:55:00 -080097
98 /**
Justin Klaassen639214e2016-07-14 21:00:06 -070099 * The identity matrix, used if one of the given matrices is {@code null}.
100 */
Christine Franks6caba0f2019-03-07 17:48:25 -0800101 static final float[] MATRIX_IDENTITY = new float[16];
Christine Franks57fdde82018-07-03 14:46:07 -0700102
Justin Klaassen639214e2016-07-14 21:00:06 -0700103 static {
104 Matrix.setIdentityM(MATRIX_IDENTITY, 0);
105 }
106
Christine Franks7119e992019-03-14 17:28:21 -0700107 /**
108 * The transition time, in milliseconds, for Night Display to turn on/off.
109 */
110 private static final long TRANSITION_DURATION = 3000L;
111
Christine Franks27912a32019-04-02 10:43:10 -0700112 private static final int MSG_USER_CHANGED = 0;
113 private static final int MSG_SET_UP = 1;
114 private static final int MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE = 2;
115 private static final int MSG_APPLY_NIGHT_DISPLAY_ANIMATED = 3;
116 private static final int MSG_APPLY_GLOBAL_SATURATION = 4;
117 private static final int MSG_APPLY_DISPLAY_WHITE_BALANCE = 5;
Christine Franks09c229e2018-12-14 10:37:40 -0800118
Justin Klaassen639214e2016-07-14 21:00:06 -0700119 /**
Christine Franks83cc5412018-07-03 14:46:07 -0700120 * Return value if a setting has not been set.
121 */
122 private static final int NOT_SET = -1;
123
124 /**
Justin Klaassen639214e2016-07-14 21:00:06 -0700125 * Evaluator used to animate color matrix transitions.
126 */
127 private static final ColorMatrixEvaluator COLOR_MATRIX_EVALUATOR = new ColorMatrixEvaluator();
128
Christine Franks83cc5412018-07-03 14:46:07 -0700129 private final NightDisplayTintController mNightDisplayTintController =
130 new NightDisplayTintController();
Christine Franks245ffd42018-11-16 13:45:14 -0800131
Long Ling1d3f1892019-02-06 12:34:02 -0800132 @VisibleForTesting
133 final DisplayWhiteBalanceTintController mDisplayWhiteBalanceTintController =
134 new DisplayWhiteBalanceTintController();
Christine Franks245ffd42018-11-16 13:45:14 -0800135
Christine Franks7119e992019-03-14 17:28:21 -0700136 private final TintController mGlobalSaturationTintController =
137 new GlobalSaturationTintController();
Christine Franks09c229e2018-12-14 10:37:40 -0800138
Christine Franks9114f462019-01-04 11:27:30 -0800139 /**
140 * Matrix and offset used for converting color to grayscale.
141 */
142 private static final float[] MATRIX_GRAYSCALE = new float[]{
143 .2126f, .2126f, .2126f, 0f,
144 .7152f, .7152f, .7152f, 0f,
145 .0722f, .0722f, .0722f, 0f,
146 0f, 0f, 0f, 1f
147 };
148
149 /**
150 * Matrix and offset used for luminance inversion. Represents a transform from RGB to YIQ color
151 * space, rotation around the Y axis by 180 degrees, transform back to RGB color space, and
152 * subtraction from 1. The last row represents a non-multiplied addition, see surfaceflinger's
153 * ProgramCache for full implementation details.
154 */
Christine Franksd154fe52019-01-04 17:17:45 -0800155 private static final float[] MATRIX_INVERT_COLOR = new float[]{
Christine Franks9114f462019-01-04 11:27:30 -0800156 0.402f, -0.598f, -0.599f, 0f,
157 -1.174f, -0.174f, -1.175f, 0f,
158 -0.228f, -0.228f, 0.772f, 0f,
159 1f, 1f, 1f, 1f
160 };
161
Justin Klaassen2696d992016-07-11 21:26:46 -0700162 private final Handler mHandler;
163
Christine Franksf3529b22019-01-03 13:20:17 -0800164 private final AppSaturationController mAppSaturationController = new AppSaturationController();
165
Justin Klaassen911e8892016-06-21 18:24:24 -0700166 private int mCurrentUser = UserHandle.USER_NULL;
Justin Klaassen2696d992016-07-11 21:26:46 -0700167 private ContentObserver mUserSetupObserver;
Justin Klaassen911e8892016-06-21 18:24:24 -0700168 private boolean mBootCompleted;
169
Christine Franks57fdde82018-07-03 14:46:07 -0700170 private ContentObserver mContentObserver;
Christine Franks57fdde82018-07-03 14:46:07 -0700171
Christine Franks245ffd42018-11-16 13:45:14 -0800172 private DisplayWhiteBalanceListener mDisplayWhiteBalanceListener;
173
Christine Franks57fdde82018-07-03 14:46:07 -0700174 private NightDisplayAutoMode mNightDisplayAutoMode;
Justin Klaassen911e8892016-06-21 18:24:24 -0700175
Daniel Solomon41ee35f2019-07-11 16:29:33 -0700176 /**
177 * Map of color modes -> display composition colorspace
178 */
179 private SparseIntArray mColorModeCompositionColorSpaces = null;
180
Christine Franks5397f032017-11-01 18:35:16 -0700181 public ColorDisplayService(Context context) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700182 super(context);
Christine Franks83cc5412018-07-03 14:46:07 -0700183 mHandler = new TintHandler(DisplayThread.get().getLooper());
Justin Klaassen911e8892016-06-21 18:24:24 -0700184 }
185
186 @Override
187 public void onStart() {
Christine Franks39b03112018-07-03 14:46:07 -0700188 publishBinderService(Context.COLOR_DISPLAY_SERVICE, new BinderService());
Christine Franks245ffd42018-11-16 13:45:14 -0800189 publishLocalService(ColorDisplayServiceInternal.class, new ColorDisplayServiceInternal());
Christine Franks0ada2772019-02-25 13:54:57 -0800190 publishLocalService(DisplayTransformManager.class, new DisplayTransformManager());
Justin Klaassen911e8892016-06-21 18:24:24 -0700191 }
192
193 @Override
Justin Klaassen2696d992016-07-11 21:26:46 -0700194 public void onBootPhase(int phase) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800195 if (phase >= PHASE_BOOT_COMPLETED) {
Justin Klaassen2696d992016-07-11 21:26:46 -0700196 mBootCompleted = true;
197
198 // Register listeners now that boot is complete.
199 if (mCurrentUser != UserHandle.USER_NULL && mUserSetupObserver == null) {
Christine Franks27912a32019-04-02 10:43:10 -0700200 mHandler.sendEmptyMessage(MSG_SET_UP);
Justin Klaassen2696d992016-07-11 21:26:46 -0700201 }
202 }
203 }
204
205 @Override
Justin Klaassen911e8892016-06-21 18:24:24 -0700206 public void onStartUser(int userHandle) {
207 super.onStartUser(userHandle);
208
Justin Klaassen911e8892016-06-21 18:24:24 -0700209 if (mCurrentUser == UserHandle.USER_NULL) {
Christine Franks27912a32019-04-02 10:43:10 -0700210 final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
211 message.arg1 = userHandle;
212 mHandler.sendMessage(message);
Justin Klaassen911e8892016-06-21 18:24:24 -0700213 }
214 }
215
216 @Override
217 public void onSwitchUser(int userHandle) {
218 super.onSwitchUser(userHandle);
219
Christine Franks27912a32019-04-02 10:43:10 -0700220 final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
221 message.arg1 = userHandle;
222 mHandler.sendMessage(message);
Justin Klaassen911e8892016-06-21 18:24:24 -0700223 }
224
225 @Override
226 public void onStopUser(int userHandle) {
227 super.onStopUser(userHandle);
228
Justin Klaassen911e8892016-06-21 18:24:24 -0700229 if (mCurrentUser == userHandle) {
Christine Franks27912a32019-04-02 10:43:10 -0700230 final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
231 message.arg1 = UserHandle.USER_NULL;
232 mHandler.sendMessage(message);
Justin Klaassen911e8892016-06-21 18:24:24 -0700233 }
234 }
235
Christine Franks771f5fa2019-06-12 13:31:50 -0700236 @VisibleForTesting void onUserChanged(int userHandle) {
Justin Klaassen2696d992016-07-11 21:26:46 -0700237 final ContentResolver cr = getContext().getContentResolver();
Justin Klaassen911e8892016-06-21 18:24:24 -0700238
Justin Klaassen2696d992016-07-11 21:26:46 -0700239 if (mCurrentUser != UserHandle.USER_NULL) {
240 if (mUserSetupObserver != null) {
241 cr.unregisterContentObserver(mUserSetupObserver);
242 mUserSetupObserver = null;
243 } else if (mBootCompleted) {
244 tearDown();
245 }
246 }
247
248 mCurrentUser = userHandle;
249
250 if (mCurrentUser != UserHandle.USER_NULL) {
251 if (!isUserSetupCompleted(cr, mCurrentUser)) {
252 mUserSetupObserver = new ContentObserver(mHandler) {
253 @Override
254 public void onChange(boolean selfChange, Uri uri) {
255 if (isUserSetupCompleted(cr, mCurrentUser)) {
256 cr.unregisterContentObserver(this);
257 mUserSetupObserver = null;
258
259 if (mBootCompleted) {
260 setUp();
261 }
262 }
263 }
264 };
265 cr.registerContentObserver(Secure.getUriFor(Secure.USER_SETUP_COMPLETE),
Christine Franks39b03112018-07-03 14:46:07 -0700266 false /* notifyForDescendants */, mUserSetupObserver, mCurrentUser);
Justin Klaassen2696d992016-07-11 21:26:46 -0700267 } else if (mBootCompleted) {
268 setUp();
Justin Klaassen911e8892016-06-21 18:24:24 -0700269 }
270 }
271 }
272
Justin Klaassen2696d992016-07-11 21:26:46 -0700273 private static boolean isUserSetupCompleted(ContentResolver cr, int userHandle) {
274 return Secure.getIntForUser(cr, Secure.USER_SETUP_COMPLETE, 0, userHandle) == 1;
275 }
276
Daniel Solomon41ee35f2019-07-11 16:29:33 -0700277 private void setUpDisplayCompositionColorSpaces(Resources res) {
278 mColorModeCompositionColorSpaces = null;
279
280 final int[] colorModes = res.getIntArray(R.array.config_displayCompositionColorModes);
281 if (colorModes == null) {
282 return;
283 }
284
285 final int[] compSpaces = res.getIntArray(R.array.config_displayCompositionColorSpaces);
286 if (compSpaces == null) {
287 return;
288 }
289
290 if (colorModes.length != compSpaces.length) {
291 Slog.e(TAG, "Number of composition color spaces doesn't match specified color modes");
292 return;
293 }
294
295 mColorModeCompositionColorSpaces = new SparseIntArray(colorModes.length);
296 for (int i = 0; i < colorModes.length; i++) {
297 mColorModeCompositionColorSpaces.put(colorModes[i], compSpaces[i]);
298 }
299 }
300
Justin Klaassen2696d992016-07-11 21:26:46 -0700301 private void setUp() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700302 Slog.d(TAG, "setUp: currentUser=" + mCurrentUser);
303
Christine Franks57fdde82018-07-03 14:46:07 -0700304 // Listen for external changes to any of the settings.
305 if (mContentObserver == null) {
Christine Franks27912a32019-04-02 10:43:10 -0700306 mContentObserver = new ContentObserver(mHandler) {
Christine Franks57fdde82018-07-03 14:46:07 -0700307 @Override
308 public void onChange(boolean selfChange, Uri uri) {
309 super.onChange(selfChange, uri);
310
311 final String setting = uri == null ? null : uri.getLastPathSegment();
312 if (setting != null) {
313 switch (setting) {
314 case Secure.NIGHT_DISPLAY_ACTIVATED:
Christine Franks78a4dd42019-02-08 11:09:30 -0800315 final boolean activated = mNightDisplayTintController
316 .isActivatedSetting();
Christine Franks83cc5412018-07-03 14:46:07 -0700317 if (mNightDisplayTintController.isActivatedStateNotSet()
318 || mNightDisplayTintController.isActivated() != activated) {
Christine Franks78a4dd42019-02-08 11:09:30 -0800319 mNightDisplayTintController.setActivated(activated);
Christine Franks83cc5412018-07-03 14:46:07 -0700320 }
Christine Franks57fdde82018-07-03 14:46:07 -0700321 break;
322 case Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE:
Christine Franks78a4dd42019-02-08 11:09:30 -0800323 final int temperature = mNightDisplayTintController
324 .getColorTemperatureSetting();
Christine Franks83cc5412018-07-03 14:46:07 -0700325 if (mNightDisplayTintController.getColorTemperature()
326 != temperature) {
327 mNightDisplayTintController
328 .onColorTemperatureChanged(temperature);
329 }
Christine Franks57fdde82018-07-03 14:46:07 -0700330 break;
331 case Secure.NIGHT_DISPLAY_AUTO_MODE:
Christine Franks83cc5412018-07-03 14:46:07 -0700332 onNightDisplayAutoModeChanged(getNightDisplayAutoModeInternal());
Christine Franks57fdde82018-07-03 14:46:07 -0700333 break;
334 case Secure.NIGHT_DISPLAY_CUSTOM_START_TIME:
335 onNightDisplayCustomStartTimeChanged(
Christine Franks83cc5412018-07-03 14:46:07 -0700336 getNightDisplayCustomStartTimeInternal().getLocalTime());
Christine Franks57fdde82018-07-03 14:46:07 -0700337 break;
338 case Secure.NIGHT_DISPLAY_CUSTOM_END_TIME:
339 onNightDisplayCustomEndTimeChanged(
Christine Franks83cc5412018-07-03 14:46:07 -0700340 getNightDisplayCustomEndTimeInternal().getLocalTime());
Christine Franks57fdde82018-07-03 14:46:07 -0700341 break;
342 case System.DISPLAY_COLOR_MODE:
Christine Franks71e003e2019-01-24 14:40:20 -0800343 onDisplayColorModeChanged(getColorModeInternal());
Christine Franks57fdde82018-07-03 14:46:07 -0700344 break;
Christine Franks57fdde82018-07-03 14:46:07 -0700345 case Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED:
Christine Franks9114f462019-01-04 11:27:30 -0800346 onAccessibilityInversionChanged();
347 onAccessibilityActivated();
348 break;
349 case Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED:
350 onAccessibilityDaltonizerChanged();
351 onAccessibilityActivated();
352 break;
353 case Secure.ACCESSIBILITY_DISPLAY_DALTONIZER:
354 onAccessibilityDaltonizerChanged();
Christine Franks57fdde82018-07-03 14:46:07 -0700355 break;
Christine Franks245ffd42018-11-16 13:45:14 -0800356 case Secure.DISPLAY_WHITE_BALANCE_ENABLED:
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800357 updateDisplayWhiteBalanceStatus();
Christine Franks245ffd42018-11-16 13:45:14 -0800358 break;
Christine Franks57fdde82018-07-03 14:46:07 -0700359 }
360 }
361 }
362 };
363 }
364 final ContentResolver cr = getContext().getContentResolver();
365 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_ACTIVATED),
366 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
367 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE),
368 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
369 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_AUTO_MODE),
370 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
371 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_CUSTOM_START_TIME),
372 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
373 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_CUSTOM_END_TIME),
374 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
375 cr.registerContentObserver(System.getUriFor(System.DISPLAY_COLOR_MODE),
376 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
377 cr.registerContentObserver(
378 Secure.getUriFor(Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED),
379 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
380 cr.registerContentObserver(
381 Secure.getUriFor(Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED),
382 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
Christine Franks9114f462019-01-04 11:27:30 -0800383 cr.registerContentObserver(
384 Secure.getUriFor(Secure.ACCESSIBILITY_DISPLAY_DALTONIZER),
385 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
Christine Franks245ffd42018-11-16 13:45:14 -0800386 cr.registerContentObserver(Secure.getUriFor(Secure.DISPLAY_WHITE_BALANCE_ENABLED),
387 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
Justin Klaassen911e8892016-06-21 18:24:24 -0700388
Christine Franks11e63152019-03-14 11:16:06 -0700389 // Apply the accessibility settings first, since they override most other settings.
390 onAccessibilityInversionChanged();
391 onAccessibilityDaltonizerChanged();
392
Daniel Solomon41ee35f2019-07-11 16:29:33 -0700393 setUpDisplayCompositionColorSpaces(getContext().getResources());
394
Christine Frankscf388c22018-05-15 15:48:10 -0700395 // Set the color mode, if valid, and immediately apply the updated tint matrix based on the
396 // existing activated state. This ensures consistency of tint across the color mode change.
Christine Franks71e003e2019-01-24 14:40:20 -0800397 onDisplayColorModeChanged(getColorModeInternal());
Christine Frankscf388c22018-05-15 15:48:10 -0700398
Christine Franksa4ed3762019-01-24 15:37:04 -0800399 if (mNightDisplayTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800400 // Reset the activated state.
401 mNightDisplayTintController.setActivated(null);
Christine Frankscf388c22018-05-15 15:48:10 -0700402
Christine Franks245ffd42018-11-16 13:45:14 -0800403 // Prepare the night display color transformation matrix.
404 mNightDisplayTintController
405 .setUp(getContext(), DisplayTransformManager.needsLinearColorMatrix());
Christine Franks78a4dd42019-02-08 11:09:30 -0800406 mNightDisplayTintController
407 .setMatrix(mNightDisplayTintController.getColorTemperatureSetting());
Christine Franks8ad71492017-10-24 19:04:22 -0700408
Christine Franks245ffd42018-11-16 13:45:14 -0800409 // Initialize the current auto mode.
Christine Franks83cc5412018-07-03 14:46:07 -0700410 onNightDisplayAutoModeChanged(getNightDisplayAutoModeInternal());
Christine Franks6418d0b2017-02-13 09:48:00 -0800411
Christine Franks83cc5412018-07-03 14:46:07 -0700412 // Force the initialization of the current saved activation state.
Christine Franks245ffd42018-11-16 13:45:14 -0800413 if (mNightDisplayTintController.isActivatedStateNotSet()) {
Christine Franks78a4dd42019-02-08 11:09:30 -0800414 mNightDisplayTintController
415 .setActivated(mNightDisplayTintController.isActivatedSetting());
Christine Franks245ffd42018-11-16 13:45:14 -0800416 }
417 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700418
Christine Franksa4ed3762019-01-24 15:37:04 -0800419 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800420 // Prepare the display white balance transform matrix.
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800421 mDisplayWhiteBalanceTintController.setUp(getContext(), true /* needsLinear */);
Christine Franks245ffd42018-11-16 13:45:14 -0800422
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800423 updateDisplayWhiteBalanceStatus();
Justin Klaassen911e8892016-06-21 18:24:24 -0700424 }
425 }
426
Justin Klaassen2696d992016-07-11 21:26:46 -0700427 private void tearDown() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700428 Slog.d(TAG, "tearDown: currentUser=" + mCurrentUser);
429
Keun young Parka2162f52019-05-29 11:33:11 -0700430 if (mContentObserver != null) {
431 getContext().getContentResolver().unregisterContentObserver(mContentObserver);
432 }
Christine Franks57fdde82018-07-03 14:46:07 -0700433
Christine Franksa4ed3762019-01-24 15:37:04 -0800434 if (mNightDisplayTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800435 if (mNightDisplayAutoMode != null) {
436 mNightDisplayAutoMode.onStop();
437 mNightDisplayAutoMode = null;
438 }
439 mNightDisplayTintController.endAnimator();
Justin Klaassen911e8892016-06-21 18:24:24 -0700440 }
441
Christine Franksa4ed3762019-01-24 15:37:04 -0800442 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800443 mDisplayWhiteBalanceTintController.endAnimator();
Justin Klaassen639214e2016-07-14 21:00:06 -0700444 }
Christine Franks6d21d342019-02-07 15:09:03 -0800445
446 if (mGlobalSaturationTintController.isAvailable(getContext())) {
447 mGlobalSaturationTintController.setActivated(null);
448 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700449 }
450
Christine Franks57fdde82018-07-03 14:46:07 -0700451 private void onNightDisplayAutoModeChanged(int autoMode) {
452 Slog.d(TAG, "onNightDisplayAutoModeChanged: autoMode=" + autoMode);
Justin Klaassenec8837a2016-08-23 12:04:42 -0700453
Christine Franks57fdde82018-07-03 14:46:07 -0700454 if (mNightDisplayAutoMode != null) {
455 mNightDisplayAutoMode.onStop();
456 mNightDisplayAutoMode = null;
Justin Klaassen911e8892016-06-21 18:24:24 -0700457 }
458
Christine Franks83cc5412018-07-03 14:46:07 -0700459 if (autoMode == AUTO_MODE_CUSTOM_TIME) {
Christine Franks57fdde82018-07-03 14:46:07 -0700460 mNightDisplayAutoMode = new CustomNightDisplayAutoMode();
Christine Franks83cc5412018-07-03 14:46:07 -0700461 } else if (autoMode == AUTO_MODE_TWILIGHT) {
Christine Franks57fdde82018-07-03 14:46:07 -0700462 mNightDisplayAutoMode = new TwilightNightDisplayAutoMode();
Justin Klaassen911e8892016-06-21 18:24:24 -0700463 }
464
Christine Franks57fdde82018-07-03 14:46:07 -0700465 if (mNightDisplayAutoMode != null) {
466 mNightDisplayAutoMode.onStart();
Justin Klaassen911e8892016-06-21 18:24:24 -0700467 }
468 }
469
Christine Franks57fdde82018-07-03 14:46:07 -0700470 private void onNightDisplayCustomStartTimeChanged(LocalTime startTime) {
471 Slog.d(TAG, "onNightDisplayCustomStartTimeChanged: startTime=" + startTime);
Justin Klaassenec8837a2016-08-23 12:04:42 -0700472
Christine Franks57fdde82018-07-03 14:46:07 -0700473 if (mNightDisplayAutoMode != null) {
474 mNightDisplayAutoMode.onCustomStartTimeChanged(startTime);
Justin Klaassen911e8892016-06-21 18:24:24 -0700475 }
476 }
477
Christine Franks57fdde82018-07-03 14:46:07 -0700478 private void onNightDisplayCustomEndTimeChanged(LocalTime endTime) {
479 Slog.d(TAG, "onNightDisplayCustomEndTimeChanged: endTime=" + endTime);
Justin Klaassenec8837a2016-08-23 12:04:42 -0700480
Christine Franks57fdde82018-07-03 14:46:07 -0700481 if (mNightDisplayAutoMode != null) {
482 mNightDisplayAutoMode.onCustomEndTimeChanged(endTime);
Justin Klaassen911e8892016-06-21 18:24:24 -0700483 }
484 }
485
Daniel Solomon41ee35f2019-07-11 16:29:33 -0700486 private int getCompositionColorSpace(int mode) {
487 if (mColorModeCompositionColorSpaces == null) {
488 return Display.COLOR_MODE_INVALID;
489 }
490
491 return mColorModeCompositionColorSpaces.get(mode, Display.COLOR_MODE_INVALID);
492 }
493
Christine Franks57fdde82018-07-03 14:46:07 -0700494 private void onDisplayColorModeChanged(int mode) {
Christine Franks83cc5412018-07-03 14:46:07 -0700495 if (mode == NOT_SET) {
Christine Frankscf388c22018-05-15 15:48:10 -0700496 return;
497 }
498
Christine Franks245ffd42018-11-16 13:45:14 -0800499 mNightDisplayTintController.cancelAnimator();
500 mDisplayWhiteBalanceTintController.cancelAnimator();
501
Christine Franksa4ed3762019-01-24 15:37:04 -0800502 if (mNightDisplayTintController.isAvailable(getContext())) {
503 mNightDisplayTintController
504 .setUp(getContext(), DisplayTransformManager.needsLinearColorMatrix(mode));
Christine Franks78a4dd42019-02-08 11:09:30 -0800505 mNightDisplayTintController
506 .setMatrix(mNightDisplayTintController.getColorTemperatureSetting());
Christine Franksa4ed3762019-01-24 15:37:04 -0800507 }
Christine Franks245ffd42018-11-16 13:45:14 -0800508
Anthony Han2c2e4a82019-06-07 11:13:35 -0700509 // dtm.setColorMode() needs to be called before
510 // updateDisplayWhiteBalanceStatus(), this is because the latter calls
511 // DisplayTransformManager.needsLinearColorMatrix(), therefore it is dependent
512 // on the state of DisplayTransformManager.
513 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
Daniel Solomon41ee35f2019-07-11 16:29:33 -0700514 dtm.setColorMode(mode, mNightDisplayTintController.getMatrix(),
515 getCompositionColorSpace(mode));
Anthony Han2c2e4a82019-06-07 11:13:35 -0700516
Christine Franks18ac4e22019-04-05 18:30:50 -0700517 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
518 updateDisplayWhiteBalanceStatus();
519 }
Christine Franks8ad71492017-10-24 19:04:22 -0700520 }
521
Christine Franks9114f462019-01-04 11:27:30 -0800522 private void onAccessibilityActivated() {
Christine Franks71e003e2019-01-24 14:40:20 -0800523 onDisplayColorModeChanged(getColorModeInternal());
Daniel Solomon317a3572018-03-30 18:36:37 -0700524 }
525
Daniel Solomonff24ba92019-04-11 19:29:31 -0700526 private boolean isAccessiblityDaltonizerEnabled() {
527 return Secure.getIntForUser(getContext().getContentResolver(),
528 Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0, mCurrentUser) != 0;
529 }
530
531 private boolean isAccessiblityInversionEnabled() {
532 return Secure.getIntForUser(getContext().getContentResolver(),
533 Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, 0, mCurrentUser) != 0;
534 }
535
536 private boolean isAccessibilityEnabled() {
537 return isAccessiblityDaltonizerEnabled() || isAccessiblityInversionEnabled();
538 }
539
Christine Franks9114f462019-01-04 11:27:30 -0800540 /**
541 * Apply the accessibility daltonizer transform based on the settings value.
542 */
543 private void onAccessibilityDaltonizerChanged() {
Christine Franks27912a32019-04-02 10:43:10 -0700544 if (mCurrentUser == UserHandle.USER_NULL) {
545 return;
546 }
Daniel Solomonff24ba92019-04-11 19:29:31 -0700547 final int daltonizerMode = isAccessiblityDaltonizerEnabled()
548 ? Secure.getIntForUser(getContext().getContentResolver(),
549 Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
550 AccessibilityManager.DALTONIZER_CORRECT_DEUTERANOMALY, mCurrentUser)
Christine Franks9114f462019-01-04 11:27:30 -0800551 : AccessibilityManager.DALTONIZER_DISABLED;
552
553 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
554 if (daltonizerMode == AccessibilityManager.DALTONIZER_SIMULATE_MONOCHROMACY) {
555 // Monochromacy isn't supported by the native Daltonizer implementation; use grayscale.
556 dtm.setColorMatrix(DisplayTransformManager.LEVEL_COLOR_MATRIX_GRAYSCALE,
557 MATRIX_GRAYSCALE);
558 dtm.setDaltonizerMode(AccessibilityManager.DALTONIZER_DISABLED);
559 } else {
560 dtm.setColorMatrix(DisplayTransformManager.LEVEL_COLOR_MATRIX_GRAYSCALE, null);
561 dtm.setDaltonizerMode(daltonizerMode);
562 }
563 }
564
565 /**
566 * Apply the accessibility inversion transform based on the settings value.
567 */
568 private void onAccessibilityInversionChanged() {
Christine Franks27912a32019-04-02 10:43:10 -0700569 if (mCurrentUser == UserHandle.USER_NULL) {
570 return;
571 }
Christine Franks9114f462019-01-04 11:27:30 -0800572 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
573 dtm.setColorMatrix(DisplayTransformManager.LEVEL_COLOR_MATRIX_INVERT_COLOR,
Daniel Solomonff24ba92019-04-11 19:29:31 -0700574 isAccessiblityInversionEnabled() ? MATRIX_INVERT_COLOR : null);
Christine Franks9114f462019-01-04 11:27:30 -0800575 }
Christine Franks8ad71492017-10-24 19:04:22 -0700576
Christine Franks6418d0b2017-02-13 09:48:00 -0800577 /**
578 * Applies current color temperature matrix, or removes it if deactivated.
579 *
580 * @param immediate {@code true} skips transition animation
581 */
Christine Franks245ffd42018-11-16 13:45:14 -0800582 private void applyTint(TintController tintController, boolean immediate) {
583 tintController.cancelAnimator();
Christine Franks6418d0b2017-02-13 09:48:00 -0800584
Christine Franks6418d0b2017-02-13 09:48:00 -0800585 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
Christine Franks245ffd42018-11-16 13:45:14 -0800586 final float[] from = dtm.getColorMatrix(tintController.getLevel());
587 final float[] to = tintController.getMatrix();
Christine Franks6418d0b2017-02-13 09:48:00 -0800588
589 if (immediate) {
Christine Franks245ffd42018-11-16 13:45:14 -0800590 dtm.setColorMatrix(tintController.getLevel(), to);
Christine Franks6418d0b2017-02-13 09:48:00 -0800591 } else {
Christine Franks245ffd42018-11-16 13:45:14 -0800592 tintController.setAnimator(ValueAnimator.ofObject(COLOR_MATRIX_EVALUATOR,
593 from == null ? MATRIX_IDENTITY : from, to));
594 tintController.getAnimator().setDuration(TRANSITION_DURATION);
595 tintController.getAnimator().setInterpolator(AnimationUtils.loadInterpolator(
Christine Franks6418d0b2017-02-13 09:48:00 -0800596 getContext(), android.R.interpolator.fast_out_slow_in));
Christine Franks245ffd42018-11-16 13:45:14 -0800597 tintController.getAnimator().addUpdateListener((ValueAnimator animator) -> {
598 final float[] value = (float[]) animator.getAnimatedValue();
599 dtm.setColorMatrix(tintController.getLevel(), value);
Christine Franks6418d0b2017-02-13 09:48:00 -0800600 });
Christine Franks245ffd42018-11-16 13:45:14 -0800601 tintController.getAnimator().addListener(new AnimatorListenerAdapter() {
Christine Franks6418d0b2017-02-13 09:48:00 -0800602
603 private boolean mIsCancelled;
604
605 @Override
606 public void onAnimationCancel(Animator animator) {
607 mIsCancelled = true;
608 }
609
610 @Override
611 public void onAnimationEnd(Animator animator) {
612 if (!mIsCancelled) {
613 // Ensure final color matrix is set at the end of the animation. If the
614 // animation is cancelled then don't set the final color matrix so the new
615 // animator can pick up from where this one left off.
Christine Franks245ffd42018-11-16 13:45:14 -0800616 dtm.setColorMatrix(tintController.getLevel(), to);
Christine Franks6418d0b2017-02-13 09:48:00 -0800617 }
Christine Franks245ffd42018-11-16 13:45:14 -0800618 tintController.setAnimator(null);
Christine Franks6418d0b2017-02-13 09:48:00 -0800619 }
620 });
Christine Franks245ffd42018-11-16 13:45:14 -0800621 tintController.getAnimator().start();
Christine Franks6418d0b2017-02-13 09:48:00 -0800622 }
623 }
624
625 /**
Christine Franks39b03112018-07-03 14:46:07 -0700626 * Returns the first date time corresponding to the local time that occurs before the provided
627 * date time.
Christine Franks03213462017-08-25 13:57:26 -0700628 *
629 * @param compareTime the LocalDateTime to compare against
630 * @return the prior LocalDateTime corresponding to this local time
631 */
Christine Franks57fdde82018-07-03 14:46:07 -0700632 @VisibleForTesting
633 static LocalDateTime getDateTimeBefore(LocalTime localTime, LocalDateTime compareTime) {
Christine Franks03213462017-08-25 13:57:26 -0700634 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
635 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
636
637 // Check if the local time has passed, if so return the same time yesterday.
638 return ldt.isAfter(compareTime) ? ldt.minusDays(1) : ldt;
639 }
640
641 /**
Christine Franks39b03112018-07-03 14:46:07 -0700642 * Returns the first date time corresponding to this local time that occurs after the provided
643 * date time.
Christine Franks03213462017-08-25 13:57:26 -0700644 *
645 * @param compareTime the LocalDateTime to compare against
646 * @return the next LocalDateTime corresponding to this local time
647 */
Christine Franks57fdde82018-07-03 14:46:07 -0700648 @VisibleForTesting
649 static LocalDateTime getDateTimeAfter(LocalTime localTime, LocalDateTime compareTime) {
Christine Franks03213462017-08-25 13:57:26 -0700650 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
651 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
652
653 // Check if the local time has passed, if so return the same time tomorrow.
654 return ldt.isBefore(compareTime) ? ldt.plusDays(1) : ldt;
655 }
656
Long Ling1d3f1892019-02-06 12:34:02 -0800657 @VisibleForTesting
658 void updateDisplayWhiteBalanceStatus() {
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800659 boolean oldActivated = mDisplayWhiteBalanceTintController.isActivated();
Christine Franks0ada2772019-02-25 13:54:57 -0800660 mDisplayWhiteBalanceTintController.setActivated(isDisplayWhiteBalanceSettingEnabled()
661 && !mNightDisplayTintController.isActivated()
Daniel Solomonff24ba92019-04-11 19:29:31 -0700662 && !isAccessibilityEnabled()
Christine Franks0ada2772019-02-25 13:54:57 -0800663 && DisplayTransformManager.needsLinearColorMatrix());
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800664 boolean activated = mDisplayWhiteBalanceTintController.isActivated();
665
666 if (mDisplayWhiteBalanceListener != null && oldActivated != activated) {
667 mDisplayWhiteBalanceListener.onDisplayWhiteBalanceStatusChanged(activated);
Christine Franks245ffd42018-11-16 13:45:14 -0800668 }
Daniel Solomon86508f82019-01-18 19:01:02 -0800669
670 // If disabled, clear the tint. If enabled, do nothing more here and let the next
671 // temperature update set the correct tint.
672 if (!activated) {
Christine Franksc7fb9452019-02-04 08:45:33 -0800673 mHandler.sendEmptyMessage(MSG_APPLY_DISPLAY_WHITE_BALANCE);
Daniel Solomon86508f82019-01-18 19:01:02 -0800674 }
Christine Franks245ffd42018-11-16 13:45:14 -0800675 }
676
Christine Franks66783a82019-03-28 11:45:56 -0700677 private boolean setDisplayWhiteBalanceSettingEnabled(boolean enabled) {
678 if (mCurrentUser == UserHandle.USER_NULL) {
679 return false;
680 }
681 return Secure.putIntForUser(getContext().getContentResolver(),
682 Secure.DISPLAY_WHITE_BALANCE_ENABLED,
683 enabled ? 1 : 0, mCurrentUser);
684 }
685
Christine Franks245ffd42018-11-16 13:45:14 -0800686 private boolean isDisplayWhiteBalanceSettingEnabled() {
Christine Franks27912a32019-04-02 10:43:10 -0700687 if (mCurrentUser == UserHandle.USER_NULL) {
688 return false;
689 }
Christine Franks245ffd42018-11-16 13:45:14 -0800690 return Secure.getIntForUser(getContext().getContentResolver(),
Christine Franks18ac4e22019-04-05 18:30:50 -0700691 Secure.DISPLAY_WHITE_BALANCE_ENABLED,
692 getContext().getResources()
693 .getBoolean(R.bool.config_displayWhiteBalanceEnabledDefault) ? 1
694 : 0,
695 mCurrentUser) == 1;
Christine Franks245ffd42018-11-16 13:45:14 -0800696 }
697
Christine Franks39b03112018-07-03 14:46:07 -0700698 private boolean isDeviceColorManagedInternal() {
699 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
700 return dtm.isDeviceColorManaged();
701 }
702
Christine Franks55194dc2019-01-15 13:47:06 -0800703 private int getTransformCapabilitiesInternal() {
704 int availabilityFlags = ColorDisplayManager.CAPABILITY_NONE;
705 if (SurfaceControl.getProtectedContentSupport()) {
706 availabilityFlags |= ColorDisplayManager.CAPABILITY_PROTECTED_CONTENT;
707 }
708 final Resources res = getContext().getResources();
709 if (res.getBoolean(R.bool.config_setColorTransformAccelerated)) {
710 availabilityFlags |= ColorDisplayManager.CAPABILITY_HARDWARE_ACCELERATION_GLOBAL;
711 }
712 if (res.getBoolean(R.bool.config_setColorTransformAcceleratedPerLayer)) {
713 availabilityFlags |= ColorDisplayManager.CAPABILITY_HARDWARE_ACCELERATION_PER_APP;
714 }
715 return availabilityFlags;
716 }
717
Christine Franks83cc5412018-07-03 14:46:07 -0700718 private boolean setNightDisplayAutoModeInternal(@AutoMode int autoMode) {
719 if (getNightDisplayAutoModeInternal() != autoMode) {
720 Secure.putStringForUser(getContext().getContentResolver(),
721 Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
722 null,
723 mCurrentUser);
724 }
725 return Secure.putIntForUser(getContext().getContentResolver(),
726 Secure.NIGHT_DISPLAY_AUTO_MODE, autoMode, mCurrentUser);
727 }
728
729 private int getNightDisplayAutoModeInternal() {
730 int autoMode = getNightDisplayAutoModeRawInternal();
731 if (autoMode == NOT_SET) {
732 autoMode = getContext().getResources().getInteger(
733 R.integer.config_defaultNightDisplayAutoMode);
734 }
735 if (autoMode != AUTO_MODE_DISABLED
736 && autoMode != AUTO_MODE_CUSTOM_TIME
737 && autoMode != AUTO_MODE_TWILIGHT) {
738 Slog.e(TAG, "Invalid autoMode: " + autoMode);
739 autoMode = AUTO_MODE_DISABLED;
740 }
741 return autoMode;
742 }
743
744 private int getNightDisplayAutoModeRawInternal() {
Christine Franks27912a32019-04-02 10:43:10 -0700745 if (mCurrentUser == UserHandle.USER_NULL) {
746 return NOT_SET;
747 }
Christine Franks83cc5412018-07-03 14:46:07 -0700748 return Secure
749 .getIntForUser(getContext().getContentResolver(), Secure.NIGHT_DISPLAY_AUTO_MODE,
750 NOT_SET, mCurrentUser);
751 }
752
753 private Time getNightDisplayCustomStartTimeInternal() {
754 int startTimeValue = Secure.getIntForUser(getContext().getContentResolver(),
755 Secure.NIGHT_DISPLAY_CUSTOM_START_TIME, NOT_SET, mCurrentUser);
756 if (startTimeValue == NOT_SET) {
757 startTimeValue = getContext().getResources().getInteger(
758 R.integer.config_defaultNightDisplayCustomStartTime);
759 }
760 return new Time(LocalTime.ofSecondOfDay(startTimeValue / 1000));
761 }
762
763 private boolean setNightDisplayCustomStartTimeInternal(Time startTime) {
764 return Secure.putIntForUser(getContext().getContentResolver(),
765 Secure.NIGHT_DISPLAY_CUSTOM_START_TIME,
766 startTime.getLocalTime().toSecondOfDay() * 1000,
767 mCurrentUser);
768 }
769
770 private Time getNightDisplayCustomEndTimeInternal() {
771 int endTimeValue = Secure.getIntForUser(getContext().getContentResolver(),
772 Secure.NIGHT_DISPLAY_CUSTOM_END_TIME, NOT_SET, mCurrentUser);
773 if (endTimeValue == NOT_SET) {
774 endTimeValue = getContext().getResources().getInteger(
775 R.integer.config_defaultNightDisplayCustomEndTime);
776 }
777 return new Time(LocalTime.ofSecondOfDay(endTimeValue / 1000));
778 }
779
780 private boolean setNightDisplayCustomEndTimeInternal(Time endTime) {
781 return Secure.putIntForUser(getContext().getContentResolver(),
782 Secure.NIGHT_DISPLAY_CUSTOM_END_TIME, endTime.getLocalTime().toSecondOfDay() * 1000,
783 mCurrentUser);
784 }
785
Christine Franks57fdde82018-07-03 14:46:07 -0700786 /**
787 * Returns the last time the night display transform activation state was changed, or {@link
788 * LocalDateTime#MIN} if night display has never been activated.
789 */
Christine Franks245ffd42018-11-16 13:45:14 -0800790 private LocalDateTime getNightDisplayLastActivatedTimeSetting() {
Christine Franks57fdde82018-07-03 14:46:07 -0700791 final ContentResolver cr = getContext().getContentResolver();
792 final String lastActivatedTime = Secure.getStringForUser(
793 cr, Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME, getContext().getUserId());
794 if (lastActivatedTime != null) {
795 try {
796 return LocalDateTime.parse(lastActivatedTime);
797 } catch (DateTimeParseException ignored) {
798 }
799 // Uses the old epoch time.
800 try {
801 return LocalDateTime.ofInstant(
802 Instant.ofEpochMilli(Long.parseLong(lastActivatedTime)),
803 ZoneId.systemDefault());
804 } catch (DateTimeException | NumberFormatException ignored) {
805 }
806 }
807 return LocalDateTime.MIN;
808 }
809
Christine Franksf3529b22019-01-03 13:20:17 -0800810 private boolean setAppSaturationLevelInternal(String packageName, int saturationLevel) {
811 return mAppSaturationController
812 .setSaturationLevel(packageName, mCurrentUser, saturationLevel);
813 }
814
Christine Franksd154fe52019-01-04 17:17:45 -0800815 private void setColorModeInternal(@ColorMode int colorMode) {
816 if (!isColorModeAvailable(colorMode)) {
817 throw new IllegalArgumentException("Invalid colorMode: " + colorMode);
818 }
819 System.putIntForUser(getContext().getContentResolver(), System.DISPLAY_COLOR_MODE,
820 colorMode,
821 mCurrentUser);
822 }
823
Christine Franks71e003e2019-01-24 14:40:20 -0800824 private @ColorMode int getColorModeInternal() {
Christine Franksd154fe52019-01-04 17:17:45 -0800825 final ContentResolver cr = getContext().getContentResolver();
Daniel Solomonff24ba92019-04-11 19:29:31 -0700826 if (isAccessibilityEnabled()) {
Christine Franksd154fe52019-01-04 17:17:45 -0800827 // There are restrictions on the available color modes combined with a11y transforms.
Christine Franksb8d03a52019-05-08 15:08:21 -0700828 final int a11yColorMode = getContext().getResources().getInteger(
829 R.integer.config_accessibilityColorMode);
830 if (a11yColorMode >= 0) {
831 return a11yColorMode;
Christine Franksd154fe52019-01-04 17:17:45 -0800832 }
833 }
834
835 int colorMode = System.getIntForUser(cr, System.DISPLAY_COLOR_MODE, -1, mCurrentUser);
836 if (colorMode == -1) {
837 // There might be a system property controlling color mode that we need to respect; if
838 // not, this will set a suitable default.
839 colorMode = getCurrentColorModeFromSystemProperties();
840 }
841
842 // This happens when a color mode is no longer available (e.g., after system update or B&R)
843 // or the device does not support any color mode.
844 if (!isColorModeAvailable(colorMode)) {
845 if (colorMode == COLOR_MODE_BOOSTED && isColorModeAvailable(COLOR_MODE_NATURAL)) {
846 colorMode = COLOR_MODE_NATURAL;
847 } else if (colorMode == COLOR_MODE_SATURATED
848 && isColorModeAvailable(COLOR_MODE_AUTOMATIC)) {
849 colorMode = COLOR_MODE_AUTOMATIC;
850 } else if (colorMode == COLOR_MODE_AUTOMATIC
851 && isColorModeAvailable(COLOR_MODE_SATURATED)) {
852 colorMode = COLOR_MODE_SATURATED;
853 } else {
854 colorMode = -1;
855 }
856 }
857
858 return colorMode;
859 }
860
861 /**
862 * Get the current color mode from system properties, or return -1 if invalid.
863 *
Christine Franks0ada2772019-02-25 13:54:57 -0800864 * See {@link DisplayTransformManager}
Christine Franksd154fe52019-01-04 17:17:45 -0800865 */
Christine Franks78a4dd42019-02-08 11:09:30 -0800866 private @ColorMode int getCurrentColorModeFromSystemProperties() {
Christine Franksd154fe52019-01-04 17:17:45 -0800867 final int displayColorSetting = SystemProperties.getInt("persist.sys.sf.native_mode", 0);
868 if (displayColorSetting == 0) {
869 return "1.0".equals(SystemProperties.get("persist.sys.sf.color_saturation"))
870 ? COLOR_MODE_NATURAL : COLOR_MODE_BOOSTED;
871 } else if (displayColorSetting == 1) {
872 return COLOR_MODE_SATURATED;
873 } else if (displayColorSetting == 2) {
874 return COLOR_MODE_AUTOMATIC;
Christine Franks531c0612019-05-16 14:29:14 -0700875 } else if (displayColorSetting >= VENDOR_COLOR_MODE_RANGE_MIN
876 && displayColorSetting <= VENDOR_COLOR_MODE_RANGE_MAX) {
877 return displayColorSetting;
Christine Franksd154fe52019-01-04 17:17:45 -0800878 } else {
879 return -1;
880 }
881 }
882
883 private boolean isColorModeAvailable(@ColorMode int colorMode) {
884 final int[] availableColorModes = getContext().getResources().getIntArray(
885 R.array.config_availableColorModes);
886 if (availableColorModes != null) {
887 for (int mode : availableColorModes) {
888 if (mode == colorMode) {
889 return true;
890 }
891 }
892 }
893 return false;
894 }
895
Christine Franksf3529b22019-01-03 13:20:17 -0800896 private void dumpInternal(PrintWriter pw) {
897 pw.println("COLOR DISPLAY MANAGER dumpsys (color_display)");
Christine Franksa4ed3762019-01-24 15:37:04 -0800898
Christine Franks0ada2772019-02-25 13:54:57 -0800899 pw.println("Night display:");
Christine Franksa4ed3762019-01-24 15:37:04 -0800900 if (mNightDisplayTintController.isAvailable(getContext())) {
Christine Franksf3529b22019-01-03 13:20:17 -0800901 pw.println(" Activated: " + mNightDisplayTintController.isActivated());
Christine Franksa4ed3762019-01-24 15:37:04 -0800902 pw.println(" Color temp: " + mNightDisplayTintController.getColorTemperature());
Christine Franksf3529b22019-01-03 13:20:17 -0800903 } else {
904 pw.println(" Not available");
905 }
Christine Franksa4ed3762019-01-24 15:37:04 -0800906
907 pw.println("Global saturation:");
908 if (mGlobalSaturationTintController.isAvailable(getContext())) {
909 pw.println(" Activated: " + mGlobalSaturationTintController.isActivated());
910 } else {
911 pw.println(" Not available");
912 }
913
Christine Franksf3529b22019-01-03 13:20:17 -0800914 mAppSaturationController.dump(pw);
Christine Franksa4ed3762019-01-24 15:37:04 -0800915
916 pw.println("Display white balance:");
917 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
918 pw.println(" Activated: " + mDisplayWhiteBalanceTintController.isActivated());
Long Ling1d3f1892019-02-06 12:34:02 -0800919 mDisplayWhiteBalanceTintController.dump(pw);
Christine Franksa4ed3762019-01-24 15:37:04 -0800920 } else {
921 pw.println(" Not available");
922 }
923
924 pw.println("Color mode: " + getColorModeInternal());
Christine Franksf3529b22019-01-03 13:20:17 -0800925 }
926
Christine Franks57fdde82018-07-03 14:46:07 -0700927 private abstract class NightDisplayAutoMode {
928
929 public abstract void onActivated(boolean activated);
930
Justin Klaassen911e8892016-06-21 18:24:24 -0700931 public abstract void onStart();
Christine Frankse5bb03e2017-02-10 17:36:10 -0800932
Justin Klaassen911e8892016-06-21 18:24:24 -0700933 public abstract void onStop();
Christine Franks57fdde82018-07-03 14:46:07 -0700934
935 public void onCustomStartTimeChanged(LocalTime startTime) {
936 }
937
938 public void onCustomEndTimeChanged(LocalTime endTime) {
939 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700940 }
941
Christine Franks57fdde82018-07-03 14:46:07 -0700942 private final class CustomNightDisplayAutoMode extends NightDisplayAutoMode implements
943 AlarmManager.OnAlarmListener {
Justin Klaassen911e8892016-06-21 18:24:24 -0700944
945 private final AlarmManager mAlarmManager;
946 private final BroadcastReceiver mTimeChangedReceiver;
947
Christine Franks03213462017-08-25 13:57:26 -0700948 private LocalTime mStartTime;
949 private LocalTime mEndTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700950
Christine Franks03213462017-08-25 13:57:26 -0700951 private LocalDateTime mLastActivatedTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700952
Christine Franks57fdde82018-07-03 14:46:07 -0700953 CustomNightDisplayAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -0700954 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
955 mTimeChangedReceiver = new BroadcastReceiver() {
956 @Override
957 public void onReceive(Context context, Intent intent) {
958 updateActivated();
959 }
960 };
961 }
962
963 private void updateActivated() {
Christine Franks03213462017-08-25 13:57:26 -0700964 final LocalDateTime now = LocalDateTime.now();
965 final LocalDateTime start = getDateTimeBefore(mStartTime, now);
966 final LocalDateTime end = getDateTimeAfter(mEndTime, start);
967 boolean activate = now.isBefore(end);
Justin Klaassen911e8892016-06-21 18:24:24 -0700968
Christine Frankse5bb03e2017-02-10 17:36:10 -0800969 if (mLastActivatedTime != null) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800970 // Maintain the existing activated state if within the current period.
Christine Franks0ada2772019-02-25 13:54:57 -0800971 if (mLastActivatedTime.isBefore(now)
972 && mLastActivatedTime.isAfter(start)
Christine Franks03213462017-08-25 13:57:26 -0700973 && (mLastActivatedTime.isAfter(end) || now.isBefore(end))) {
Christine Franks78a4dd42019-02-08 11:09:30 -0800974 activate = mNightDisplayTintController.isActivatedSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -0700975 }
976 }
977
Christine Franks0ada2772019-02-25 13:54:57 -0800978 if (mNightDisplayTintController.isActivatedStateNotSet()
979 || (mNightDisplayTintController.isActivated() != activate)) {
Christine Franks8851ac82019-06-14 09:44:43 -0700980 mNightDisplayTintController.setActivated(activate, activate ? start : end);
Justin Klaassen911e8892016-06-21 18:24:24 -0700981 }
Christine Franks03213462017-08-25 13:57:26 -0700982
Christine Franks245ffd42018-11-16 13:45:14 -0800983 updateNextAlarm(mNightDisplayTintController.isActivated(), now);
Justin Klaassen911e8892016-06-21 18:24:24 -0700984 }
985
Christine Franks03213462017-08-25 13:57:26 -0700986 private void updateNextAlarm(@Nullable Boolean activated, @NonNull LocalDateTime now) {
Justin Klaassen4346f632016-08-08 15:01:47 -0700987 if (activated != null) {
Christine Franks03213462017-08-25 13:57:26 -0700988 final LocalDateTime next = activated ? getDateTimeAfter(mEndTime, now)
989 : getDateTimeAfter(mStartTime, now);
990 final long millis = next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
991 mAlarmManager.setExact(AlarmManager.RTC, millis, TAG, this, null);
Justin Klaassen911e8892016-06-21 18:24:24 -0700992 }
993 }
994
995 @Override
996 public void onStart() {
997 final IntentFilter intentFilter = new IntentFilter(Intent.ACTION_TIME_CHANGED);
998 intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
999 getContext().registerReceiver(mTimeChangedReceiver, intentFilter);
1000
Christine Franks83cc5412018-07-03 14:46:07 -07001001 mStartTime = getNightDisplayCustomStartTimeInternal().getLocalTime();
1002 mEndTime = getNightDisplayCustomEndTimeInternal().getLocalTime();
Justin Klaassen911e8892016-06-21 18:24:24 -07001003
Christine Franks57fdde82018-07-03 14:46:07 -07001004 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Christine Frankse5bb03e2017-02-10 17:36:10 -08001005
Justin Klaassen911e8892016-06-21 18:24:24 -07001006 // Force an update to initialize state.
1007 updateActivated();
1008 }
1009
1010 @Override
1011 public void onStop() {
1012 getContext().unregisterReceiver(mTimeChangedReceiver);
1013
1014 mAlarmManager.cancel(this);
1015 mLastActivatedTime = null;
1016 }
1017
1018 @Override
1019 public void onActivated(boolean activated) {
Christine Franks57fdde82018-07-03 14:46:07 -07001020 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Christine Franks03213462017-08-25 13:57:26 -07001021 updateNextAlarm(activated, LocalDateTime.now());
Justin Klaassen911e8892016-06-21 18:24:24 -07001022 }
1023
1024 @Override
Christine Franks03213462017-08-25 13:57:26 -07001025 public void onCustomStartTimeChanged(LocalTime startTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -07001026 mStartTime = startTime;
1027 mLastActivatedTime = null;
1028 updateActivated();
1029 }
1030
1031 @Override
Christine Franks03213462017-08-25 13:57:26 -07001032 public void onCustomEndTimeChanged(LocalTime endTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -07001033 mEndTime = endTime;
1034 mLastActivatedTime = null;
1035 updateActivated();
1036 }
1037
1038 @Override
1039 public void onAlarm() {
Justin Klaassenec8837a2016-08-23 12:04:42 -07001040 Slog.d(TAG, "onAlarm");
Justin Klaassen911e8892016-06-21 18:24:24 -07001041 updateActivated();
1042 }
1043 }
1044
Christine Franks57fdde82018-07-03 14:46:07 -07001045 private final class TwilightNightDisplayAutoMode extends NightDisplayAutoMode implements
1046 TwilightListener {
Justin Klaassen911e8892016-06-21 18:24:24 -07001047
1048 private final TwilightManager mTwilightManager;
Christine Franks57fdde82018-07-03 14:46:07 -07001049 private LocalDateTime mLastActivatedTime;
Justin Klaassen911e8892016-06-21 18:24:24 -07001050
Christine Franks57fdde82018-07-03 14:46:07 -07001051 TwilightNightDisplayAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -07001052 mTwilightManager = getLocalService(TwilightManager.class);
Justin Klaassen911e8892016-06-21 18:24:24 -07001053 }
1054
Justin Klaassen908b86c2016-08-08 09:18:42 -07001055 private void updateActivated(TwilightState state) {
Justin Klaassen3da4c442017-05-05 15:19:33 -07001056 if (state == null) {
1057 // If there isn't a valid TwilightState then just keep the current activated
1058 // state.
1059 return;
1060 }
1061
1062 boolean activate = state.isNight();
Christine Franks57fdde82018-07-03 14:46:07 -07001063 if (mLastActivatedTime != null) {
Christine Franks03213462017-08-25 13:57:26 -07001064 final LocalDateTime now = LocalDateTime.now();
1065 final LocalDateTime sunrise = state.sunrise();
1066 final LocalDateTime sunset = state.sunset();
Christine Frankse5bb03e2017-02-10 17:36:10 -08001067 // Maintain the existing activated state if within the current period.
Christine Franks57fdde82018-07-03 14:46:07 -07001068 if (mLastActivatedTime.isBefore(now) && (mLastActivatedTime.isBefore(sunrise)
1069 ^ mLastActivatedTime.isBefore(sunset))) {
Christine Franks78a4dd42019-02-08 11:09:30 -08001070 activate = mNightDisplayTintController.isActivatedSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -07001071 }
1072 }
Justin Klaassen908b86c2016-08-08 09:18:42 -07001073
Christine Franks245ffd42018-11-16 13:45:14 -08001074 if (mNightDisplayTintController.isActivatedStateNotSet() || (
1075 mNightDisplayTintController.isActivated() != activate)) {
Christine Franks83cc5412018-07-03 14:46:07 -07001076 mNightDisplayTintController.setActivated(activate);
Justin Klaassen908b86c2016-08-08 09:18:42 -07001077 }
Justin Klaassen911e8892016-06-21 18:24:24 -07001078 }
1079
1080 @Override
Christine Franks57fdde82018-07-03 14:46:07 -07001081 public void onActivated(boolean activated) {
1082 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
1083 }
1084
1085 @Override
Justin Klaassen911e8892016-06-21 18:24:24 -07001086 public void onStart() {
1087 mTwilightManager.registerListener(this, mHandler);
Christine Franks57fdde82018-07-03 14:46:07 -07001088 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -07001089
1090 // Force an update to initialize state.
Justin Klaassen908b86c2016-08-08 09:18:42 -07001091 updateActivated(mTwilightManager.getLastTwilightState());
Justin Klaassen911e8892016-06-21 18:24:24 -07001092 }
1093
1094 @Override
1095 public void onStop() {
1096 mTwilightManager.unregisterListener(this);
Christine Franks57fdde82018-07-03 14:46:07 -07001097 mLastActivatedTime = null;
Justin Klaassen908b86c2016-08-08 09:18:42 -07001098 }
1099
1100 @Override
1101 public void onTwilightStateChanged(@Nullable TwilightState state) {
Justin Klaassenec8837a2016-08-23 12:04:42 -07001102 Slog.d(TAG, "onTwilightStateChanged: isNight="
1103 + (state == null ? null : state.isNight()));
Justin Klaassen908b86c2016-08-08 09:18:42 -07001104 updateActivated(state);
Justin Klaassen911e8892016-06-21 18:24:24 -07001105 }
1106 }
Justin Klaassen639214e2016-07-14 21:00:06 -07001107
1108 /**
1109 * Interpolates between two 4x4 color transform matrices (in column-major order).
1110 */
1111 private static class ColorMatrixEvaluator implements TypeEvaluator<float[]> {
1112
1113 /**
1114 * Result matrix returned by {@link #evaluate(float, float[], float[])}.
1115 */
1116 private final float[] mResultMatrix = new float[16];
1117
1118 @Override
1119 public float[] evaluate(float fraction, float[] startValue, float[] endValue) {
1120 for (int i = 0; i < mResultMatrix.length; i++) {
1121 mResultMatrix[i] = MathUtils.lerp(startValue[i], endValue[i], fraction);
1122 }
1123 return mResultMatrix;
1124 }
1125 }
Christine Franks39b03112018-07-03 14:46:07 -07001126
Christine Franks83cc5412018-07-03 14:46:07 -07001127 private final class NightDisplayTintController extends TintController {
1128
Christine Franksa4ed3762019-01-24 15:37:04 -08001129 private final float[] mMatrix = new float[16];
Christine Franks83cc5412018-07-03 14:46:07 -07001130 private final float[] mColorTempCoefficients = new float[9];
Christine Franksa4ed3762019-01-24 15:37:04 -08001131
1132 private Boolean mIsAvailable;
Christine Franks83cc5412018-07-03 14:46:07 -07001133 private Integer mColorTemp;
1134
1135 /**
1136 * Set coefficients based on whether the color matrix is linear or not.
1137 */
1138 @Override
1139 public void setUp(Context context, boolean needsLinear) {
1140 final String[] coefficients = context.getResources().getStringArray(needsLinear
1141 ? R.array.config_nightDisplayColorTemperatureCoefficients
1142 : R.array.config_nightDisplayColorTemperatureCoefficientsNative);
1143 for (int i = 0; i < 9 && i < coefficients.length; i++) {
1144 mColorTempCoefficients[i] = Float.parseFloat(coefficients[i]);
1145 }
1146 }
1147
1148 @Override
1149 public void setMatrix(int cct) {
1150 if (mMatrix.length != 16) {
1151 Slog.d(TAG, "The display transformation matrix must be 4x4");
1152 return;
1153 }
1154
1155 Matrix.setIdentityM(mMatrix, 0);
1156
1157 final float squareTemperature = cct * cct;
1158 final float red = squareTemperature * mColorTempCoefficients[0]
1159 + cct * mColorTempCoefficients[1] + mColorTempCoefficients[2];
1160 final float green = squareTemperature * mColorTempCoefficients[3]
1161 + cct * mColorTempCoefficients[4] + mColorTempCoefficients[5];
1162 final float blue = squareTemperature * mColorTempCoefficients[6]
1163 + cct * mColorTempCoefficients[7] + mColorTempCoefficients[8];
1164 mMatrix[0] = red;
1165 mMatrix[5] = green;
1166 mMatrix[10] = blue;
1167 }
1168
1169 @Override
1170 public float[] getMatrix() {
1171 return isActivated() ? mMatrix : MATRIX_IDENTITY;
1172 }
1173
1174 @Override
1175 public void setActivated(Boolean activated) {
Christine Franks8851ac82019-06-14 09:44:43 -07001176 setActivated(activated, LocalDateTime.now());
1177 }
1178
1179 /**
1180 * Use directly when it is important that the last activation time be exact (for example, an
1181 * automatic change). Otherwise use {@link #setActivated(Boolean)}.
1182 */
1183 public void setActivated(Boolean activated, @NonNull LocalDateTime lastActivationTime) {
Christine Franks83cc5412018-07-03 14:46:07 -07001184 if (activated == null) {
1185 super.setActivated(null);
1186 return;
1187 }
1188
1189 boolean activationStateChanged = activated != isActivated();
1190
1191 if (!isActivatedStateNotSet() && activationStateChanged) {
1192 // This is a true state change, so set this as the last activation time.
1193 Secure.putStringForUser(getContext().getContentResolver(),
1194 Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
Christine Franks8851ac82019-06-14 09:44:43 -07001195 lastActivationTime.toString(),
Christine Franks83cc5412018-07-03 14:46:07 -07001196 mCurrentUser);
1197 }
1198
1199 if (isActivatedStateNotSet() || activationStateChanged) {
1200 super.setActivated(activated);
Christine Franks78a4dd42019-02-08 11:09:30 -08001201 if (isActivatedSetting() != activated) {
1202 Secure.putIntForUser(getContext().getContentResolver(),
1203 Secure.NIGHT_DISPLAY_ACTIVATED,
1204 activated ? 1 : 0, mCurrentUser);
1205 }
Christine Franks83cc5412018-07-03 14:46:07 -07001206 onActivated(activated);
1207 }
1208 }
1209
1210 @Override
1211 public int getLevel() {
1212 return LEVEL_COLOR_MATRIX_NIGHT_DISPLAY;
1213 }
1214
Christine Franksa4ed3762019-01-24 15:37:04 -08001215 @Override
1216 public boolean isAvailable(Context context) {
1217 if (mIsAvailable == null) {
1218 mIsAvailable = ColorDisplayManager.isNightDisplayAvailable(context);
1219 }
1220 return mIsAvailable;
1221 }
1222
Christine Franks78a4dd42019-02-08 11:09:30 -08001223 private void onActivated(boolean activated) {
Christine Franks83cc5412018-07-03 14:46:07 -07001224 Slog.i(TAG, activated ? "Turning on night display" : "Turning off night display");
1225 if (mNightDisplayAutoMode != null) {
1226 mNightDisplayAutoMode.onActivated(activated);
1227 }
1228
Christine Franksa4ed3762019-01-24 15:37:04 -08001229 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
Christine Franks83cc5412018-07-03 14:46:07 -07001230 updateDisplayWhiteBalanceStatus();
1231 }
1232
1233 mHandler.sendEmptyMessage(MSG_APPLY_NIGHT_DISPLAY_ANIMATED);
1234 }
1235
1236 int getColorTemperature() {
1237 return mColorTemp != null ? clampNightDisplayColorTemperature(mColorTemp)
Christine Franks78a4dd42019-02-08 11:09:30 -08001238 : getColorTemperatureSetting();
Christine Franks83cc5412018-07-03 14:46:07 -07001239 }
1240
1241 boolean setColorTemperature(int temperature) {
1242 mColorTemp = temperature;
1243 final boolean success = Secure.putIntForUser(getContext().getContentResolver(),
1244 Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE, temperature, mCurrentUser);
1245 onColorTemperatureChanged(temperature);
1246 return success;
1247 }
1248
1249 void onColorTemperatureChanged(int temperature) {
1250 setMatrix(temperature);
1251 mHandler.sendEmptyMessage(MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE);
1252 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001253
1254 boolean isActivatedSetting() {
Christine Franks44782612019-03-07 17:25:39 -08001255 if (mCurrentUser == UserHandle.USER_NULL) {
1256 return false;
1257 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001258 return Secure.getIntForUser(getContext().getContentResolver(),
1259 Secure.NIGHT_DISPLAY_ACTIVATED, 0, mCurrentUser) == 1;
1260 }
1261
1262 int getColorTemperatureSetting() {
Christine Franks44782612019-03-07 17:25:39 -08001263 if (mCurrentUser == UserHandle.USER_NULL) {
1264 return NOT_SET;
1265 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001266 return clampNightDisplayColorTemperature(Secure.getIntForUser(
1267 getContext().getContentResolver(), Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE,
1268 NOT_SET,
1269 mCurrentUser));
1270 }
1271
1272 private int clampNightDisplayColorTemperature(int colorTemperature) {
1273 if (colorTemperature == NOT_SET) {
1274 colorTemperature = getContext().getResources().getInteger(
1275 R.integer.config_nightDisplayColorTemperatureDefault);
1276 }
1277 final int minimumTemperature = ColorDisplayManager
1278 .getMinimumColorTemperature(getContext());
1279 final int maximumTemperature = ColorDisplayManager
1280 .getMaximumColorTemperature(getContext());
1281 if (colorTemperature < minimumTemperature) {
1282 colorTemperature = minimumTemperature;
1283 } else if (colorTemperature > maximumTemperature) {
1284 colorTemperature = maximumTemperature;
1285 }
1286
1287 return colorTemperature;
1288 }
Christine Franks83cc5412018-07-03 14:46:07 -07001289 }
1290
Christine Franks245ffd42018-11-16 13:45:14 -08001291 /**
1292 * Local service that allows color transforms to be enabled from other system services.
1293 */
1294 public final class ColorDisplayServiceInternal {
1295
1296 /**
1297 * Set the current CCT value for the display white balance transform, and if the transform
1298 * is enabled, apply it.
1299 *
1300 * @param cct the color temperature in Kelvin.
1301 */
1302 public boolean setDisplayWhiteBalanceColorTemperature(int cct) {
1303 // Update the transform matrix even if it can't be applied.
Christine Franks245ffd42018-11-16 13:45:14 -08001304 mDisplayWhiteBalanceTintController.setMatrix(cct);
1305
1306 if (mDisplayWhiteBalanceTintController.isActivated()) {
Christine Franksc7fb9452019-02-04 08:45:33 -08001307 mHandler.sendEmptyMessage(MSG_APPLY_DISPLAY_WHITE_BALANCE);
Christine Franks245ffd42018-11-16 13:45:14 -08001308 return true;
1309 }
1310 return false;
1311 }
1312
1313 /**
Daniel Solomon37816412019-04-10 15:17:41 -07001314 * Reset the CCT value for the display white balance transform to its default value.
1315 */
1316 public boolean resetDisplayWhiteBalanceColorTemperature() {
1317 return setDisplayWhiteBalanceColorTemperature(getContext().getResources()
1318 .getInteger(R.integer.config_displayWhiteBalanceColorTemperatureDefault));
1319 }
1320
1321 /**
Christine Franks245ffd42018-11-16 13:45:14 -08001322 * Sets the listener and returns whether display white balance is currently enabled.
1323 */
1324 public boolean setDisplayWhiteBalanceListener(DisplayWhiteBalanceListener listener) {
1325 mDisplayWhiteBalanceListener = listener;
1326 return mDisplayWhiteBalanceTintController.isActivated();
1327 }
Daniel Solomon8b72c5b2018-11-25 11:07:13 -08001328
Christine Franksf3529b22019-01-03 13:20:17 -08001329 /**
Christine Franks66783a82019-03-28 11:45:56 -07001330 * Returns whether Display white balance is currently enabled.
1331 */
1332 public boolean isDisplayWhiteBalanceEnabled() {
1333 return isDisplayWhiteBalanceSettingEnabled();
1334 }
1335
1336 /**
Christine Franksf3529b22019-01-03 13:20:17 -08001337 * Adds a {@link WeakReference<ColorTransformController>} for a newly started activity, and
1338 * invokes {@link ColorTransformController#applyAppSaturation(float[], float[])} if needed.
1339 */
Christine Franks55194dc2019-01-15 13:47:06 -08001340 public boolean attachColorTransformController(String packageName, @UserIdInt int userId,
Christine Franksf3529b22019-01-03 13:20:17 -08001341 WeakReference<ColorTransformController> controller) {
1342 return mAppSaturationController
Christine Franks55194dc2019-01-15 13:47:06 -08001343 .addColorTransformController(packageName, userId, controller);
Christine Franksf3529b22019-01-03 13:20:17 -08001344 }
Christine Franks245ffd42018-11-16 13:45:14 -08001345 }
1346
1347 /**
1348 * Listener for changes in display white balance status.
1349 */
1350 public interface DisplayWhiteBalanceListener {
1351
1352 /**
1353 * Notify that the display white balance status has changed, either due to preemption by
1354 * another transform or the feature being turned off.
1355 */
Christine Franks66783a82019-03-28 11:45:56 -07001356 void onDisplayWhiteBalanceStatusChanged(boolean activated);
Christine Franks245ffd42018-11-16 13:45:14 -08001357 }
1358
Christine Franks09c229e2018-12-14 10:37:40 -08001359 private final class TintHandler extends Handler {
1360
Christine Franks83cc5412018-07-03 14:46:07 -07001361 private TintHandler(Looper looper) {
Christine Franks09c229e2018-12-14 10:37:40 -08001362 super(looper, null, true /* async */);
1363 }
1364
1365 @Override
1366 public void handleMessage(Message msg) {
1367 switch (msg.what) {
Christine Franks27912a32019-04-02 10:43:10 -07001368 case MSG_USER_CHANGED:
1369 onUserChanged(msg.arg1);
1370 break;
1371 case MSG_SET_UP:
1372 setUp();
1373 break;
Christine Franks09c229e2018-12-14 10:37:40 -08001374 case MSG_APPLY_GLOBAL_SATURATION:
1375 mGlobalSaturationTintController.setMatrix(msg.arg1);
1376 applyTint(mGlobalSaturationTintController, false);
1377 break;
Christine Franks83cc5412018-07-03 14:46:07 -07001378 case MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE:
1379 applyTint(mNightDisplayTintController, true);
1380 break;
1381 case MSG_APPLY_NIGHT_DISPLAY_ANIMATED:
1382 applyTint(mNightDisplayTintController, false);
1383 break;
Christine Franksc7fb9452019-02-04 08:45:33 -08001384 case MSG_APPLY_DISPLAY_WHITE_BALANCE:
1385 applyTint(mDisplayWhiteBalanceTintController, false);
1386 break;
Christine Franks09c229e2018-12-14 10:37:40 -08001387 }
1388 }
1389 }
1390
Christine Franksf3529b22019-01-03 13:20:17 -08001391 /**
1392 * Interface for applying transforms to a given AppWindow.
1393 */
1394 public interface ColorTransformController {
1395
Christine Franksd154fe52019-01-04 17:17:45 -08001396 /**
1397 * Apply the given saturation (grayscale) matrix to the associated AppWindow.
1398 */
Christine Franksf3529b22019-01-03 13:20:17 -08001399 void applyAppSaturation(@Size(9) float[] matrix, @Size(3) float[] translation);
1400 }
1401
Christine Franks83cc5412018-07-03 14:46:07 -07001402 @VisibleForTesting
1403 final class BinderService extends IColorDisplayManager.Stub {
Christine Franks57fdde82018-07-03 14:46:07 -07001404
Christine Franks39b03112018-07-03 14:46:07 -07001405 @Override
Christine Franksd154fe52019-01-04 17:17:45 -08001406 public void setColorMode(int colorMode) {
1407 getContext().enforceCallingOrSelfPermission(
1408 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1409 "Permission required to set display color mode");
1410 final long token = Binder.clearCallingIdentity();
1411 try {
1412 setColorModeInternal(colorMode);
1413 } finally {
1414 Binder.restoreCallingIdentity(token);
1415 }
1416 }
1417
1418 @Override
1419 public int getColorMode() {
1420 final long token = Binder.clearCallingIdentity();
1421 try {
1422 return getColorModeInternal();
1423 } finally {
1424 Binder.restoreCallingIdentity(token);
1425 }
1426 }
1427
1428 @Override
Christine Franks39b03112018-07-03 14:46:07 -07001429 public boolean isDeviceColorManaged() {
1430 final long token = Binder.clearCallingIdentity();
1431 try {
1432 return isDeviceColorManagedInternal();
1433 } finally {
1434 Binder.restoreCallingIdentity(token);
1435 }
1436 }
Christine Franks09c229e2018-12-14 10:37:40 -08001437
1438 @Override
1439 public boolean setSaturationLevel(int level) {
1440 final boolean hasTransformsPermission = getContext()
1441 .checkCallingPermission(Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS)
1442 == PackageManager.PERMISSION_GRANTED;
1443 final boolean hasLegacyPermission = getContext()
1444 .checkCallingPermission(Manifest.permission.CONTROL_DISPLAY_SATURATION)
1445 == PackageManager.PERMISSION_GRANTED;
1446 if (!hasTransformsPermission && !hasLegacyPermission) {
1447 throw new SecurityException("Permission required to set display saturation level");
1448 }
1449 final long token = Binder.clearCallingIdentity();
1450 try {
1451 final Message message = mHandler.obtainMessage(MSG_APPLY_GLOBAL_SATURATION);
1452 message.arg1 = level;
1453 mHandler.sendMessage(message);
1454 } finally {
1455 Binder.restoreCallingIdentity(token);
1456 }
1457 return true;
1458 }
Christine Franksf3529b22019-01-03 13:20:17 -08001459
1460 @Override
Christine Franks6d21d342019-02-07 15:09:03 -08001461 public boolean isSaturationActivated() {
1462 getContext().enforceCallingPermission(
1463 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1464 "Permission required to get display saturation level");
1465 final long token = Binder.clearCallingIdentity();
1466 try {
1467 return !mGlobalSaturationTintController.isActivatedStateNotSet()
1468 && mGlobalSaturationTintController.isActivated();
1469 } finally {
1470 Binder.restoreCallingIdentity(token);
1471 }
1472 }
1473
1474 @Override
Christine Franksf3529b22019-01-03 13:20:17 -08001475 public boolean setAppSaturationLevel(String packageName, int level) {
1476 getContext().enforceCallingPermission(
1477 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1478 "Permission required to set display saturation level");
1479 final long token = Binder.clearCallingIdentity();
1480 try {
1481 return setAppSaturationLevelInternal(packageName, level);
1482 } finally {
1483 Binder.restoreCallingIdentity(token);
1484 }
1485 }
1486
Christine Franks55194dc2019-01-15 13:47:06 -08001487 public int getTransformCapabilities() {
1488 getContext().enforceCallingPermission(
1489 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1490 "Permission required to query transform capabilities");
1491 final long token = Binder.clearCallingIdentity();
1492 try {
1493 return getTransformCapabilitiesInternal();
1494 } finally {
1495 Binder.restoreCallingIdentity(token);
1496 }
1497 }
1498
Christine Franksf3529b22019-01-03 13:20:17 -08001499 @Override
Christine Franks83cc5412018-07-03 14:46:07 -07001500 public boolean setNightDisplayActivated(boolean activated) {
1501 getContext().enforceCallingOrSelfPermission(
1502 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1503 "Permission required to set night display activated");
1504 final long token = Binder.clearCallingIdentity();
1505 try {
1506 mNightDisplayTintController.setActivated(activated);
1507 return true;
1508 } finally {
1509 Binder.restoreCallingIdentity(token);
1510 }
1511 }
1512
1513 @Override
1514 public boolean isNightDisplayActivated() {
1515 final long token = Binder.clearCallingIdentity();
1516 try {
1517 return mNightDisplayTintController.isActivated();
1518 } finally {
1519 Binder.restoreCallingIdentity(token);
1520 }
1521 }
1522
1523 @Override
1524 public boolean setNightDisplayColorTemperature(int temperature) {
1525 getContext().enforceCallingOrSelfPermission(
1526 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1527 "Permission required to set night display temperature");
1528 final long token = Binder.clearCallingIdentity();
1529 try {
1530 return mNightDisplayTintController.setColorTemperature(temperature);
1531 } finally {
1532 Binder.restoreCallingIdentity(token);
1533 }
1534 }
1535
1536 @Override
1537 public int getNightDisplayColorTemperature() {
1538 final long token = Binder.clearCallingIdentity();
1539 try {
1540 return mNightDisplayTintController.getColorTemperature();
1541 } finally {
1542 Binder.restoreCallingIdentity(token);
1543 }
1544 }
1545
1546 @Override
1547 public boolean setNightDisplayAutoMode(int autoMode) {
1548 getContext().enforceCallingOrSelfPermission(
1549 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1550 "Permission required to set night display auto mode");
1551 final long token = Binder.clearCallingIdentity();
1552 try {
1553 return setNightDisplayAutoModeInternal(autoMode);
1554 } finally {
1555 Binder.restoreCallingIdentity(token);
1556 }
1557 }
1558
1559 @Override
1560 public int getNightDisplayAutoMode() {
1561 getContext().enforceCallingOrSelfPermission(
1562 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1563 "Permission required to get night display auto mode");
1564 final long token = Binder.clearCallingIdentity();
1565 try {
1566 return getNightDisplayAutoModeInternal();
1567 } finally {
1568 Binder.restoreCallingIdentity(token);
1569 }
1570 }
1571
1572 @Override
1573 public int getNightDisplayAutoModeRaw() {
1574 final long token = Binder.clearCallingIdentity();
1575 try {
1576 return getNightDisplayAutoModeRawInternal();
1577 } finally {
1578 Binder.restoreCallingIdentity(token);
1579 }
1580 }
1581
1582 @Override
1583 public boolean setNightDisplayCustomStartTime(Time startTime) {
1584 getContext().enforceCallingOrSelfPermission(
1585 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1586 "Permission required to set night display custom start time");
1587 final long token = Binder.clearCallingIdentity();
1588 try {
1589 return setNightDisplayCustomStartTimeInternal(startTime);
1590 } finally {
1591 Binder.restoreCallingIdentity(token);
1592 }
1593 }
1594
1595 @Override
1596 public Time getNightDisplayCustomStartTime() {
1597 final long token = Binder.clearCallingIdentity();
1598 try {
1599 return getNightDisplayCustomStartTimeInternal();
1600 } finally {
1601 Binder.restoreCallingIdentity(token);
1602 }
1603 }
1604
1605 @Override
1606 public boolean setNightDisplayCustomEndTime(Time endTime) {
1607 getContext().enforceCallingOrSelfPermission(
1608 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1609 "Permission required to set night display custom end time");
1610 final long token = Binder.clearCallingIdentity();
1611 try {
1612 return setNightDisplayCustomEndTimeInternal(endTime);
1613 } finally {
1614 Binder.restoreCallingIdentity(token);
1615 }
1616 }
1617
1618 @Override
1619 public Time getNightDisplayCustomEndTime() {
1620 final long token = Binder.clearCallingIdentity();
1621 try {
1622 return getNightDisplayCustomEndTimeInternal();
1623 } finally {
1624 Binder.restoreCallingIdentity(token);
1625 }
1626 }
1627
1628 @Override
Christine Franks66783a82019-03-28 11:45:56 -07001629 public boolean setDisplayWhiteBalanceEnabled(boolean enabled) {
1630 getContext().enforceCallingOrSelfPermission(
1631 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1632 "Permission required to set night display activated");
1633 final long token = Binder.clearCallingIdentity();
1634 try {
1635 return setDisplayWhiteBalanceSettingEnabled(enabled);
1636 } finally {
1637 Binder.restoreCallingIdentity(token);
1638 }
1639 }
1640
1641 @Override
1642 public boolean isDisplayWhiteBalanceEnabled() {
1643 final long token = Binder.clearCallingIdentity();
1644 try {
1645 return isDisplayWhiteBalanceSettingEnabled();
1646 } finally {
1647 Binder.restoreCallingIdentity(token);
1648 }
1649 }
1650
1651 @Override
Christine Franksf3529b22019-01-03 13:20:17 -08001652 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Christine Franksd154fe52019-01-04 17:17:45 -08001653 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) {
1654 return;
1655 }
Christine Franksf3529b22019-01-03 13:20:17 -08001656
1657 final long token = Binder.clearCallingIdentity();
1658 try {
1659 dumpInternal(pw);
1660 } finally {
1661 Binder.restoreCallingIdentity(token);
1662 }
1663 }
Christine Franks39b03112018-07-03 14:46:07 -07001664 }
Justin Klaassen911e8892016-06-21 18:24:24 -07001665}