blob: 0bf43b6d1b9c2d0623efccb94951e79d1382437d [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) {
Anthony Han00a490b2019-08-26 14:00:28 -0700612 Slog.d(TAG, tintController.getClass().getSimpleName()
613 + " Animation cancelled: " + mIsCancelled
614 + " to matrix: " + TintController.matrixToString(to, 16));
Christine Franks6418d0b2017-02-13 09:48:00 -0800615 if (!mIsCancelled) {
616 // Ensure final color matrix is set at the end of the animation. If the
617 // animation is cancelled then don't set the final color matrix so the new
618 // animator can pick up from where this one left off.
Christine Franks245ffd42018-11-16 13:45:14 -0800619 dtm.setColorMatrix(tintController.getLevel(), to);
Christine Franks6418d0b2017-02-13 09:48:00 -0800620 }
Christine Franks245ffd42018-11-16 13:45:14 -0800621 tintController.setAnimator(null);
Christine Franks6418d0b2017-02-13 09:48:00 -0800622 }
623 });
Christine Franks245ffd42018-11-16 13:45:14 -0800624 tintController.getAnimator().start();
Christine Franks6418d0b2017-02-13 09:48:00 -0800625 }
626 }
627
628 /**
Christine Franks39b03112018-07-03 14:46:07 -0700629 * Returns the first date time corresponding to the local time that occurs before the provided
630 * date time.
Christine Franks03213462017-08-25 13:57:26 -0700631 *
632 * @param compareTime the LocalDateTime to compare against
633 * @return the prior LocalDateTime corresponding to this local time
634 */
Christine Franks57fdde82018-07-03 14:46:07 -0700635 @VisibleForTesting
636 static LocalDateTime getDateTimeBefore(LocalTime localTime, LocalDateTime compareTime) {
Christine Franks03213462017-08-25 13:57:26 -0700637 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
638 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
639
640 // Check if the local time has passed, if so return the same time yesterday.
641 return ldt.isAfter(compareTime) ? ldt.minusDays(1) : ldt;
642 }
643
644 /**
Christine Franks39b03112018-07-03 14:46:07 -0700645 * Returns the first date time corresponding to this local time that occurs after the provided
646 * date time.
Christine Franks03213462017-08-25 13:57:26 -0700647 *
648 * @param compareTime the LocalDateTime to compare against
649 * @return the next LocalDateTime corresponding to this local time
650 */
Christine Franks57fdde82018-07-03 14:46:07 -0700651 @VisibleForTesting
652 static LocalDateTime getDateTimeAfter(LocalTime localTime, LocalDateTime compareTime) {
Christine Franks03213462017-08-25 13:57:26 -0700653 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
654 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
655
656 // Check if the local time has passed, if so return the same time tomorrow.
657 return ldt.isBefore(compareTime) ? ldt.plusDays(1) : ldt;
658 }
659
Long Ling1d3f1892019-02-06 12:34:02 -0800660 @VisibleForTesting
661 void updateDisplayWhiteBalanceStatus() {
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800662 boolean oldActivated = mDisplayWhiteBalanceTintController.isActivated();
Christine Franks0ada2772019-02-25 13:54:57 -0800663 mDisplayWhiteBalanceTintController.setActivated(isDisplayWhiteBalanceSettingEnabled()
664 && !mNightDisplayTintController.isActivated()
Daniel Solomonff24ba92019-04-11 19:29:31 -0700665 && !isAccessibilityEnabled()
Christine Franks0ada2772019-02-25 13:54:57 -0800666 && DisplayTransformManager.needsLinearColorMatrix());
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800667 boolean activated = mDisplayWhiteBalanceTintController.isActivated();
668
669 if (mDisplayWhiteBalanceListener != null && oldActivated != activated) {
670 mDisplayWhiteBalanceListener.onDisplayWhiteBalanceStatusChanged(activated);
Christine Franks245ffd42018-11-16 13:45:14 -0800671 }
Daniel Solomon86508f82019-01-18 19:01:02 -0800672
673 // If disabled, clear the tint. If enabled, do nothing more here and let the next
674 // temperature update set the correct tint.
675 if (!activated) {
Christine Franksc7fb9452019-02-04 08:45:33 -0800676 mHandler.sendEmptyMessage(MSG_APPLY_DISPLAY_WHITE_BALANCE);
Daniel Solomon86508f82019-01-18 19:01:02 -0800677 }
Christine Franks245ffd42018-11-16 13:45:14 -0800678 }
679
Christine Franks66783a82019-03-28 11:45:56 -0700680 private boolean setDisplayWhiteBalanceSettingEnabled(boolean enabled) {
681 if (mCurrentUser == UserHandle.USER_NULL) {
682 return false;
683 }
684 return Secure.putIntForUser(getContext().getContentResolver(),
685 Secure.DISPLAY_WHITE_BALANCE_ENABLED,
686 enabled ? 1 : 0, mCurrentUser);
687 }
688
Christine Franks245ffd42018-11-16 13:45:14 -0800689 private boolean isDisplayWhiteBalanceSettingEnabled() {
Christine Franks27912a32019-04-02 10:43:10 -0700690 if (mCurrentUser == UserHandle.USER_NULL) {
691 return false;
692 }
Christine Franks245ffd42018-11-16 13:45:14 -0800693 return Secure.getIntForUser(getContext().getContentResolver(),
Christine Franks18ac4e22019-04-05 18:30:50 -0700694 Secure.DISPLAY_WHITE_BALANCE_ENABLED,
695 getContext().getResources()
696 .getBoolean(R.bool.config_displayWhiteBalanceEnabledDefault) ? 1
697 : 0,
698 mCurrentUser) == 1;
Christine Franks245ffd42018-11-16 13:45:14 -0800699 }
700
Christine Franks39b03112018-07-03 14:46:07 -0700701 private boolean isDeviceColorManagedInternal() {
702 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
703 return dtm.isDeviceColorManaged();
704 }
705
Christine Franks55194dc2019-01-15 13:47:06 -0800706 private int getTransformCapabilitiesInternal() {
707 int availabilityFlags = ColorDisplayManager.CAPABILITY_NONE;
708 if (SurfaceControl.getProtectedContentSupport()) {
709 availabilityFlags |= ColorDisplayManager.CAPABILITY_PROTECTED_CONTENT;
710 }
711 final Resources res = getContext().getResources();
712 if (res.getBoolean(R.bool.config_setColorTransformAccelerated)) {
713 availabilityFlags |= ColorDisplayManager.CAPABILITY_HARDWARE_ACCELERATION_GLOBAL;
714 }
715 if (res.getBoolean(R.bool.config_setColorTransformAcceleratedPerLayer)) {
716 availabilityFlags |= ColorDisplayManager.CAPABILITY_HARDWARE_ACCELERATION_PER_APP;
717 }
718 return availabilityFlags;
719 }
720
Christine Franks83cc5412018-07-03 14:46:07 -0700721 private boolean setNightDisplayAutoModeInternal(@AutoMode int autoMode) {
722 if (getNightDisplayAutoModeInternal() != autoMode) {
723 Secure.putStringForUser(getContext().getContentResolver(),
724 Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
725 null,
726 mCurrentUser);
727 }
728 return Secure.putIntForUser(getContext().getContentResolver(),
729 Secure.NIGHT_DISPLAY_AUTO_MODE, autoMode, mCurrentUser);
730 }
731
732 private int getNightDisplayAutoModeInternal() {
733 int autoMode = getNightDisplayAutoModeRawInternal();
734 if (autoMode == NOT_SET) {
735 autoMode = getContext().getResources().getInteger(
736 R.integer.config_defaultNightDisplayAutoMode);
737 }
738 if (autoMode != AUTO_MODE_DISABLED
739 && autoMode != AUTO_MODE_CUSTOM_TIME
740 && autoMode != AUTO_MODE_TWILIGHT) {
741 Slog.e(TAG, "Invalid autoMode: " + autoMode);
742 autoMode = AUTO_MODE_DISABLED;
743 }
744 return autoMode;
745 }
746
747 private int getNightDisplayAutoModeRawInternal() {
Christine Franks27912a32019-04-02 10:43:10 -0700748 if (mCurrentUser == UserHandle.USER_NULL) {
749 return NOT_SET;
750 }
Christine Franks83cc5412018-07-03 14:46:07 -0700751 return Secure
752 .getIntForUser(getContext().getContentResolver(), Secure.NIGHT_DISPLAY_AUTO_MODE,
753 NOT_SET, mCurrentUser);
754 }
755
756 private Time getNightDisplayCustomStartTimeInternal() {
757 int startTimeValue = Secure.getIntForUser(getContext().getContentResolver(),
758 Secure.NIGHT_DISPLAY_CUSTOM_START_TIME, NOT_SET, mCurrentUser);
759 if (startTimeValue == NOT_SET) {
760 startTimeValue = getContext().getResources().getInteger(
761 R.integer.config_defaultNightDisplayCustomStartTime);
762 }
763 return new Time(LocalTime.ofSecondOfDay(startTimeValue / 1000));
764 }
765
766 private boolean setNightDisplayCustomStartTimeInternal(Time startTime) {
767 return Secure.putIntForUser(getContext().getContentResolver(),
768 Secure.NIGHT_DISPLAY_CUSTOM_START_TIME,
769 startTime.getLocalTime().toSecondOfDay() * 1000,
770 mCurrentUser);
771 }
772
773 private Time getNightDisplayCustomEndTimeInternal() {
774 int endTimeValue = Secure.getIntForUser(getContext().getContentResolver(),
775 Secure.NIGHT_DISPLAY_CUSTOM_END_TIME, NOT_SET, mCurrentUser);
776 if (endTimeValue == NOT_SET) {
777 endTimeValue = getContext().getResources().getInteger(
778 R.integer.config_defaultNightDisplayCustomEndTime);
779 }
780 return new Time(LocalTime.ofSecondOfDay(endTimeValue / 1000));
781 }
782
783 private boolean setNightDisplayCustomEndTimeInternal(Time endTime) {
784 return Secure.putIntForUser(getContext().getContentResolver(),
785 Secure.NIGHT_DISPLAY_CUSTOM_END_TIME, endTime.getLocalTime().toSecondOfDay() * 1000,
786 mCurrentUser);
787 }
788
Christine Franks57fdde82018-07-03 14:46:07 -0700789 /**
790 * Returns the last time the night display transform activation state was changed, or {@link
791 * LocalDateTime#MIN} if night display has never been activated.
792 */
Christine Franks245ffd42018-11-16 13:45:14 -0800793 private LocalDateTime getNightDisplayLastActivatedTimeSetting() {
Christine Franks57fdde82018-07-03 14:46:07 -0700794 final ContentResolver cr = getContext().getContentResolver();
795 final String lastActivatedTime = Secure.getStringForUser(
796 cr, Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME, getContext().getUserId());
797 if (lastActivatedTime != null) {
798 try {
799 return LocalDateTime.parse(lastActivatedTime);
800 } catch (DateTimeParseException ignored) {
801 }
802 // Uses the old epoch time.
803 try {
804 return LocalDateTime.ofInstant(
805 Instant.ofEpochMilli(Long.parseLong(lastActivatedTime)),
806 ZoneId.systemDefault());
807 } catch (DateTimeException | NumberFormatException ignored) {
808 }
809 }
810 return LocalDateTime.MIN;
811 }
812
Christine Franksf3529b22019-01-03 13:20:17 -0800813 private boolean setAppSaturationLevelInternal(String packageName, int saturationLevel) {
814 return mAppSaturationController
815 .setSaturationLevel(packageName, mCurrentUser, saturationLevel);
816 }
817
Christine Franksd154fe52019-01-04 17:17:45 -0800818 private void setColorModeInternal(@ColorMode int colorMode) {
819 if (!isColorModeAvailable(colorMode)) {
820 throw new IllegalArgumentException("Invalid colorMode: " + colorMode);
821 }
822 System.putIntForUser(getContext().getContentResolver(), System.DISPLAY_COLOR_MODE,
823 colorMode,
824 mCurrentUser);
825 }
826
Christine Franks71e003e2019-01-24 14:40:20 -0800827 private @ColorMode int getColorModeInternal() {
Christine Franksd154fe52019-01-04 17:17:45 -0800828 final ContentResolver cr = getContext().getContentResolver();
Daniel Solomonff24ba92019-04-11 19:29:31 -0700829 if (isAccessibilityEnabled()) {
Christine Franksd154fe52019-01-04 17:17:45 -0800830 // There are restrictions on the available color modes combined with a11y transforms.
Christine Franksb8d03a52019-05-08 15:08:21 -0700831 final int a11yColorMode = getContext().getResources().getInteger(
832 R.integer.config_accessibilityColorMode);
833 if (a11yColorMode >= 0) {
834 return a11yColorMode;
Christine Franksd154fe52019-01-04 17:17:45 -0800835 }
836 }
837
838 int colorMode = System.getIntForUser(cr, System.DISPLAY_COLOR_MODE, -1, mCurrentUser);
839 if (colorMode == -1) {
840 // There might be a system property controlling color mode that we need to respect; if
841 // not, this will set a suitable default.
842 colorMode = getCurrentColorModeFromSystemProperties();
843 }
844
845 // This happens when a color mode is no longer available (e.g., after system update or B&R)
846 // or the device does not support any color mode.
847 if (!isColorModeAvailable(colorMode)) {
848 if (colorMode == COLOR_MODE_BOOSTED && isColorModeAvailable(COLOR_MODE_NATURAL)) {
849 colorMode = COLOR_MODE_NATURAL;
850 } else if (colorMode == COLOR_MODE_SATURATED
851 && isColorModeAvailable(COLOR_MODE_AUTOMATIC)) {
852 colorMode = COLOR_MODE_AUTOMATIC;
853 } else if (colorMode == COLOR_MODE_AUTOMATIC
854 && isColorModeAvailable(COLOR_MODE_SATURATED)) {
855 colorMode = COLOR_MODE_SATURATED;
856 } else {
857 colorMode = -1;
858 }
859 }
860
861 return colorMode;
862 }
863
864 /**
865 * Get the current color mode from system properties, or return -1 if invalid.
866 *
Christine Franks0ada2772019-02-25 13:54:57 -0800867 * See {@link DisplayTransformManager}
Christine Franksd154fe52019-01-04 17:17:45 -0800868 */
Christine Franks78a4dd42019-02-08 11:09:30 -0800869 private @ColorMode int getCurrentColorModeFromSystemProperties() {
Christine Franksd154fe52019-01-04 17:17:45 -0800870 final int displayColorSetting = SystemProperties.getInt("persist.sys.sf.native_mode", 0);
871 if (displayColorSetting == 0) {
872 return "1.0".equals(SystemProperties.get("persist.sys.sf.color_saturation"))
873 ? COLOR_MODE_NATURAL : COLOR_MODE_BOOSTED;
874 } else if (displayColorSetting == 1) {
875 return COLOR_MODE_SATURATED;
876 } else if (displayColorSetting == 2) {
877 return COLOR_MODE_AUTOMATIC;
Christine Franks531c0612019-05-16 14:29:14 -0700878 } else if (displayColorSetting >= VENDOR_COLOR_MODE_RANGE_MIN
879 && displayColorSetting <= VENDOR_COLOR_MODE_RANGE_MAX) {
880 return displayColorSetting;
Christine Franksd154fe52019-01-04 17:17:45 -0800881 } else {
882 return -1;
883 }
884 }
885
886 private boolean isColorModeAvailable(@ColorMode int colorMode) {
887 final int[] availableColorModes = getContext().getResources().getIntArray(
888 R.array.config_availableColorModes);
889 if (availableColorModes != null) {
890 for (int mode : availableColorModes) {
891 if (mode == colorMode) {
892 return true;
893 }
894 }
895 }
896 return false;
897 }
898
Christine Franksf3529b22019-01-03 13:20:17 -0800899 private void dumpInternal(PrintWriter pw) {
900 pw.println("COLOR DISPLAY MANAGER dumpsys (color_display)");
Christine Franksa4ed3762019-01-24 15:37:04 -0800901
Christine Franks0ada2772019-02-25 13:54:57 -0800902 pw.println("Night display:");
Christine Franksa4ed3762019-01-24 15:37:04 -0800903 if (mNightDisplayTintController.isAvailable(getContext())) {
Christine Franksf3529b22019-01-03 13:20:17 -0800904 pw.println(" Activated: " + mNightDisplayTintController.isActivated());
Christine Franksa4ed3762019-01-24 15:37:04 -0800905 pw.println(" Color temp: " + mNightDisplayTintController.getColorTemperature());
Christine Franksf3529b22019-01-03 13:20:17 -0800906 } else {
907 pw.println(" Not available");
908 }
Christine Franksa4ed3762019-01-24 15:37:04 -0800909
910 pw.println("Global saturation:");
911 if (mGlobalSaturationTintController.isAvailable(getContext())) {
912 pw.println(" Activated: " + mGlobalSaturationTintController.isActivated());
913 } else {
914 pw.println(" Not available");
915 }
916
Christine Franksf3529b22019-01-03 13:20:17 -0800917 mAppSaturationController.dump(pw);
Christine Franksa4ed3762019-01-24 15:37:04 -0800918
919 pw.println("Display white balance:");
920 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
921 pw.println(" Activated: " + mDisplayWhiteBalanceTintController.isActivated());
Long Ling1d3f1892019-02-06 12:34:02 -0800922 mDisplayWhiteBalanceTintController.dump(pw);
Christine Franksa4ed3762019-01-24 15:37:04 -0800923 } else {
924 pw.println(" Not available");
925 }
926
927 pw.println("Color mode: " + getColorModeInternal());
Christine Franksf3529b22019-01-03 13:20:17 -0800928 }
929
Christine Franks57fdde82018-07-03 14:46:07 -0700930 private abstract class NightDisplayAutoMode {
931
932 public abstract void onActivated(boolean activated);
933
Justin Klaassen911e8892016-06-21 18:24:24 -0700934 public abstract void onStart();
Christine Frankse5bb03e2017-02-10 17:36:10 -0800935
Justin Klaassen911e8892016-06-21 18:24:24 -0700936 public abstract void onStop();
Christine Franks57fdde82018-07-03 14:46:07 -0700937
938 public void onCustomStartTimeChanged(LocalTime startTime) {
939 }
940
941 public void onCustomEndTimeChanged(LocalTime endTime) {
942 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700943 }
944
Christine Franks57fdde82018-07-03 14:46:07 -0700945 private final class CustomNightDisplayAutoMode extends NightDisplayAutoMode implements
946 AlarmManager.OnAlarmListener {
Justin Klaassen911e8892016-06-21 18:24:24 -0700947
948 private final AlarmManager mAlarmManager;
949 private final BroadcastReceiver mTimeChangedReceiver;
950
Christine Franks03213462017-08-25 13:57:26 -0700951 private LocalTime mStartTime;
952 private LocalTime mEndTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700953
Christine Franks03213462017-08-25 13:57:26 -0700954 private LocalDateTime mLastActivatedTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700955
Christine Franks57fdde82018-07-03 14:46:07 -0700956 CustomNightDisplayAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -0700957 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
958 mTimeChangedReceiver = new BroadcastReceiver() {
959 @Override
960 public void onReceive(Context context, Intent intent) {
961 updateActivated();
962 }
963 };
964 }
965
966 private void updateActivated() {
Christine Franks03213462017-08-25 13:57:26 -0700967 final LocalDateTime now = LocalDateTime.now();
968 final LocalDateTime start = getDateTimeBefore(mStartTime, now);
969 final LocalDateTime end = getDateTimeAfter(mEndTime, start);
970 boolean activate = now.isBefore(end);
Justin Klaassen911e8892016-06-21 18:24:24 -0700971
Christine Frankse5bb03e2017-02-10 17:36:10 -0800972 if (mLastActivatedTime != null) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800973 // Maintain the existing activated state if within the current period.
Christine Franks0ada2772019-02-25 13:54:57 -0800974 if (mLastActivatedTime.isBefore(now)
975 && mLastActivatedTime.isAfter(start)
Christine Franks03213462017-08-25 13:57:26 -0700976 && (mLastActivatedTime.isAfter(end) || now.isBefore(end))) {
Christine Franks78a4dd42019-02-08 11:09:30 -0800977 activate = mNightDisplayTintController.isActivatedSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -0700978 }
979 }
980
Christine Franks0ada2772019-02-25 13:54:57 -0800981 if (mNightDisplayTintController.isActivatedStateNotSet()
982 || (mNightDisplayTintController.isActivated() != activate)) {
Christine Franks8851ac82019-06-14 09:44:43 -0700983 mNightDisplayTintController.setActivated(activate, activate ? start : end);
Justin Klaassen911e8892016-06-21 18:24:24 -0700984 }
Christine Franks03213462017-08-25 13:57:26 -0700985
Christine Franks245ffd42018-11-16 13:45:14 -0800986 updateNextAlarm(mNightDisplayTintController.isActivated(), now);
Justin Klaassen911e8892016-06-21 18:24:24 -0700987 }
988
Christine Franks03213462017-08-25 13:57:26 -0700989 private void updateNextAlarm(@Nullable Boolean activated, @NonNull LocalDateTime now) {
Justin Klaassen4346f632016-08-08 15:01:47 -0700990 if (activated != null) {
Christine Franks03213462017-08-25 13:57:26 -0700991 final LocalDateTime next = activated ? getDateTimeAfter(mEndTime, now)
992 : getDateTimeAfter(mStartTime, now);
993 final long millis = next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
994 mAlarmManager.setExact(AlarmManager.RTC, millis, TAG, this, null);
Justin Klaassen911e8892016-06-21 18:24:24 -0700995 }
996 }
997
998 @Override
999 public void onStart() {
1000 final IntentFilter intentFilter = new IntentFilter(Intent.ACTION_TIME_CHANGED);
1001 intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
1002 getContext().registerReceiver(mTimeChangedReceiver, intentFilter);
1003
Christine Franks83cc5412018-07-03 14:46:07 -07001004 mStartTime = getNightDisplayCustomStartTimeInternal().getLocalTime();
1005 mEndTime = getNightDisplayCustomEndTimeInternal().getLocalTime();
Justin Klaassen911e8892016-06-21 18:24:24 -07001006
Christine Franks57fdde82018-07-03 14:46:07 -07001007 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Christine Frankse5bb03e2017-02-10 17:36:10 -08001008
Justin Klaassen911e8892016-06-21 18:24:24 -07001009 // Force an update to initialize state.
1010 updateActivated();
1011 }
1012
1013 @Override
1014 public void onStop() {
1015 getContext().unregisterReceiver(mTimeChangedReceiver);
1016
1017 mAlarmManager.cancel(this);
1018 mLastActivatedTime = null;
1019 }
1020
1021 @Override
1022 public void onActivated(boolean activated) {
Christine Franks57fdde82018-07-03 14:46:07 -07001023 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Christine Franks03213462017-08-25 13:57:26 -07001024 updateNextAlarm(activated, LocalDateTime.now());
Justin Klaassen911e8892016-06-21 18:24:24 -07001025 }
1026
1027 @Override
Christine Franks03213462017-08-25 13:57:26 -07001028 public void onCustomStartTimeChanged(LocalTime startTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -07001029 mStartTime = startTime;
1030 mLastActivatedTime = null;
1031 updateActivated();
1032 }
1033
1034 @Override
Christine Franks03213462017-08-25 13:57:26 -07001035 public void onCustomEndTimeChanged(LocalTime endTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -07001036 mEndTime = endTime;
1037 mLastActivatedTime = null;
1038 updateActivated();
1039 }
1040
1041 @Override
1042 public void onAlarm() {
Justin Klaassenec8837a2016-08-23 12:04:42 -07001043 Slog.d(TAG, "onAlarm");
Justin Klaassen911e8892016-06-21 18:24:24 -07001044 updateActivated();
1045 }
1046 }
1047
Christine Franks57fdde82018-07-03 14:46:07 -07001048 private final class TwilightNightDisplayAutoMode extends NightDisplayAutoMode implements
1049 TwilightListener {
Justin Klaassen911e8892016-06-21 18:24:24 -07001050
1051 private final TwilightManager mTwilightManager;
Christine Franks57fdde82018-07-03 14:46:07 -07001052 private LocalDateTime mLastActivatedTime;
Justin Klaassen911e8892016-06-21 18:24:24 -07001053
Christine Franks57fdde82018-07-03 14:46:07 -07001054 TwilightNightDisplayAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -07001055 mTwilightManager = getLocalService(TwilightManager.class);
Justin Klaassen911e8892016-06-21 18:24:24 -07001056 }
1057
Justin Klaassen908b86c2016-08-08 09:18:42 -07001058 private void updateActivated(TwilightState state) {
Justin Klaassen3da4c442017-05-05 15:19:33 -07001059 if (state == null) {
1060 // If there isn't a valid TwilightState then just keep the current activated
1061 // state.
1062 return;
1063 }
1064
1065 boolean activate = state.isNight();
Christine Franks57fdde82018-07-03 14:46:07 -07001066 if (mLastActivatedTime != null) {
Christine Franks03213462017-08-25 13:57:26 -07001067 final LocalDateTime now = LocalDateTime.now();
1068 final LocalDateTime sunrise = state.sunrise();
1069 final LocalDateTime sunset = state.sunset();
Christine Frankse5bb03e2017-02-10 17:36:10 -08001070 // Maintain the existing activated state if within the current period.
Christine Franks57fdde82018-07-03 14:46:07 -07001071 if (mLastActivatedTime.isBefore(now) && (mLastActivatedTime.isBefore(sunrise)
1072 ^ mLastActivatedTime.isBefore(sunset))) {
Christine Franks78a4dd42019-02-08 11:09:30 -08001073 activate = mNightDisplayTintController.isActivatedSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -07001074 }
1075 }
Justin Klaassen908b86c2016-08-08 09:18:42 -07001076
Christine Franks245ffd42018-11-16 13:45:14 -08001077 if (mNightDisplayTintController.isActivatedStateNotSet() || (
1078 mNightDisplayTintController.isActivated() != activate)) {
Christine Franks83cc5412018-07-03 14:46:07 -07001079 mNightDisplayTintController.setActivated(activate);
Justin Klaassen908b86c2016-08-08 09:18:42 -07001080 }
Justin Klaassen911e8892016-06-21 18:24:24 -07001081 }
1082
1083 @Override
Christine Franks57fdde82018-07-03 14:46:07 -07001084 public void onActivated(boolean activated) {
1085 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
1086 }
1087
1088 @Override
Justin Klaassen911e8892016-06-21 18:24:24 -07001089 public void onStart() {
1090 mTwilightManager.registerListener(this, mHandler);
Christine Franks57fdde82018-07-03 14:46:07 -07001091 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -07001092
1093 // Force an update to initialize state.
Justin Klaassen908b86c2016-08-08 09:18:42 -07001094 updateActivated(mTwilightManager.getLastTwilightState());
Justin Klaassen911e8892016-06-21 18:24:24 -07001095 }
1096
1097 @Override
1098 public void onStop() {
1099 mTwilightManager.unregisterListener(this);
Christine Franks57fdde82018-07-03 14:46:07 -07001100 mLastActivatedTime = null;
Justin Klaassen908b86c2016-08-08 09:18:42 -07001101 }
1102
1103 @Override
1104 public void onTwilightStateChanged(@Nullable TwilightState state) {
Justin Klaassenec8837a2016-08-23 12:04:42 -07001105 Slog.d(TAG, "onTwilightStateChanged: isNight="
1106 + (state == null ? null : state.isNight()));
Justin Klaassen908b86c2016-08-08 09:18:42 -07001107 updateActivated(state);
Justin Klaassen911e8892016-06-21 18:24:24 -07001108 }
1109 }
Justin Klaassen639214e2016-07-14 21:00:06 -07001110
1111 /**
1112 * Interpolates between two 4x4 color transform matrices (in column-major order).
1113 */
1114 private static class ColorMatrixEvaluator implements TypeEvaluator<float[]> {
1115
1116 /**
1117 * Result matrix returned by {@link #evaluate(float, float[], float[])}.
1118 */
1119 private final float[] mResultMatrix = new float[16];
1120
1121 @Override
1122 public float[] evaluate(float fraction, float[] startValue, float[] endValue) {
1123 for (int i = 0; i < mResultMatrix.length; i++) {
1124 mResultMatrix[i] = MathUtils.lerp(startValue[i], endValue[i], fraction);
1125 }
1126 return mResultMatrix;
1127 }
1128 }
Christine Franks39b03112018-07-03 14:46:07 -07001129
Christine Franks83cc5412018-07-03 14:46:07 -07001130 private final class NightDisplayTintController extends TintController {
1131
Christine Franksa4ed3762019-01-24 15:37:04 -08001132 private final float[] mMatrix = new float[16];
Christine Franks83cc5412018-07-03 14:46:07 -07001133 private final float[] mColorTempCoefficients = new float[9];
Christine Franksa4ed3762019-01-24 15:37:04 -08001134
1135 private Boolean mIsAvailable;
Christine Franks83cc5412018-07-03 14:46:07 -07001136 private Integer mColorTemp;
1137
1138 /**
1139 * Set coefficients based on whether the color matrix is linear or not.
1140 */
1141 @Override
1142 public void setUp(Context context, boolean needsLinear) {
1143 final String[] coefficients = context.getResources().getStringArray(needsLinear
1144 ? R.array.config_nightDisplayColorTemperatureCoefficients
1145 : R.array.config_nightDisplayColorTemperatureCoefficientsNative);
1146 for (int i = 0; i < 9 && i < coefficients.length; i++) {
1147 mColorTempCoefficients[i] = Float.parseFloat(coefficients[i]);
1148 }
1149 }
1150
1151 @Override
1152 public void setMatrix(int cct) {
1153 if (mMatrix.length != 16) {
1154 Slog.d(TAG, "The display transformation matrix must be 4x4");
1155 return;
1156 }
1157
1158 Matrix.setIdentityM(mMatrix, 0);
1159
1160 final float squareTemperature = cct * cct;
1161 final float red = squareTemperature * mColorTempCoefficients[0]
1162 + cct * mColorTempCoefficients[1] + mColorTempCoefficients[2];
1163 final float green = squareTemperature * mColorTempCoefficients[3]
1164 + cct * mColorTempCoefficients[4] + mColorTempCoefficients[5];
1165 final float blue = squareTemperature * mColorTempCoefficients[6]
1166 + cct * mColorTempCoefficients[7] + mColorTempCoefficients[8];
1167 mMatrix[0] = red;
1168 mMatrix[5] = green;
1169 mMatrix[10] = blue;
1170 }
1171
1172 @Override
1173 public float[] getMatrix() {
1174 return isActivated() ? mMatrix : MATRIX_IDENTITY;
1175 }
1176
1177 @Override
1178 public void setActivated(Boolean activated) {
Christine Franks8851ac82019-06-14 09:44:43 -07001179 setActivated(activated, LocalDateTime.now());
1180 }
1181
1182 /**
1183 * Use directly when it is important that the last activation time be exact (for example, an
1184 * automatic change). Otherwise use {@link #setActivated(Boolean)}.
1185 */
1186 public void setActivated(Boolean activated, @NonNull LocalDateTime lastActivationTime) {
Christine Franks83cc5412018-07-03 14:46:07 -07001187 if (activated == null) {
1188 super.setActivated(null);
1189 return;
1190 }
1191
1192 boolean activationStateChanged = activated != isActivated();
1193
1194 if (!isActivatedStateNotSet() && activationStateChanged) {
1195 // This is a true state change, so set this as the last activation time.
1196 Secure.putStringForUser(getContext().getContentResolver(),
1197 Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
Christine Franks8851ac82019-06-14 09:44:43 -07001198 lastActivationTime.toString(),
Christine Franks83cc5412018-07-03 14:46:07 -07001199 mCurrentUser);
1200 }
1201
1202 if (isActivatedStateNotSet() || activationStateChanged) {
1203 super.setActivated(activated);
Christine Franks78a4dd42019-02-08 11:09:30 -08001204 if (isActivatedSetting() != activated) {
1205 Secure.putIntForUser(getContext().getContentResolver(),
1206 Secure.NIGHT_DISPLAY_ACTIVATED,
1207 activated ? 1 : 0, mCurrentUser);
1208 }
Christine Franks83cc5412018-07-03 14:46:07 -07001209 onActivated(activated);
1210 }
1211 }
1212
1213 @Override
1214 public int getLevel() {
1215 return LEVEL_COLOR_MATRIX_NIGHT_DISPLAY;
1216 }
1217
Christine Franksa4ed3762019-01-24 15:37:04 -08001218 @Override
1219 public boolean isAvailable(Context context) {
1220 if (mIsAvailable == null) {
1221 mIsAvailable = ColorDisplayManager.isNightDisplayAvailable(context);
1222 }
1223 return mIsAvailable;
1224 }
1225
Christine Franks78a4dd42019-02-08 11:09:30 -08001226 private void onActivated(boolean activated) {
Christine Franks83cc5412018-07-03 14:46:07 -07001227 Slog.i(TAG, activated ? "Turning on night display" : "Turning off night display");
1228 if (mNightDisplayAutoMode != null) {
1229 mNightDisplayAutoMode.onActivated(activated);
1230 }
1231
Christine Franksa4ed3762019-01-24 15:37:04 -08001232 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
Christine Franks83cc5412018-07-03 14:46:07 -07001233 updateDisplayWhiteBalanceStatus();
1234 }
1235
1236 mHandler.sendEmptyMessage(MSG_APPLY_NIGHT_DISPLAY_ANIMATED);
1237 }
1238
1239 int getColorTemperature() {
1240 return mColorTemp != null ? clampNightDisplayColorTemperature(mColorTemp)
Christine Franks78a4dd42019-02-08 11:09:30 -08001241 : getColorTemperatureSetting();
Christine Franks83cc5412018-07-03 14:46:07 -07001242 }
1243
1244 boolean setColorTemperature(int temperature) {
1245 mColorTemp = temperature;
1246 final boolean success = Secure.putIntForUser(getContext().getContentResolver(),
1247 Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE, temperature, mCurrentUser);
1248 onColorTemperatureChanged(temperature);
1249 return success;
1250 }
1251
1252 void onColorTemperatureChanged(int temperature) {
1253 setMatrix(temperature);
1254 mHandler.sendEmptyMessage(MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE);
1255 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001256
1257 boolean isActivatedSetting() {
Christine Franks44782612019-03-07 17:25:39 -08001258 if (mCurrentUser == UserHandle.USER_NULL) {
1259 return false;
1260 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001261 return Secure.getIntForUser(getContext().getContentResolver(),
1262 Secure.NIGHT_DISPLAY_ACTIVATED, 0, mCurrentUser) == 1;
1263 }
1264
1265 int getColorTemperatureSetting() {
Christine Franks44782612019-03-07 17:25:39 -08001266 if (mCurrentUser == UserHandle.USER_NULL) {
1267 return NOT_SET;
1268 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001269 return clampNightDisplayColorTemperature(Secure.getIntForUser(
1270 getContext().getContentResolver(), Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE,
1271 NOT_SET,
1272 mCurrentUser));
1273 }
1274
1275 private int clampNightDisplayColorTemperature(int colorTemperature) {
1276 if (colorTemperature == NOT_SET) {
1277 colorTemperature = getContext().getResources().getInteger(
1278 R.integer.config_nightDisplayColorTemperatureDefault);
1279 }
1280 final int minimumTemperature = ColorDisplayManager
1281 .getMinimumColorTemperature(getContext());
1282 final int maximumTemperature = ColorDisplayManager
1283 .getMaximumColorTemperature(getContext());
1284 if (colorTemperature < minimumTemperature) {
1285 colorTemperature = minimumTemperature;
1286 } else if (colorTemperature > maximumTemperature) {
1287 colorTemperature = maximumTemperature;
1288 }
1289
1290 return colorTemperature;
1291 }
Christine Franks83cc5412018-07-03 14:46:07 -07001292 }
1293
Christine Franks245ffd42018-11-16 13:45:14 -08001294 /**
1295 * Local service that allows color transforms to be enabled from other system services.
1296 */
1297 public final class ColorDisplayServiceInternal {
1298
1299 /**
1300 * Set the current CCT value for the display white balance transform, and if the transform
1301 * is enabled, apply it.
1302 *
1303 * @param cct the color temperature in Kelvin.
1304 */
1305 public boolean setDisplayWhiteBalanceColorTemperature(int cct) {
1306 // Update the transform matrix even if it can't be applied.
Christine Franks245ffd42018-11-16 13:45:14 -08001307 mDisplayWhiteBalanceTintController.setMatrix(cct);
1308
1309 if (mDisplayWhiteBalanceTintController.isActivated()) {
Christine Franksc7fb9452019-02-04 08:45:33 -08001310 mHandler.sendEmptyMessage(MSG_APPLY_DISPLAY_WHITE_BALANCE);
Christine Franks245ffd42018-11-16 13:45:14 -08001311 return true;
1312 }
1313 return false;
1314 }
1315
1316 /**
Daniel Solomon37816412019-04-10 15:17:41 -07001317 * Reset the CCT value for the display white balance transform to its default value.
1318 */
1319 public boolean resetDisplayWhiteBalanceColorTemperature() {
Anthony Han00a490b2019-08-26 14:00:28 -07001320 int temperatureDefault = getContext().getResources()
1321 .getInteger(R.integer.config_displayWhiteBalanceColorTemperatureDefault);
1322 Slog.d(TAG, "resetDisplayWhiteBalanceColorTemperature: " + temperatureDefault);
1323 return setDisplayWhiteBalanceColorTemperature(temperatureDefault);
Daniel Solomon37816412019-04-10 15:17:41 -07001324 }
1325
1326 /**
Christine Franks245ffd42018-11-16 13:45:14 -08001327 * Sets the listener and returns whether display white balance is currently enabled.
1328 */
1329 public boolean setDisplayWhiteBalanceListener(DisplayWhiteBalanceListener listener) {
1330 mDisplayWhiteBalanceListener = listener;
1331 return mDisplayWhiteBalanceTintController.isActivated();
1332 }
Daniel Solomon8b72c5b2018-11-25 11:07:13 -08001333
Christine Franksf3529b22019-01-03 13:20:17 -08001334 /**
Christine Franks66783a82019-03-28 11:45:56 -07001335 * Returns whether Display white balance is currently enabled.
1336 */
1337 public boolean isDisplayWhiteBalanceEnabled() {
1338 return isDisplayWhiteBalanceSettingEnabled();
1339 }
1340
1341 /**
Christine Franksf3529b22019-01-03 13:20:17 -08001342 * Adds a {@link WeakReference<ColorTransformController>} for a newly started activity, and
1343 * invokes {@link ColorTransformController#applyAppSaturation(float[], float[])} if needed.
1344 */
Christine Franks55194dc2019-01-15 13:47:06 -08001345 public boolean attachColorTransformController(String packageName, @UserIdInt int userId,
Christine Franksf3529b22019-01-03 13:20:17 -08001346 WeakReference<ColorTransformController> controller) {
1347 return mAppSaturationController
Christine Franks55194dc2019-01-15 13:47:06 -08001348 .addColorTransformController(packageName, userId, controller);
Christine Franksf3529b22019-01-03 13:20:17 -08001349 }
Christine Franks245ffd42018-11-16 13:45:14 -08001350 }
1351
1352 /**
1353 * Listener for changes in display white balance status.
1354 */
1355 public interface DisplayWhiteBalanceListener {
1356
1357 /**
1358 * Notify that the display white balance status has changed, either due to preemption by
1359 * another transform or the feature being turned off.
1360 */
Christine Franks66783a82019-03-28 11:45:56 -07001361 void onDisplayWhiteBalanceStatusChanged(boolean activated);
Christine Franks245ffd42018-11-16 13:45:14 -08001362 }
1363
Christine Franks09c229e2018-12-14 10:37:40 -08001364 private final class TintHandler extends Handler {
1365
Christine Franks83cc5412018-07-03 14:46:07 -07001366 private TintHandler(Looper looper) {
Christine Franks09c229e2018-12-14 10:37:40 -08001367 super(looper, null, true /* async */);
1368 }
1369
1370 @Override
1371 public void handleMessage(Message msg) {
1372 switch (msg.what) {
Christine Franks27912a32019-04-02 10:43:10 -07001373 case MSG_USER_CHANGED:
1374 onUserChanged(msg.arg1);
1375 break;
1376 case MSG_SET_UP:
1377 setUp();
1378 break;
Christine Franks09c229e2018-12-14 10:37:40 -08001379 case MSG_APPLY_GLOBAL_SATURATION:
1380 mGlobalSaturationTintController.setMatrix(msg.arg1);
1381 applyTint(mGlobalSaturationTintController, false);
1382 break;
Christine Franks83cc5412018-07-03 14:46:07 -07001383 case MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE:
1384 applyTint(mNightDisplayTintController, true);
1385 break;
1386 case MSG_APPLY_NIGHT_DISPLAY_ANIMATED:
1387 applyTint(mNightDisplayTintController, false);
1388 break;
Christine Franksc7fb9452019-02-04 08:45:33 -08001389 case MSG_APPLY_DISPLAY_WHITE_BALANCE:
1390 applyTint(mDisplayWhiteBalanceTintController, false);
1391 break;
Christine Franks09c229e2018-12-14 10:37:40 -08001392 }
1393 }
1394 }
1395
Christine Franksf3529b22019-01-03 13:20:17 -08001396 /**
1397 * Interface for applying transforms to a given AppWindow.
1398 */
1399 public interface ColorTransformController {
1400
Christine Franksd154fe52019-01-04 17:17:45 -08001401 /**
1402 * Apply the given saturation (grayscale) matrix to the associated AppWindow.
1403 */
Christine Franksf3529b22019-01-03 13:20:17 -08001404 void applyAppSaturation(@Size(9) float[] matrix, @Size(3) float[] translation);
1405 }
1406
Christine Franks83cc5412018-07-03 14:46:07 -07001407 @VisibleForTesting
1408 final class BinderService extends IColorDisplayManager.Stub {
Christine Franks57fdde82018-07-03 14:46:07 -07001409
Christine Franks39b03112018-07-03 14:46:07 -07001410 @Override
Christine Franksd154fe52019-01-04 17:17:45 -08001411 public void setColorMode(int colorMode) {
1412 getContext().enforceCallingOrSelfPermission(
1413 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1414 "Permission required to set display color mode");
1415 final long token = Binder.clearCallingIdentity();
1416 try {
1417 setColorModeInternal(colorMode);
1418 } finally {
1419 Binder.restoreCallingIdentity(token);
1420 }
1421 }
1422
1423 @Override
1424 public int getColorMode() {
1425 final long token = Binder.clearCallingIdentity();
1426 try {
1427 return getColorModeInternal();
1428 } finally {
1429 Binder.restoreCallingIdentity(token);
1430 }
1431 }
1432
1433 @Override
Christine Franks39b03112018-07-03 14:46:07 -07001434 public boolean isDeviceColorManaged() {
1435 final long token = Binder.clearCallingIdentity();
1436 try {
1437 return isDeviceColorManagedInternal();
1438 } finally {
1439 Binder.restoreCallingIdentity(token);
1440 }
1441 }
Christine Franks09c229e2018-12-14 10:37:40 -08001442
1443 @Override
1444 public boolean setSaturationLevel(int level) {
1445 final boolean hasTransformsPermission = getContext()
1446 .checkCallingPermission(Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS)
1447 == PackageManager.PERMISSION_GRANTED;
1448 final boolean hasLegacyPermission = getContext()
1449 .checkCallingPermission(Manifest.permission.CONTROL_DISPLAY_SATURATION)
1450 == PackageManager.PERMISSION_GRANTED;
1451 if (!hasTransformsPermission && !hasLegacyPermission) {
1452 throw new SecurityException("Permission required to set display saturation level");
1453 }
1454 final long token = Binder.clearCallingIdentity();
1455 try {
1456 final Message message = mHandler.obtainMessage(MSG_APPLY_GLOBAL_SATURATION);
1457 message.arg1 = level;
1458 mHandler.sendMessage(message);
1459 } finally {
1460 Binder.restoreCallingIdentity(token);
1461 }
1462 return true;
1463 }
Christine Franksf3529b22019-01-03 13:20:17 -08001464
1465 @Override
Christine Franks6d21d342019-02-07 15:09:03 -08001466 public boolean isSaturationActivated() {
1467 getContext().enforceCallingPermission(
1468 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1469 "Permission required to get display saturation level");
1470 final long token = Binder.clearCallingIdentity();
1471 try {
1472 return !mGlobalSaturationTintController.isActivatedStateNotSet()
1473 && mGlobalSaturationTintController.isActivated();
1474 } finally {
1475 Binder.restoreCallingIdentity(token);
1476 }
1477 }
1478
1479 @Override
Christine Franksf3529b22019-01-03 13:20:17 -08001480 public boolean setAppSaturationLevel(String packageName, int level) {
1481 getContext().enforceCallingPermission(
1482 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1483 "Permission required to set display saturation level");
1484 final long token = Binder.clearCallingIdentity();
1485 try {
1486 return setAppSaturationLevelInternal(packageName, level);
1487 } finally {
1488 Binder.restoreCallingIdentity(token);
1489 }
1490 }
1491
Christine Franks55194dc2019-01-15 13:47:06 -08001492 public int getTransformCapabilities() {
1493 getContext().enforceCallingPermission(
1494 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1495 "Permission required to query transform capabilities");
1496 final long token = Binder.clearCallingIdentity();
1497 try {
1498 return getTransformCapabilitiesInternal();
1499 } finally {
1500 Binder.restoreCallingIdentity(token);
1501 }
1502 }
1503
Christine Franksf3529b22019-01-03 13:20:17 -08001504 @Override
Christine Franks83cc5412018-07-03 14:46:07 -07001505 public boolean setNightDisplayActivated(boolean activated) {
1506 getContext().enforceCallingOrSelfPermission(
1507 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1508 "Permission required to set night display activated");
1509 final long token = Binder.clearCallingIdentity();
1510 try {
1511 mNightDisplayTintController.setActivated(activated);
1512 return true;
1513 } finally {
1514 Binder.restoreCallingIdentity(token);
1515 }
1516 }
1517
1518 @Override
1519 public boolean isNightDisplayActivated() {
1520 final long token = Binder.clearCallingIdentity();
1521 try {
1522 return mNightDisplayTintController.isActivated();
1523 } finally {
1524 Binder.restoreCallingIdentity(token);
1525 }
1526 }
1527
1528 @Override
1529 public boolean setNightDisplayColorTemperature(int temperature) {
1530 getContext().enforceCallingOrSelfPermission(
1531 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1532 "Permission required to set night display temperature");
1533 final long token = Binder.clearCallingIdentity();
1534 try {
1535 return mNightDisplayTintController.setColorTemperature(temperature);
1536 } finally {
1537 Binder.restoreCallingIdentity(token);
1538 }
1539 }
1540
1541 @Override
1542 public int getNightDisplayColorTemperature() {
1543 final long token = Binder.clearCallingIdentity();
1544 try {
1545 return mNightDisplayTintController.getColorTemperature();
1546 } finally {
1547 Binder.restoreCallingIdentity(token);
1548 }
1549 }
1550
1551 @Override
1552 public boolean setNightDisplayAutoMode(int autoMode) {
1553 getContext().enforceCallingOrSelfPermission(
1554 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1555 "Permission required to set night display auto mode");
1556 final long token = Binder.clearCallingIdentity();
1557 try {
1558 return setNightDisplayAutoModeInternal(autoMode);
1559 } finally {
1560 Binder.restoreCallingIdentity(token);
1561 }
1562 }
1563
1564 @Override
1565 public int getNightDisplayAutoMode() {
1566 getContext().enforceCallingOrSelfPermission(
1567 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1568 "Permission required to get night display auto mode");
1569 final long token = Binder.clearCallingIdentity();
1570 try {
1571 return getNightDisplayAutoModeInternal();
1572 } finally {
1573 Binder.restoreCallingIdentity(token);
1574 }
1575 }
1576
1577 @Override
1578 public int getNightDisplayAutoModeRaw() {
1579 final long token = Binder.clearCallingIdentity();
1580 try {
1581 return getNightDisplayAutoModeRawInternal();
1582 } finally {
1583 Binder.restoreCallingIdentity(token);
1584 }
1585 }
1586
1587 @Override
1588 public boolean setNightDisplayCustomStartTime(Time startTime) {
1589 getContext().enforceCallingOrSelfPermission(
1590 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1591 "Permission required to set night display custom start time");
1592 final long token = Binder.clearCallingIdentity();
1593 try {
1594 return setNightDisplayCustomStartTimeInternal(startTime);
1595 } finally {
1596 Binder.restoreCallingIdentity(token);
1597 }
1598 }
1599
1600 @Override
1601 public Time getNightDisplayCustomStartTime() {
1602 final long token = Binder.clearCallingIdentity();
1603 try {
1604 return getNightDisplayCustomStartTimeInternal();
1605 } finally {
1606 Binder.restoreCallingIdentity(token);
1607 }
1608 }
1609
1610 @Override
1611 public boolean setNightDisplayCustomEndTime(Time endTime) {
1612 getContext().enforceCallingOrSelfPermission(
1613 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1614 "Permission required to set night display custom end time");
1615 final long token = Binder.clearCallingIdentity();
1616 try {
1617 return setNightDisplayCustomEndTimeInternal(endTime);
1618 } finally {
1619 Binder.restoreCallingIdentity(token);
1620 }
1621 }
1622
1623 @Override
1624 public Time getNightDisplayCustomEndTime() {
1625 final long token = Binder.clearCallingIdentity();
1626 try {
1627 return getNightDisplayCustomEndTimeInternal();
1628 } finally {
1629 Binder.restoreCallingIdentity(token);
1630 }
1631 }
1632
1633 @Override
Christine Franks66783a82019-03-28 11:45:56 -07001634 public boolean setDisplayWhiteBalanceEnabled(boolean enabled) {
1635 getContext().enforceCallingOrSelfPermission(
1636 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1637 "Permission required to set night display activated");
1638 final long token = Binder.clearCallingIdentity();
1639 try {
1640 return setDisplayWhiteBalanceSettingEnabled(enabled);
1641 } finally {
1642 Binder.restoreCallingIdentity(token);
1643 }
1644 }
1645
1646 @Override
1647 public boolean isDisplayWhiteBalanceEnabled() {
1648 final long token = Binder.clearCallingIdentity();
1649 try {
1650 return isDisplayWhiteBalanceSettingEnabled();
1651 } finally {
1652 Binder.restoreCallingIdentity(token);
1653 }
1654 }
1655
1656 @Override
Christine Franksf3529b22019-01-03 13:20:17 -08001657 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Christine Franksd154fe52019-01-04 17:17:45 -08001658 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) {
1659 return;
1660 }
Christine Franksf3529b22019-01-03 13:20:17 -08001661
1662 final long token = Binder.clearCallingIdentity();
1663 try {
1664 dumpInternal(pw);
1665 } finally {
1666 Binder.restoreCallingIdentity(token);
1667 }
1668 }
Christine Franks39b03112018-07-03 14:46:07 -07001669 }
Justin Klaassen911e8892016-06-21 18:24:24 -07001670}