blob: b2420b5b320eae22fa683387508bbbfc874181bb [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;
Christine Franks55194dc2019-01-15 13:47:06 -080066import android.view.SurfaceControl;
Christine Franks9114f462019-01-04 11:27:30 -080067import android.view.accessibility.AccessibilityManager;
Justin Klaassen639214e2016-07-14 21:00:06 -070068import android.view.animation.AnimationUtils;
Daniel Solomona4ab5672019-01-22 19:35:55 -080069
Christine Franks39b03112018-07-03 14:46:07 -070070import com.android.internal.R;
Christine Franks57fdde82018-07-03 14:46:07 -070071import com.android.internal.annotations.VisibleForTesting;
Christine Franksf3529b22019-01-03 13:20:17 -080072import com.android.internal.util.DumpUtils;
Christine Franks57fdde82018-07-03 14:46:07 -070073import com.android.server.DisplayThread;
Justin Klaassen911e8892016-06-21 18:24:24 -070074import com.android.server.SystemService;
75import com.android.server.twilight.TwilightListener;
76import com.android.server.twilight.TwilightManager;
77import com.android.server.twilight.TwilightState;
Christine Franksa4ed3762019-01-24 15:37:04 -080078
Christine Franksf3529b22019-01-03 13:20:17 -080079import java.io.FileDescriptor;
Daniel Solomon8b72c5b2018-11-25 11:07:13 -080080import java.io.PrintWriter;
Christine Franksf3529b22019-01-03 13:20:17 -080081import java.lang.ref.WeakReference;
Christine Franks57fdde82018-07-03 14:46:07 -070082import java.time.DateTimeException;
83import java.time.Instant;
Christine Franks03213462017-08-25 13:57:26 -070084import java.time.LocalDateTime;
85import java.time.LocalTime;
86import java.time.ZoneId;
Christine Franks57fdde82018-07-03 14:46:07 -070087import java.time.format.DateTimeParseException;
Christine Franks8ad71492017-10-24 19:04:22 -070088
Justin Klaassen911e8892016-06-21 18:24:24 -070089/**
Christine Franks39b03112018-07-03 14:46:07 -070090 * Controls the display's color transforms.
Justin Klaassen911e8892016-06-21 18:24:24 -070091 */
Christine Franks57fdde82018-07-03 14:46:07 -070092public final class ColorDisplayService extends SystemService {
Justin Klaassen911e8892016-06-21 18:24:24 -070093
Christine Franks7119e992019-03-14 17:28:21 -070094 static final String TAG = "ColorDisplayService";
Christine Franks7b83b4282017-01-18 14:55:00 -080095
96 /**
Justin Klaassen639214e2016-07-14 21:00:06 -070097 * The identity matrix, used if one of the given matrices is {@code null}.
98 */
Christine Franks6caba0f2019-03-07 17:48:25 -080099 static final float[] MATRIX_IDENTITY = new float[16];
Christine Franks57fdde82018-07-03 14:46:07 -0700100
Justin Klaassen639214e2016-07-14 21:00:06 -0700101 static {
102 Matrix.setIdentityM(MATRIX_IDENTITY, 0);
103 }
104
Christine Franks7119e992019-03-14 17:28:21 -0700105 /**
106 * The transition time, in milliseconds, for Night Display to turn on/off.
107 */
108 private static final long TRANSITION_DURATION = 3000L;
109
Christine Franks27912a32019-04-02 10:43:10 -0700110 private static final int MSG_USER_CHANGED = 0;
111 private static final int MSG_SET_UP = 1;
112 private static final int MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE = 2;
113 private static final int MSG_APPLY_NIGHT_DISPLAY_ANIMATED = 3;
114 private static final int MSG_APPLY_GLOBAL_SATURATION = 4;
115 private static final int MSG_APPLY_DISPLAY_WHITE_BALANCE = 5;
Christine Franks09c229e2018-12-14 10:37:40 -0800116
Justin Klaassen639214e2016-07-14 21:00:06 -0700117 /**
Christine Franks83cc5412018-07-03 14:46:07 -0700118 * Return value if a setting has not been set.
119 */
120 private static final int NOT_SET = -1;
121
122 /**
Justin Klaassen639214e2016-07-14 21:00:06 -0700123 * Evaluator used to animate color matrix transitions.
124 */
125 private static final ColorMatrixEvaluator COLOR_MATRIX_EVALUATOR = new ColorMatrixEvaluator();
126
Christine Franks83cc5412018-07-03 14:46:07 -0700127 private final NightDisplayTintController mNightDisplayTintController =
128 new NightDisplayTintController();
Christine Franks245ffd42018-11-16 13:45:14 -0800129
Long Ling1d3f1892019-02-06 12:34:02 -0800130 @VisibleForTesting
131 final DisplayWhiteBalanceTintController mDisplayWhiteBalanceTintController =
132 new DisplayWhiteBalanceTintController();
Christine Franks245ffd42018-11-16 13:45:14 -0800133
Christine Franks7119e992019-03-14 17:28:21 -0700134 private final TintController mGlobalSaturationTintController =
135 new GlobalSaturationTintController();
Christine Franks09c229e2018-12-14 10:37:40 -0800136
Christine Franks9114f462019-01-04 11:27:30 -0800137 /**
138 * Matrix and offset used for converting color to grayscale.
139 */
140 private static final float[] MATRIX_GRAYSCALE = new float[]{
141 .2126f, .2126f, .2126f, 0f,
142 .7152f, .7152f, .7152f, 0f,
143 .0722f, .0722f, .0722f, 0f,
144 0f, 0f, 0f, 1f
145 };
146
147 /**
148 * Matrix and offset used for luminance inversion. Represents a transform from RGB to YIQ color
149 * space, rotation around the Y axis by 180 degrees, transform back to RGB color space, and
150 * subtraction from 1. The last row represents a non-multiplied addition, see surfaceflinger's
151 * ProgramCache for full implementation details.
152 */
Christine Franksd154fe52019-01-04 17:17:45 -0800153 private static final float[] MATRIX_INVERT_COLOR = new float[]{
Christine Franks9114f462019-01-04 11:27:30 -0800154 0.402f, -0.598f, -0.599f, 0f,
155 -1.174f, -0.174f, -1.175f, 0f,
156 -0.228f, -0.228f, 0.772f, 0f,
157 1f, 1f, 1f, 1f
158 };
159
Justin Klaassen2696d992016-07-11 21:26:46 -0700160 private final Handler mHandler;
161
Christine Franksf3529b22019-01-03 13:20:17 -0800162 private final AppSaturationController mAppSaturationController = new AppSaturationController();
163
Justin Klaassen911e8892016-06-21 18:24:24 -0700164 private int mCurrentUser = UserHandle.USER_NULL;
Justin Klaassen2696d992016-07-11 21:26:46 -0700165 private ContentObserver mUserSetupObserver;
Justin Klaassen911e8892016-06-21 18:24:24 -0700166 private boolean mBootCompleted;
167
Christine Franks57fdde82018-07-03 14:46:07 -0700168 private ContentObserver mContentObserver;
Christine Franks57fdde82018-07-03 14:46:07 -0700169
Christine Franks245ffd42018-11-16 13:45:14 -0800170 private DisplayWhiteBalanceListener mDisplayWhiteBalanceListener;
171
Christine Franks57fdde82018-07-03 14:46:07 -0700172 private NightDisplayAutoMode mNightDisplayAutoMode;
Justin Klaassen911e8892016-06-21 18:24:24 -0700173
Christine Franks5397f032017-11-01 18:35:16 -0700174 public ColorDisplayService(Context context) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700175 super(context);
Christine Franks83cc5412018-07-03 14:46:07 -0700176 mHandler = new TintHandler(DisplayThread.get().getLooper());
Justin Klaassen911e8892016-06-21 18:24:24 -0700177 }
178
179 @Override
180 public void onStart() {
Christine Franks39b03112018-07-03 14:46:07 -0700181 publishBinderService(Context.COLOR_DISPLAY_SERVICE, new BinderService());
Christine Franks245ffd42018-11-16 13:45:14 -0800182 publishLocalService(ColorDisplayServiceInternal.class, new ColorDisplayServiceInternal());
Christine Franks0ada2772019-02-25 13:54:57 -0800183 publishLocalService(DisplayTransformManager.class, new DisplayTransformManager());
Justin Klaassen911e8892016-06-21 18:24:24 -0700184 }
185
186 @Override
Justin Klaassen2696d992016-07-11 21:26:46 -0700187 public void onBootPhase(int phase) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800188 if (phase >= PHASE_BOOT_COMPLETED) {
Justin Klaassen2696d992016-07-11 21:26:46 -0700189 mBootCompleted = true;
190
191 // Register listeners now that boot is complete.
192 if (mCurrentUser != UserHandle.USER_NULL && mUserSetupObserver == null) {
Christine Franks27912a32019-04-02 10:43:10 -0700193 mHandler.sendEmptyMessage(MSG_SET_UP);
Justin Klaassen2696d992016-07-11 21:26:46 -0700194 }
195 }
196 }
197
198 @Override
Justin Klaassen911e8892016-06-21 18:24:24 -0700199 public void onStartUser(int userHandle) {
200 super.onStartUser(userHandle);
201
Justin Klaassen911e8892016-06-21 18:24:24 -0700202 if (mCurrentUser == UserHandle.USER_NULL) {
Christine Franks27912a32019-04-02 10:43:10 -0700203 final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
204 message.arg1 = userHandle;
205 mHandler.sendMessage(message);
Justin Klaassen911e8892016-06-21 18:24:24 -0700206 }
207 }
208
209 @Override
210 public void onSwitchUser(int userHandle) {
211 super.onSwitchUser(userHandle);
212
Christine Franks27912a32019-04-02 10:43:10 -0700213 final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
214 message.arg1 = userHandle;
215 mHandler.sendMessage(message);
Justin Klaassen911e8892016-06-21 18:24:24 -0700216 }
217
218 @Override
219 public void onStopUser(int userHandle) {
220 super.onStopUser(userHandle);
221
Justin Klaassen911e8892016-06-21 18:24:24 -0700222 if (mCurrentUser == userHandle) {
Christine Franks27912a32019-04-02 10:43:10 -0700223 final Message message = mHandler.obtainMessage(MSG_USER_CHANGED);
224 message.arg1 = UserHandle.USER_NULL;
225 mHandler.sendMessage(message);
Justin Klaassen911e8892016-06-21 18:24:24 -0700226 }
227 }
228
Justin Klaassen2696d992016-07-11 21:26:46 -0700229 private void onUserChanged(int userHandle) {
230 final ContentResolver cr = getContext().getContentResolver();
Justin Klaassen911e8892016-06-21 18:24:24 -0700231
Justin Klaassen2696d992016-07-11 21:26:46 -0700232 if (mCurrentUser != UserHandle.USER_NULL) {
233 if (mUserSetupObserver != null) {
234 cr.unregisterContentObserver(mUserSetupObserver);
235 mUserSetupObserver = null;
236 } else if (mBootCompleted) {
237 tearDown();
238 }
239 }
240
241 mCurrentUser = userHandle;
242
243 if (mCurrentUser != UserHandle.USER_NULL) {
244 if (!isUserSetupCompleted(cr, mCurrentUser)) {
245 mUserSetupObserver = new ContentObserver(mHandler) {
246 @Override
247 public void onChange(boolean selfChange, Uri uri) {
248 if (isUserSetupCompleted(cr, mCurrentUser)) {
249 cr.unregisterContentObserver(this);
250 mUserSetupObserver = null;
251
252 if (mBootCompleted) {
253 setUp();
254 }
255 }
256 }
257 };
258 cr.registerContentObserver(Secure.getUriFor(Secure.USER_SETUP_COMPLETE),
Christine Franks39b03112018-07-03 14:46:07 -0700259 false /* notifyForDescendants */, mUserSetupObserver, mCurrentUser);
Justin Klaassen2696d992016-07-11 21:26:46 -0700260 } else if (mBootCompleted) {
261 setUp();
Justin Klaassen911e8892016-06-21 18:24:24 -0700262 }
263 }
264 }
265
Justin Klaassen2696d992016-07-11 21:26:46 -0700266 private static boolean isUserSetupCompleted(ContentResolver cr, int userHandle) {
267 return Secure.getIntForUser(cr, Secure.USER_SETUP_COMPLETE, 0, userHandle) == 1;
268 }
269
270 private void setUp() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700271 Slog.d(TAG, "setUp: currentUser=" + mCurrentUser);
272
Christine Franks57fdde82018-07-03 14:46:07 -0700273 // Listen for external changes to any of the settings.
274 if (mContentObserver == null) {
Christine Franks27912a32019-04-02 10:43:10 -0700275 mContentObserver = new ContentObserver(mHandler) {
Christine Franks57fdde82018-07-03 14:46:07 -0700276 @Override
277 public void onChange(boolean selfChange, Uri uri) {
278 super.onChange(selfChange, uri);
279
280 final String setting = uri == null ? null : uri.getLastPathSegment();
281 if (setting != null) {
282 switch (setting) {
283 case Secure.NIGHT_DISPLAY_ACTIVATED:
Christine Franks78a4dd42019-02-08 11:09:30 -0800284 final boolean activated = mNightDisplayTintController
285 .isActivatedSetting();
Christine Franks83cc5412018-07-03 14:46:07 -0700286 if (mNightDisplayTintController.isActivatedStateNotSet()
287 || mNightDisplayTintController.isActivated() != activated) {
Christine Franks78a4dd42019-02-08 11:09:30 -0800288 mNightDisplayTintController.setActivated(activated);
Christine Franks83cc5412018-07-03 14:46:07 -0700289 }
Christine Franks57fdde82018-07-03 14:46:07 -0700290 break;
291 case Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE:
Christine Franks78a4dd42019-02-08 11:09:30 -0800292 final int temperature = mNightDisplayTintController
293 .getColorTemperatureSetting();
Christine Franks83cc5412018-07-03 14:46:07 -0700294 if (mNightDisplayTintController.getColorTemperature()
295 != temperature) {
296 mNightDisplayTintController
297 .onColorTemperatureChanged(temperature);
298 }
Christine Franks57fdde82018-07-03 14:46:07 -0700299 break;
300 case Secure.NIGHT_DISPLAY_AUTO_MODE:
Christine Franks83cc5412018-07-03 14:46:07 -0700301 onNightDisplayAutoModeChanged(getNightDisplayAutoModeInternal());
Christine Franks57fdde82018-07-03 14:46:07 -0700302 break;
303 case Secure.NIGHT_DISPLAY_CUSTOM_START_TIME:
304 onNightDisplayCustomStartTimeChanged(
Christine Franks83cc5412018-07-03 14:46:07 -0700305 getNightDisplayCustomStartTimeInternal().getLocalTime());
Christine Franks57fdde82018-07-03 14:46:07 -0700306 break;
307 case Secure.NIGHT_DISPLAY_CUSTOM_END_TIME:
308 onNightDisplayCustomEndTimeChanged(
Christine Franks83cc5412018-07-03 14:46:07 -0700309 getNightDisplayCustomEndTimeInternal().getLocalTime());
Christine Franks57fdde82018-07-03 14:46:07 -0700310 break;
311 case System.DISPLAY_COLOR_MODE:
Christine Franks71e003e2019-01-24 14:40:20 -0800312 onDisplayColorModeChanged(getColorModeInternal());
Christine Franks57fdde82018-07-03 14:46:07 -0700313 break;
Christine Franks57fdde82018-07-03 14:46:07 -0700314 case Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED:
Christine Franks9114f462019-01-04 11:27:30 -0800315 onAccessibilityInversionChanged();
316 onAccessibilityActivated();
317 break;
318 case Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED:
319 onAccessibilityDaltonizerChanged();
320 onAccessibilityActivated();
321 break;
322 case Secure.ACCESSIBILITY_DISPLAY_DALTONIZER:
323 onAccessibilityDaltonizerChanged();
Christine Franks57fdde82018-07-03 14:46:07 -0700324 break;
Christine Franks245ffd42018-11-16 13:45:14 -0800325 case Secure.DISPLAY_WHITE_BALANCE_ENABLED:
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800326 updateDisplayWhiteBalanceStatus();
Christine Franks245ffd42018-11-16 13:45:14 -0800327 break;
Christine Franks57fdde82018-07-03 14:46:07 -0700328 }
329 }
330 }
331 };
332 }
333 final ContentResolver cr = getContext().getContentResolver();
334 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_ACTIVATED),
335 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
336 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE),
337 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
338 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_AUTO_MODE),
339 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
340 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_CUSTOM_START_TIME),
341 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
342 cr.registerContentObserver(Secure.getUriFor(Secure.NIGHT_DISPLAY_CUSTOM_END_TIME),
343 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
344 cr.registerContentObserver(System.getUriFor(System.DISPLAY_COLOR_MODE),
345 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
346 cr.registerContentObserver(
347 Secure.getUriFor(Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED),
348 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
349 cr.registerContentObserver(
350 Secure.getUriFor(Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED),
351 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
Christine Franks9114f462019-01-04 11:27:30 -0800352 cr.registerContentObserver(
353 Secure.getUriFor(Secure.ACCESSIBILITY_DISPLAY_DALTONIZER),
354 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
Christine Franks245ffd42018-11-16 13:45:14 -0800355 cr.registerContentObserver(Secure.getUriFor(Secure.DISPLAY_WHITE_BALANCE_ENABLED),
356 false /* notifyForDescendants */, mContentObserver, mCurrentUser);
Justin Klaassen911e8892016-06-21 18:24:24 -0700357
Christine Franks11e63152019-03-14 11:16:06 -0700358 // Apply the accessibility settings first, since they override most other settings.
359 onAccessibilityInversionChanged();
360 onAccessibilityDaltonizerChanged();
361
Christine Frankscf388c22018-05-15 15:48:10 -0700362 // Set the color mode, if valid, and immediately apply the updated tint matrix based on the
363 // existing activated state. This ensures consistency of tint across the color mode change.
Christine Franks71e003e2019-01-24 14:40:20 -0800364 onDisplayColorModeChanged(getColorModeInternal());
Christine Frankscf388c22018-05-15 15:48:10 -0700365
Christine Franksa4ed3762019-01-24 15:37:04 -0800366 if (mNightDisplayTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800367 // Reset the activated state.
368 mNightDisplayTintController.setActivated(null);
Christine Frankscf388c22018-05-15 15:48:10 -0700369
Christine Franks245ffd42018-11-16 13:45:14 -0800370 // Prepare the night display color transformation matrix.
371 mNightDisplayTintController
372 .setUp(getContext(), DisplayTransformManager.needsLinearColorMatrix());
Christine Franks78a4dd42019-02-08 11:09:30 -0800373 mNightDisplayTintController
374 .setMatrix(mNightDisplayTintController.getColorTemperatureSetting());
Christine Franks8ad71492017-10-24 19:04:22 -0700375
Christine Franks245ffd42018-11-16 13:45:14 -0800376 // Initialize the current auto mode.
Christine Franks83cc5412018-07-03 14:46:07 -0700377 onNightDisplayAutoModeChanged(getNightDisplayAutoModeInternal());
Christine Franks6418d0b2017-02-13 09:48:00 -0800378
Christine Franks83cc5412018-07-03 14:46:07 -0700379 // Force the initialization of the current saved activation state.
Christine Franks245ffd42018-11-16 13:45:14 -0800380 if (mNightDisplayTintController.isActivatedStateNotSet()) {
Christine Franks78a4dd42019-02-08 11:09:30 -0800381 mNightDisplayTintController
382 .setActivated(mNightDisplayTintController.isActivatedSetting());
Christine Franks245ffd42018-11-16 13:45:14 -0800383 }
384 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700385
Christine Franksa4ed3762019-01-24 15:37:04 -0800386 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800387 // Prepare the display white balance transform matrix.
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800388 mDisplayWhiteBalanceTintController.setUp(getContext(), true /* needsLinear */);
Christine Franks245ffd42018-11-16 13:45:14 -0800389
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800390 updateDisplayWhiteBalanceStatus();
Justin Klaassen911e8892016-06-21 18:24:24 -0700391 }
392 }
393
Justin Klaassen2696d992016-07-11 21:26:46 -0700394 private void tearDown() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700395 Slog.d(TAG, "tearDown: currentUser=" + mCurrentUser);
396
Christine Franks57fdde82018-07-03 14:46:07 -0700397 getContext().getContentResolver().unregisterContentObserver(mContentObserver);
398
Christine Franksa4ed3762019-01-24 15:37:04 -0800399 if (mNightDisplayTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800400 if (mNightDisplayAutoMode != null) {
401 mNightDisplayAutoMode.onStop();
402 mNightDisplayAutoMode = null;
403 }
404 mNightDisplayTintController.endAnimator();
Justin Klaassen911e8892016-06-21 18:24:24 -0700405 }
406
Christine Franksa4ed3762019-01-24 15:37:04 -0800407 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
Christine Franks245ffd42018-11-16 13:45:14 -0800408 mDisplayWhiteBalanceTintController.endAnimator();
Justin Klaassen639214e2016-07-14 21:00:06 -0700409 }
Christine Franks6d21d342019-02-07 15:09:03 -0800410
411 if (mGlobalSaturationTintController.isAvailable(getContext())) {
412 mGlobalSaturationTintController.setActivated(null);
413 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700414 }
415
Christine Franks57fdde82018-07-03 14:46:07 -0700416 private void onNightDisplayAutoModeChanged(int autoMode) {
417 Slog.d(TAG, "onNightDisplayAutoModeChanged: autoMode=" + autoMode);
Justin Klaassenec8837a2016-08-23 12:04:42 -0700418
Christine Franks57fdde82018-07-03 14:46:07 -0700419 if (mNightDisplayAutoMode != null) {
420 mNightDisplayAutoMode.onStop();
421 mNightDisplayAutoMode = null;
Justin Klaassen911e8892016-06-21 18:24:24 -0700422 }
423
Christine Franks83cc5412018-07-03 14:46:07 -0700424 if (autoMode == AUTO_MODE_CUSTOM_TIME) {
Christine Franks57fdde82018-07-03 14:46:07 -0700425 mNightDisplayAutoMode = new CustomNightDisplayAutoMode();
Christine Franks83cc5412018-07-03 14:46:07 -0700426 } else if (autoMode == AUTO_MODE_TWILIGHT) {
Christine Franks57fdde82018-07-03 14:46:07 -0700427 mNightDisplayAutoMode = new TwilightNightDisplayAutoMode();
Justin Klaassen911e8892016-06-21 18:24:24 -0700428 }
429
Christine Franks57fdde82018-07-03 14:46:07 -0700430 if (mNightDisplayAutoMode != null) {
431 mNightDisplayAutoMode.onStart();
Justin Klaassen911e8892016-06-21 18:24:24 -0700432 }
433 }
434
Christine Franks57fdde82018-07-03 14:46:07 -0700435 private void onNightDisplayCustomStartTimeChanged(LocalTime startTime) {
436 Slog.d(TAG, "onNightDisplayCustomStartTimeChanged: startTime=" + startTime);
Justin Klaassenec8837a2016-08-23 12:04:42 -0700437
Christine Franks57fdde82018-07-03 14:46:07 -0700438 if (mNightDisplayAutoMode != null) {
439 mNightDisplayAutoMode.onCustomStartTimeChanged(startTime);
Justin Klaassen911e8892016-06-21 18:24:24 -0700440 }
441 }
442
Christine Franks57fdde82018-07-03 14:46:07 -0700443 private void onNightDisplayCustomEndTimeChanged(LocalTime endTime) {
444 Slog.d(TAG, "onNightDisplayCustomEndTimeChanged: endTime=" + endTime);
Justin Klaassenec8837a2016-08-23 12:04:42 -0700445
Christine Franks57fdde82018-07-03 14:46:07 -0700446 if (mNightDisplayAutoMode != null) {
447 mNightDisplayAutoMode.onCustomEndTimeChanged(endTime);
Justin Klaassen911e8892016-06-21 18:24:24 -0700448 }
449 }
450
Christine Franks57fdde82018-07-03 14:46:07 -0700451 private void onDisplayColorModeChanged(int mode) {
Christine Franks83cc5412018-07-03 14:46:07 -0700452 if (mode == NOT_SET) {
Christine Frankscf388c22018-05-15 15:48:10 -0700453 return;
454 }
455
Christine Franks245ffd42018-11-16 13:45:14 -0800456 mNightDisplayTintController.cancelAnimator();
457 mDisplayWhiteBalanceTintController.cancelAnimator();
458
Christine Franksa4ed3762019-01-24 15:37:04 -0800459 if (mNightDisplayTintController.isAvailable(getContext())) {
460 mNightDisplayTintController
461 .setUp(getContext(), DisplayTransformManager.needsLinearColorMatrix(mode));
Christine Franks78a4dd42019-02-08 11:09:30 -0800462 mNightDisplayTintController
463 .setMatrix(mNightDisplayTintController.getColorTemperatureSetting());
Christine Franksa4ed3762019-01-24 15:37:04 -0800464 }
Christine Franks245ffd42018-11-16 13:45:14 -0800465
Christine Franks18ac4e22019-04-05 18:30:50 -0700466 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
467 updateDisplayWhiteBalanceStatus();
468 }
Christine Franks8ad71492017-10-24 19:04:22 -0700469
Christine Franks218e6562017-11-27 10:20:14 -0800470 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
Christine Franks245ffd42018-11-16 13:45:14 -0800471 dtm.setColorMode(mode, mNightDisplayTintController.getMatrix());
Christine Franks8ad71492017-10-24 19:04:22 -0700472 }
473
Christine Franks9114f462019-01-04 11:27:30 -0800474 private void onAccessibilityActivated() {
Christine Franks71e003e2019-01-24 14:40:20 -0800475 onDisplayColorModeChanged(getColorModeInternal());
Daniel Solomon317a3572018-03-30 18:36:37 -0700476 }
477
Daniel Solomonff24ba92019-04-11 19:29:31 -0700478 private boolean isAccessiblityDaltonizerEnabled() {
479 return Secure.getIntForUser(getContext().getContentResolver(),
480 Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0, mCurrentUser) != 0;
481 }
482
483 private boolean isAccessiblityInversionEnabled() {
484 return Secure.getIntForUser(getContext().getContentResolver(),
485 Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, 0, mCurrentUser) != 0;
486 }
487
488 private boolean isAccessibilityEnabled() {
489 return isAccessiblityDaltonizerEnabled() || isAccessiblityInversionEnabled();
490 }
491
Christine Franks9114f462019-01-04 11:27:30 -0800492 /**
493 * Apply the accessibility daltonizer transform based on the settings value.
494 */
495 private void onAccessibilityDaltonizerChanged() {
Christine Franks27912a32019-04-02 10:43:10 -0700496 if (mCurrentUser == UserHandle.USER_NULL) {
497 return;
498 }
Daniel Solomonff24ba92019-04-11 19:29:31 -0700499 final int daltonizerMode = isAccessiblityDaltonizerEnabled()
500 ? Secure.getIntForUser(getContext().getContentResolver(),
501 Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
502 AccessibilityManager.DALTONIZER_CORRECT_DEUTERANOMALY, mCurrentUser)
Christine Franks9114f462019-01-04 11:27:30 -0800503 : AccessibilityManager.DALTONIZER_DISABLED;
504
505 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
506 if (daltonizerMode == AccessibilityManager.DALTONIZER_SIMULATE_MONOCHROMACY) {
507 // Monochromacy isn't supported by the native Daltonizer implementation; use grayscale.
508 dtm.setColorMatrix(DisplayTransformManager.LEVEL_COLOR_MATRIX_GRAYSCALE,
509 MATRIX_GRAYSCALE);
510 dtm.setDaltonizerMode(AccessibilityManager.DALTONIZER_DISABLED);
511 } else {
512 dtm.setColorMatrix(DisplayTransformManager.LEVEL_COLOR_MATRIX_GRAYSCALE, null);
513 dtm.setDaltonizerMode(daltonizerMode);
514 }
515 }
516
517 /**
518 * Apply the accessibility inversion transform based on the settings value.
519 */
520 private void onAccessibilityInversionChanged() {
Christine Franks27912a32019-04-02 10:43:10 -0700521 if (mCurrentUser == UserHandle.USER_NULL) {
522 return;
523 }
Christine Franks9114f462019-01-04 11:27:30 -0800524 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
525 dtm.setColorMatrix(DisplayTransformManager.LEVEL_COLOR_MATRIX_INVERT_COLOR,
Daniel Solomonff24ba92019-04-11 19:29:31 -0700526 isAccessiblityInversionEnabled() ? MATRIX_INVERT_COLOR : null);
Christine Franks9114f462019-01-04 11:27:30 -0800527 }
Christine Franks8ad71492017-10-24 19:04:22 -0700528
Christine Franks6418d0b2017-02-13 09:48:00 -0800529 /**
530 * Applies current color temperature matrix, or removes it if deactivated.
531 *
532 * @param immediate {@code true} skips transition animation
533 */
Christine Franks245ffd42018-11-16 13:45:14 -0800534 private void applyTint(TintController tintController, boolean immediate) {
535 tintController.cancelAnimator();
Christine Franks6418d0b2017-02-13 09:48:00 -0800536
Christine Franks6418d0b2017-02-13 09:48:00 -0800537 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
Christine Franks245ffd42018-11-16 13:45:14 -0800538 final float[] from = dtm.getColorMatrix(tintController.getLevel());
539 final float[] to = tintController.getMatrix();
Christine Franks6418d0b2017-02-13 09:48:00 -0800540
541 if (immediate) {
Christine Franks245ffd42018-11-16 13:45:14 -0800542 dtm.setColorMatrix(tintController.getLevel(), to);
Christine Franks6418d0b2017-02-13 09:48:00 -0800543 } else {
Christine Franks245ffd42018-11-16 13:45:14 -0800544 tintController.setAnimator(ValueAnimator.ofObject(COLOR_MATRIX_EVALUATOR,
545 from == null ? MATRIX_IDENTITY : from, to));
546 tintController.getAnimator().setDuration(TRANSITION_DURATION);
547 tintController.getAnimator().setInterpolator(AnimationUtils.loadInterpolator(
Christine Franks6418d0b2017-02-13 09:48:00 -0800548 getContext(), android.R.interpolator.fast_out_slow_in));
Christine Franks245ffd42018-11-16 13:45:14 -0800549 tintController.getAnimator().addUpdateListener((ValueAnimator animator) -> {
550 final float[] value = (float[]) animator.getAnimatedValue();
551 dtm.setColorMatrix(tintController.getLevel(), value);
Christine Franks6418d0b2017-02-13 09:48:00 -0800552 });
Christine Franks245ffd42018-11-16 13:45:14 -0800553 tintController.getAnimator().addListener(new AnimatorListenerAdapter() {
Christine Franks6418d0b2017-02-13 09:48:00 -0800554
555 private boolean mIsCancelled;
556
557 @Override
558 public void onAnimationCancel(Animator animator) {
559 mIsCancelled = true;
560 }
561
562 @Override
563 public void onAnimationEnd(Animator animator) {
564 if (!mIsCancelled) {
565 // Ensure final color matrix is set at the end of the animation. If the
566 // animation is cancelled then don't set the final color matrix so the new
567 // animator can pick up from where this one left off.
Christine Franks245ffd42018-11-16 13:45:14 -0800568 dtm.setColorMatrix(tintController.getLevel(), to);
Christine Franks6418d0b2017-02-13 09:48:00 -0800569 }
Christine Franks245ffd42018-11-16 13:45:14 -0800570 tintController.setAnimator(null);
Christine Franks6418d0b2017-02-13 09:48:00 -0800571 }
572 });
Christine Franks245ffd42018-11-16 13:45:14 -0800573 tintController.getAnimator().start();
Christine Franks6418d0b2017-02-13 09:48:00 -0800574 }
575 }
576
577 /**
Christine Franks39b03112018-07-03 14:46:07 -0700578 * Returns the first date time corresponding to the local time that occurs before the provided
579 * date time.
Christine Franks03213462017-08-25 13:57:26 -0700580 *
581 * @param compareTime the LocalDateTime to compare against
582 * @return the prior LocalDateTime corresponding to this local time
583 */
Christine Franks57fdde82018-07-03 14:46:07 -0700584 @VisibleForTesting
585 static LocalDateTime getDateTimeBefore(LocalTime localTime, LocalDateTime compareTime) {
Christine Franks03213462017-08-25 13:57:26 -0700586 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
587 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
588
589 // Check if the local time has passed, if so return the same time yesterday.
590 return ldt.isAfter(compareTime) ? ldt.minusDays(1) : ldt;
591 }
592
593 /**
Christine Franks39b03112018-07-03 14:46:07 -0700594 * Returns the first date time corresponding to this local time that occurs after the provided
595 * date time.
Christine Franks03213462017-08-25 13:57:26 -0700596 *
597 * @param compareTime the LocalDateTime to compare against
598 * @return the next LocalDateTime corresponding to this local time
599 */
Christine Franks57fdde82018-07-03 14:46:07 -0700600 @VisibleForTesting
601 static LocalDateTime getDateTimeAfter(LocalTime localTime, LocalDateTime compareTime) {
Christine Franks03213462017-08-25 13:57:26 -0700602 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
603 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
604
605 // Check if the local time has passed, if so return the same time tomorrow.
606 return ldt.isBefore(compareTime) ? ldt.plusDays(1) : ldt;
607 }
608
Long Ling1d3f1892019-02-06 12:34:02 -0800609 @VisibleForTesting
610 void updateDisplayWhiteBalanceStatus() {
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800611 boolean oldActivated = mDisplayWhiteBalanceTintController.isActivated();
Christine Franks0ada2772019-02-25 13:54:57 -0800612 mDisplayWhiteBalanceTintController.setActivated(isDisplayWhiteBalanceSettingEnabled()
613 && !mNightDisplayTintController.isActivated()
Daniel Solomonff24ba92019-04-11 19:29:31 -0700614 && !isAccessibilityEnabled()
Christine Franks0ada2772019-02-25 13:54:57 -0800615 && DisplayTransformManager.needsLinearColorMatrix());
Daniel Solomon8b72c5b2018-11-25 11:07:13 -0800616 boolean activated = mDisplayWhiteBalanceTintController.isActivated();
617
618 if (mDisplayWhiteBalanceListener != null && oldActivated != activated) {
619 mDisplayWhiteBalanceListener.onDisplayWhiteBalanceStatusChanged(activated);
Christine Franks245ffd42018-11-16 13:45:14 -0800620 }
Daniel Solomon86508f82019-01-18 19:01:02 -0800621
622 // If disabled, clear the tint. If enabled, do nothing more here and let the next
623 // temperature update set the correct tint.
624 if (!activated) {
Christine Franksc7fb9452019-02-04 08:45:33 -0800625 mHandler.sendEmptyMessage(MSG_APPLY_DISPLAY_WHITE_BALANCE);
Daniel Solomon86508f82019-01-18 19:01:02 -0800626 }
Christine Franks245ffd42018-11-16 13:45:14 -0800627 }
628
Christine Franks66783a82019-03-28 11:45:56 -0700629 private boolean setDisplayWhiteBalanceSettingEnabled(boolean enabled) {
630 if (mCurrentUser == UserHandle.USER_NULL) {
631 return false;
632 }
633 return Secure.putIntForUser(getContext().getContentResolver(),
634 Secure.DISPLAY_WHITE_BALANCE_ENABLED,
635 enabled ? 1 : 0, mCurrentUser);
636 }
637
Christine Franks245ffd42018-11-16 13:45:14 -0800638 private boolean isDisplayWhiteBalanceSettingEnabled() {
Christine Franks27912a32019-04-02 10:43:10 -0700639 if (mCurrentUser == UserHandle.USER_NULL) {
640 return false;
641 }
Christine Franks245ffd42018-11-16 13:45:14 -0800642 return Secure.getIntForUser(getContext().getContentResolver(),
Christine Franks18ac4e22019-04-05 18:30:50 -0700643 Secure.DISPLAY_WHITE_BALANCE_ENABLED,
644 getContext().getResources()
645 .getBoolean(R.bool.config_displayWhiteBalanceEnabledDefault) ? 1
646 : 0,
647 mCurrentUser) == 1;
Christine Franks245ffd42018-11-16 13:45:14 -0800648 }
649
Christine Franks39b03112018-07-03 14:46:07 -0700650 private boolean isDeviceColorManagedInternal() {
651 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
652 return dtm.isDeviceColorManaged();
653 }
654
Christine Franks55194dc2019-01-15 13:47:06 -0800655 private int getTransformCapabilitiesInternal() {
656 int availabilityFlags = ColorDisplayManager.CAPABILITY_NONE;
657 if (SurfaceControl.getProtectedContentSupport()) {
658 availabilityFlags |= ColorDisplayManager.CAPABILITY_PROTECTED_CONTENT;
659 }
660 final Resources res = getContext().getResources();
661 if (res.getBoolean(R.bool.config_setColorTransformAccelerated)) {
662 availabilityFlags |= ColorDisplayManager.CAPABILITY_HARDWARE_ACCELERATION_GLOBAL;
663 }
664 if (res.getBoolean(R.bool.config_setColorTransformAcceleratedPerLayer)) {
665 availabilityFlags |= ColorDisplayManager.CAPABILITY_HARDWARE_ACCELERATION_PER_APP;
666 }
667 return availabilityFlags;
668 }
669
Christine Franks83cc5412018-07-03 14:46:07 -0700670 private boolean setNightDisplayAutoModeInternal(@AutoMode int autoMode) {
671 if (getNightDisplayAutoModeInternal() != autoMode) {
672 Secure.putStringForUser(getContext().getContentResolver(),
673 Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
674 null,
675 mCurrentUser);
676 }
677 return Secure.putIntForUser(getContext().getContentResolver(),
678 Secure.NIGHT_DISPLAY_AUTO_MODE, autoMode, mCurrentUser);
679 }
680
681 private int getNightDisplayAutoModeInternal() {
682 int autoMode = getNightDisplayAutoModeRawInternal();
683 if (autoMode == NOT_SET) {
684 autoMode = getContext().getResources().getInteger(
685 R.integer.config_defaultNightDisplayAutoMode);
686 }
687 if (autoMode != AUTO_MODE_DISABLED
688 && autoMode != AUTO_MODE_CUSTOM_TIME
689 && autoMode != AUTO_MODE_TWILIGHT) {
690 Slog.e(TAG, "Invalid autoMode: " + autoMode);
691 autoMode = AUTO_MODE_DISABLED;
692 }
693 return autoMode;
694 }
695
696 private int getNightDisplayAutoModeRawInternal() {
Christine Franks27912a32019-04-02 10:43:10 -0700697 if (mCurrentUser == UserHandle.USER_NULL) {
698 return NOT_SET;
699 }
Christine Franks83cc5412018-07-03 14:46:07 -0700700 return Secure
701 .getIntForUser(getContext().getContentResolver(), Secure.NIGHT_DISPLAY_AUTO_MODE,
702 NOT_SET, mCurrentUser);
703 }
704
705 private Time getNightDisplayCustomStartTimeInternal() {
706 int startTimeValue = Secure.getIntForUser(getContext().getContentResolver(),
707 Secure.NIGHT_DISPLAY_CUSTOM_START_TIME, NOT_SET, mCurrentUser);
708 if (startTimeValue == NOT_SET) {
709 startTimeValue = getContext().getResources().getInteger(
710 R.integer.config_defaultNightDisplayCustomStartTime);
711 }
712 return new Time(LocalTime.ofSecondOfDay(startTimeValue / 1000));
713 }
714
715 private boolean setNightDisplayCustomStartTimeInternal(Time startTime) {
716 return Secure.putIntForUser(getContext().getContentResolver(),
717 Secure.NIGHT_DISPLAY_CUSTOM_START_TIME,
718 startTime.getLocalTime().toSecondOfDay() * 1000,
719 mCurrentUser);
720 }
721
722 private Time getNightDisplayCustomEndTimeInternal() {
723 int endTimeValue = Secure.getIntForUser(getContext().getContentResolver(),
724 Secure.NIGHT_DISPLAY_CUSTOM_END_TIME, NOT_SET, mCurrentUser);
725 if (endTimeValue == NOT_SET) {
726 endTimeValue = getContext().getResources().getInteger(
727 R.integer.config_defaultNightDisplayCustomEndTime);
728 }
729 return new Time(LocalTime.ofSecondOfDay(endTimeValue / 1000));
730 }
731
732 private boolean setNightDisplayCustomEndTimeInternal(Time endTime) {
733 return Secure.putIntForUser(getContext().getContentResolver(),
734 Secure.NIGHT_DISPLAY_CUSTOM_END_TIME, endTime.getLocalTime().toSecondOfDay() * 1000,
735 mCurrentUser);
736 }
737
Christine Franks57fdde82018-07-03 14:46:07 -0700738 /**
739 * Returns the last time the night display transform activation state was changed, or {@link
740 * LocalDateTime#MIN} if night display has never been activated.
741 */
Christine Franks245ffd42018-11-16 13:45:14 -0800742 private LocalDateTime getNightDisplayLastActivatedTimeSetting() {
Christine Franks57fdde82018-07-03 14:46:07 -0700743 final ContentResolver cr = getContext().getContentResolver();
744 final String lastActivatedTime = Secure.getStringForUser(
745 cr, Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME, getContext().getUserId());
746 if (lastActivatedTime != null) {
747 try {
748 return LocalDateTime.parse(lastActivatedTime);
749 } catch (DateTimeParseException ignored) {
750 }
751 // Uses the old epoch time.
752 try {
753 return LocalDateTime.ofInstant(
754 Instant.ofEpochMilli(Long.parseLong(lastActivatedTime)),
755 ZoneId.systemDefault());
756 } catch (DateTimeException | NumberFormatException ignored) {
757 }
758 }
759 return LocalDateTime.MIN;
760 }
761
Christine Franksf3529b22019-01-03 13:20:17 -0800762 private boolean setAppSaturationLevelInternal(String packageName, int saturationLevel) {
763 return mAppSaturationController
764 .setSaturationLevel(packageName, mCurrentUser, saturationLevel);
765 }
766
Christine Franksd154fe52019-01-04 17:17:45 -0800767 private void setColorModeInternal(@ColorMode int colorMode) {
768 if (!isColorModeAvailable(colorMode)) {
769 throw new IllegalArgumentException("Invalid colorMode: " + colorMode);
770 }
771 System.putIntForUser(getContext().getContentResolver(), System.DISPLAY_COLOR_MODE,
772 colorMode,
773 mCurrentUser);
774 }
775
Christine Franks71e003e2019-01-24 14:40:20 -0800776 private @ColorMode int getColorModeInternal() {
Christine Franksd154fe52019-01-04 17:17:45 -0800777 final ContentResolver cr = getContext().getContentResolver();
Daniel Solomonff24ba92019-04-11 19:29:31 -0700778 if (isAccessibilityEnabled()) {
Christine Franksd154fe52019-01-04 17:17:45 -0800779 // There are restrictions on the available color modes combined with a11y transforms.
Christine Franksb8d03a52019-05-08 15:08:21 -0700780 final int a11yColorMode = getContext().getResources().getInteger(
781 R.integer.config_accessibilityColorMode);
782 if (a11yColorMode >= 0) {
783 return a11yColorMode;
Christine Franksd154fe52019-01-04 17:17:45 -0800784 }
785 }
786
787 int colorMode = System.getIntForUser(cr, System.DISPLAY_COLOR_MODE, -1, mCurrentUser);
788 if (colorMode == -1) {
789 // There might be a system property controlling color mode that we need to respect; if
790 // not, this will set a suitable default.
791 colorMode = getCurrentColorModeFromSystemProperties();
792 }
793
794 // This happens when a color mode is no longer available (e.g., after system update or B&R)
795 // or the device does not support any color mode.
796 if (!isColorModeAvailable(colorMode)) {
797 if (colorMode == COLOR_MODE_BOOSTED && isColorModeAvailable(COLOR_MODE_NATURAL)) {
798 colorMode = COLOR_MODE_NATURAL;
799 } else if (colorMode == COLOR_MODE_SATURATED
800 && isColorModeAvailable(COLOR_MODE_AUTOMATIC)) {
801 colorMode = COLOR_MODE_AUTOMATIC;
802 } else if (colorMode == COLOR_MODE_AUTOMATIC
803 && isColorModeAvailable(COLOR_MODE_SATURATED)) {
804 colorMode = COLOR_MODE_SATURATED;
805 } else {
806 colorMode = -1;
807 }
808 }
809
810 return colorMode;
811 }
812
813 /**
814 * Get the current color mode from system properties, or return -1 if invalid.
815 *
Christine Franks0ada2772019-02-25 13:54:57 -0800816 * See {@link DisplayTransformManager}
Christine Franksd154fe52019-01-04 17:17:45 -0800817 */
Christine Franks78a4dd42019-02-08 11:09:30 -0800818 private @ColorMode int getCurrentColorModeFromSystemProperties() {
Christine Franksd154fe52019-01-04 17:17:45 -0800819 final int displayColorSetting = SystemProperties.getInt("persist.sys.sf.native_mode", 0);
820 if (displayColorSetting == 0) {
821 return "1.0".equals(SystemProperties.get("persist.sys.sf.color_saturation"))
822 ? COLOR_MODE_NATURAL : COLOR_MODE_BOOSTED;
823 } else if (displayColorSetting == 1) {
824 return COLOR_MODE_SATURATED;
825 } else if (displayColorSetting == 2) {
826 return COLOR_MODE_AUTOMATIC;
Christine Franks531c0612019-05-16 14:29:14 -0700827 } else if (displayColorSetting >= VENDOR_COLOR_MODE_RANGE_MIN
828 && displayColorSetting <= VENDOR_COLOR_MODE_RANGE_MAX) {
829 return displayColorSetting;
Christine Franksd154fe52019-01-04 17:17:45 -0800830 } else {
831 return -1;
832 }
833 }
834
835 private boolean isColorModeAvailable(@ColorMode int colorMode) {
836 final int[] availableColorModes = getContext().getResources().getIntArray(
837 R.array.config_availableColorModes);
838 if (availableColorModes != null) {
839 for (int mode : availableColorModes) {
840 if (mode == colorMode) {
841 return true;
842 }
843 }
844 }
845 return false;
846 }
847
Christine Franksf3529b22019-01-03 13:20:17 -0800848 private void dumpInternal(PrintWriter pw) {
849 pw.println("COLOR DISPLAY MANAGER dumpsys (color_display)");
Christine Franksa4ed3762019-01-24 15:37:04 -0800850
Christine Franks0ada2772019-02-25 13:54:57 -0800851 pw.println("Night display:");
Christine Franksa4ed3762019-01-24 15:37:04 -0800852 if (mNightDisplayTintController.isAvailable(getContext())) {
Christine Franksf3529b22019-01-03 13:20:17 -0800853 pw.println(" Activated: " + mNightDisplayTintController.isActivated());
Christine Franksa4ed3762019-01-24 15:37:04 -0800854 pw.println(" Color temp: " + mNightDisplayTintController.getColorTemperature());
Christine Franksf3529b22019-01-03 13:20:17 -0800855 } else {
856 pw.println(" Not available");
857 }
Christine Franksa4ed3762019-01-24 15:37:04 -0800858
859 pw.println("Global saturation:");
860 if (mGlobalSaturationTintController.isAvailable(getContext())) {
861 pw.println(" Activated: " + mGlobalSaturationTintController.isActivated());
862 } else {
863 pw.println(" Not available");
864 }
865
Christine Franksf3529b22019-01-03 13:20:17 -0800866 mAppSaturationController.dump(pw);
Christine Franksa4ed3762019-01-24 15:37:04 -0800867
868 pw.println("Display white balance:");
869 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
870 pw.println(" Activated: " + mDisplayWhiteBalanceTintController.isActivated());
Long Ling1d3f1892019-02-06 12:34:02 -0800871 mDisplayWhiteBalanceTintController.dump(pw);
Christine Franksa4ed3762019-01-24 15:37:04 -0800872 } else {
873 pw.println(" Not available");
874 }
875
876 pw.println("Color mode: " + getColorModeInternal());
Christine Franksf3529b22019-01-03 13:20:17 -0800877 }
878
Christine Franks57fdde82018-07-03 14:46:07 -0700879 private abstract class NightDisplayAutoMode {
880
881 public abstract void onActivated(boolean activated);
882
Justin Klaassen911e8892016-06-21 18:24:24 -0700883 public abstract void onStart();
Christine Frankse5bb03e2017-02-10 17:36:10 -0800884
Justin Klaassen911e8892016-06-21 18:24:24 -0700885 public abstract void onStop();
Christine Franks57fdde82018-07-03 14:46:07 -0700886
887 public void onCustomStartTimeChanged(LocalTime startTime) {
888 }
889
890 public void onCustomEndTimeChanged(LocalTime endTime) {
891 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700892 }
893
Christine Franks57fdde82018-07-03 14:46:07 -0700894 private final class CustomNightDisplayAutoMode extends NightDisplayAutoMode implements
895 AlarmManager.OnAlarmListener {
Justin Klaassen911e8892016-06-21 18:24:24 -0700896
897 private final AlarmManager mAlarmManager;
898 private final BroadcastReceiver mTimeChangedReceiver;
899
Christine Franks03213462017-08-25 13:57:26 -0700900 private LocalTime mStartTime;
901 private LocalTime mEndTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700902
Christine Franks03213462017-08-25 13:57:26 -0700903 private LocalDateTime mLastActivatedTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700904
Christine Franks57fdde82018-07-03 14:46:07 -0700905 CustomNightDisplayAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -0700906 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
907 mTimeChangedReceiver = new BroadcastReceiver() {
908 @Override
909 public void onReceive(Context context, Intent intent) {
910 updateActivated();
911 }
912 };
913 }
914
915 private void updateActivated() {
Christine Franks03213462017-08-25 13:57:26 -0700916 final LocalDateTime now = LocalDateTime.now();
917 final LocalDateTime start = getDateTimeBefore(mStartTime, now);
918 final LocalDateTime end = getDateTimeAfter(mEndTime, start);
919 boolean activate = now.isBefore(end);
Justin Klaassen911e8892016-06-21 18:24:24 -0700920
Christine Frankse5bb03e2017-02-10 17:36:10 -0800921 if (mLastActivatedTime != null) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800922 // Maintain the existing activated state if within the current period.
Christine Franks0ada2772019-02-25 13:54:57 -0800923 if (mLastActivatedTime.isBefore(now)
924 && mLastActivatedTime.isAfter(start)
Christine Franks03213462017-08-25 13:57:26 -0700925 && (mLastActivatedTime.isAfter(end) || now.isBefore(end))) {
Christine Franks78a4dd42019-02-08 11:09:30 -0800926 activate = mNightDisplayTintController.isActivatedSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -0700927 }
928 }
929
Christine Franks0ada2772019-02-25 13:54:57 -0800930 if (mNightDisplayTintController.isActivatedStateNotSet()
931 || (mNightDisplayTintController.isActivated() != activate)) {
Christine Franks83cc5412018-07-03 14:46:07 -0700932 mNightDisplayTintController.setActivated(activate);
Justin Klaassen911e8892016-06-21 18:24:24 -0700933 }
Christine Franks03213462017-08-25 13:57:26 -0700934
Christine Franks245ffd42018-11-16 13:45:14 -0800935 updateNextAlarm(mNightDisplayTintController.isActivated(), now);
Justin Klaassen911e8892016-06-21 18:24:24 -0700936 }
937
Christine Franks03213462017-08-25 13:57:26 -0700938 private void updateNextAlarm(@Nullable Boolean activated, @NonNull LocalDateTime now) {
Justin Klaassen4346f632016-08-08 15:01:47 -0700939 if (activated != null) {
Christine Franks03213462017-08-25 13:57:26 -0700940 final LocalDateTime next = activated ? getDateTimeAfter(mEndTime, now)
941 : getDateTimeAfter(mStartTime, now);
942 final long millis = next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
943 mAlarmManager.setExact(AlarmManager.RTC, millis, TAG, this, null);
Justin Klaassen911e8892016-06-21 18:24:24 -0700944 }
945 }
946
947 @Override
948 public void onStart() {
949 final IntentFilter intentFilter = new IntentFilter(Intent.ACTION_TIME_CHANGED);
950 intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
951 getContext().registerReceiver(mTimeChangedReceiver, intentFilter);
952
Christine Franks83cc5412018-07-03 14:46:07 -0700953 mStartTime = getNightDisplayCustomStartTimeInternal().getLocalTime();
954 mEndTime = getNightDisplayCustomEndTimeInternal().getLocalTime();
Justin Klaassen911e8892016-06-21 18:24:24 -0700955
Christine Franks57fdde82018-07-03 14:46:07 -0700956 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Christine Frankse5bb03e2017-02-10 17:36:10 -0800957
Justin Klaassen911e8892016-06-21 18:24:24 -0700958 // Force an update to initialize state.
959 updateActivated();
960 }
961
962 @Override
963 public void onStop() {
964 getContext().unregisterReceiver(mTimeChangedReceiver);
965
966 mAlarmManager.cancel(this);
967 mLastActivatedTime = null;
968 }
969
970 @Override
971 public void onActivated(boolean activated) {
Christine Franks57fdde82018-07-03 14:46:07 -0700972 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Christine Franks03213462017-08-25 13:57:26 -0700973 updateNextAlarm(activated, LocalDateTime.now());
Justin Klaassen911e8892016-06-21 18:24:24 -0700974 }
975
976 @Override
Christine Franks03213462017-08-25 13:57:26 -0700977 public void onCustomStartTimeChanged(LocalTime startTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700978 mStartTime = startTime;
979 mLastActivatedTime = null;
980 updateActivated();
981 }
982
983 @Override
Christine Franks03213462017-08-25 13:57:26 -0700984 public void onCustomEndTimeChanged(LocalTime endTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700985 mEndTime = endTime;
986 mLastActivatedTime = null;
987 updateActivated();
988 }
989
990 @Override
991 public void onAlarm() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700992 Slog.d(TAG, "onAlarm");
Justin Klaassen911e8892016-06-21 18:24:24 -0700993 updateActivated();
994 }
995 }
996
Christine Franks57fdde82018-07-03 14:46:07 -0700997 private final class TwilightNightDisplayAutoMode extends NightDisplayAutoMode implements
998 TwilightListener {
Justin Klaassen911e8892016-06-21 18:24:24 -0700999
1000 private final TwilightManager mTwilightManager;
Christine Franks57fdde82018-07-03 14:46:07 -07001001 private LocalDateTime mLastActivatedTime;
Justin Klaassen911e8892016-06-21 18:24:24 -07001002
Christine Franks57fdde82018-07-03 14:46:07 -07001003 TwilightNightDisplayAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -07001004 mTwilightManager = getLocalService(TwilightManager.class);
Justin Klaassen911e8892016-06-21 18:24:24 -07001005 }
1006
Justin Klaassen908b86c2016-08-08 09:18:42 -07001007 private void updateActivated(TwilightState state) {
Justin Klaassen3da4c442017-05-05 15:19:33 -07001008 if (state == null) {
1009 // If there isn't a valid TwilightState then just keep the current activated
1010 // state.
1011 return;
1012 }
1013
1014 boolean activate = state.isNight();
Christine Franks57fdde82018-07-03 14:46:07 -07001015 if (mLastActivatedTime != null) {
Christine Franks03213462017-08-25 13:57:26 -07001016 final LocalDateTime now = LocalDateTime.now();
1017 final LocalDateTime sunrise = state.sunrise();
1018 final LocalDateTime sunset = state.sunset();
Christine Frankse5bb03e2017-02-10 17:36:10 -08001019 // Maintain the existing activated state if within the current period.
Christine Franks57fdde82018-07-03 14:46:07 -07001020 if (mLastActivatedTime.isBefore(now) && (mLastActivatedTime.isBefore(sunrise)
1021 ^ mLastActivatedTime.isBefore(sunset))) {
Christine Franks78a4dd42019-02-08 11:09:30 -08001022 activate = mNightDisplayTintController.isActivatedSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -07001023 }
1024 }
Justin Klaassen908b86c2016-08-08 09:18:42 -07001025
Christine Franks245ffd42018-11-16 13:45:14 -08001026 if (mNightDisplayTintController.isActivatedStateNotSet() || (
1027 mNightDisplayTintController.isActivated() != activate)) {
Christine Franks83cc5412018-07-03 14:46:07 -07001028 mNightDisplayTintController.setActivated(activate);
Justin Klaassen908b86c2016-08-08 09:18:42 -07001029 }
Justin Klaassen911e8892016-06-21 18:24:24 -07001030 }
1031
1032 @Override
Christine Franks57fdde82018-07-03 14:46:07 -07001033 public void onActivated(boolean activated) {
1034 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
1035 }
1036
1037 @Override
Justin Klaassen911e8892016-06-21 18:24:24 -07001038 public void onStart() {
1039 mTwilightManager.registerListener(this, mHandler);
Christine Franks57fdde82018-07-03 14:46:07 -07001040 mLastActivatedTime = getNightDisplayLastActivatedTimeSetting();
Justin Klaassen911e8892016-06-21 18:24:24 -07001041
1042 // Force an update to initialize state.
Justin Klaassen908b86c2016-08-08 09:18:42 -07001043 updateActivated(mTwilightManager.getLastTwilightState());
Justin Klaassen911e8892016-06-21 18:24:24 -07001044 }
1045
1046 @Override
1047 public void onStop() {
1048 mTwilightManager.unregisterListener(this);
Christine Franks57fdde82018-07-03 14:46:07 -07001049 mLastActivatedTime = null;
Justin Klaassen908b86c2016-08-08 09:18:42 -07001050 }
1051
1052 @Override
1053 public void onTwilightStateChanged(@Nullable TwilightState state) {
Justin Klaassenec8837a2016-08-23 12:04:42 -07001054 Slog.d(TAG, "onTwilightStateChanged: isNight="
1055 + (state == null ? null : state.isNight()));
Justin Klaassen908b86c2016-08-08 09:18:42 -07001056 updateActivated(state);
Justin Klaassen911e8892016-06-21 18:24:24 -07001057 }
1058 }
Justin Klaassen639214e2016-07-14 21:00:06 -07001059
1060 /**
1061 * Interpolates between two 4x4 color transform matrices (in column-major order).
1062 */
1063 private static class ColorMatrixEvaluator implements TypeEvaluator<float[]> {
1064
1065 /**
1066 * Result matrix returned by {@link #evaluate(float, float[], float[])}.
1067 */
1068 private final float[] mResultMatrix = new float[16];
1069
1070 @Override
1071 public float[] evaluate(float fraction, float[] startValue, float[] endValue) {
1072 for (int i = 0; i < mResultMatrix.length; i++) {
1073 mResultMatrix[i] = MathUtils.lerp(startValue[i], endValue[i], fraction);
1074 }
1075 return mResultMatrix;
1076 }
1077 }
Christine Franks39b03112018-07-03 14:46:07 -07001078
Christine Franks83cc5412018-07-03 14:46:07 -07001079 private final class NightDisplayTintController extends TintController {
1080
Christine Franksa4ed3762019-01-24 15:37:04 -08001081 private final float[] mMatrix = new float[16];
Christine Franks83cc5412018-07-03 14:46:07 -07001082 private final float[] mColorTempCoefficients = new float[9];
Christine Franksa4ed3762019-01-24 15:37:04 -08001083
1084 private Boolean mIsAvailable;
Christine Franks83cc5412018-07-03 14:46:07 -07001085 private Integer mColorTemp;
1086
1087 /**
1088 * Set coefficients based on whether the color matrix is linear or not.
1089 */
1090 @Override
1091 public void setUp(Context context, boolean needsLinear) {
1092 final String[] coefficients = context.getResources().getStringArray(needsLinear
1093 ? R.array.config_nightDisplayColorTemperatureCoefficients
1094 : R.array.config_nightDisplayColorTemperatureCoefficientsNative);
1095 for (int i = 0; i < 9 && i < coefficients.length; i++) {
1096 mColorTempCoefficients[i] = Float.parseFloat(coefficients[i]);
1097 }
1098 }
1099
1100 @Override
1101 public void setMatrix(int cct) {
1102 if (mMatrix.length != 16) {
1103 Slog.d(TAG, "The display transformation matrix must be 4x4");
1104 return;
1105 }
1106
1107 Matrix.setIdentityM(mMatrix, 0);
1108
1109 final float squareTemperature = cct * cct;
1110 final float red = squareTemperature * mColorTempCoefficients[0]
1111 + cct * mColorTempCoefficients[1] + mColorTempCoefficients[2];
1112 final float green = squareTemperature * mColorTempCoefficients[3]
1113 + cct * mColorTempCoefficients[4] + mColorTempCoefficients[5];
1114 final float blue = squareTemperature * mColorTempCoefficients[6]
1115 + cct * mColorTempCoefficients[7] + mColorTempCoefficients[8];
1116 mMatrix[0] = red;
1117 mMatrix[5] = green;
1118 mMatrix[10] = blue;
1119 }
1120
1121 @Override
1122 public float[] getMatrix() {
1123 return isActivated() ? mMatrix : MATRIX_IDENTITY;
1124 }
1125
1126 @Override
1127 public void setActivated(Boolean activated) {
1128 if (activated == null) {
1129 super.setActivated(null);
1130 return;
1131 }
1132
1133 boolean activationStateChanged = activated != isActivated();
1134
1135 if (!isActivatedStateNotSet() && activationStateChanged) {
1136 // This is a true state change, so set this as the last activation time.
1137 Secure.putStringForUser(getContext().getContentResolver(),
1138 Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
1139 LocalDateTime.now().toString(),
1140 mCurrentUser);
1141 }
1142
1143 if (isActivatedStateNotSet() || activationStateChanged) {
1144 super.setActivated(activated);
Christine Franks78a4dd42019-02-08 11:09:30 -08001145 if (isActivatedSetting() != activated) {
1146 Secure.putIntForUser(getContext().getContentResolver(),
1147 Secure.NIGHT_DISPLAY_ACTIVATED,
1148 activated ? 1 : 0, mCurrentUser);
1149 }
Christine Franks83cc5412018-07-03 14:46:07 -07001150 onActivated(activated);
1151 }
1152 }
1153
1154 @Override
1155 public int getLevel() {
1156 return LEVEL_COLOR_MATRIX_NIGHT_DISPLAY;
1157 }
1158
Christine Franksa4ed3762019-01-24 15:37:04 -08001159 @Override
1160 public boolean isAvailable(Context context) {
1161 if (mIsAvailable == null) {
1162 mIsAvailable = ColorDisplayManager.isNightDisplayAvailable(context);
1163 }
1164 return mIsAvailable;
1165 }
1166
Christine Franks78a4dd42019-02-08 11:09:30 -08001167 private void onActivated(boolean activated) {
Christine Franks83cc5412018-07-03 14:46:07 -07001168 Slog.i(TAG, activated ? "Turning on night display" : "Turning off night display");
1169 if (mNightDisplayAutoMode != null) {
1170 mNightDisplayAutoMode.onActivated(activated);
1171 }
1172
Christine Franksa4ed3762019-01-24 15:37:04 -08001173 if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
Christine Franks83cc5412018-07-03 14:46:07 -07001174 updateDisplayWhiteBalanceStatus();
1175 }
1176
1177 mHandler.sendEmptyMessage(MSG_APPLY_NIGHT_DISPLAY_ANIMATED);
1178 }
1179
1180 int getColorTemperature() {
1181 return mColorTemp != null ? clampNightDisplayColorTemperature(mColorTemp)
Christine Franks78a4dd42019-02-08 11:09:30 -08001182 : getColorTemperatureSetting();
Christine Franks83cc5412018-07-03 14:46:07 -07001183 }
1184
1185 boolean setColorTemperature(int temperature) {
1186 mColorTemp = temperature;
1187 final boolean success = Secure.putIntForUser(getContext().getContentResolver(),
1188 Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE, temperature, mCurrentUser);
1189 onColorTemperatureChanged(temperature);
1190 return success;
1191 }
1192
1193 void onColorTemperatureChanged(int temperature) {
1194 setMatrix(temperature);
1195 mHandler.sendEmptyMessage(MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE);
1196 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001197
1198 boolean isActivatedSetting() {
Christine Franks44782612019-03-07 17:25:39 -08001199 if (mCurrentUser == UserHandle.USER_NULL) {
1200 return false;
1201 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001202 return Secure.getIntForUser(getContext().getContentResolver(),
1203 Secure.NIGHT_DISPLAY_ACTIVATED, 0, mCurrentUser) == 1;
1204 }
1205
1206 int getColorTemperatureSetting() {
Christine Franks44782612019-03-07 17:25:39 -08001207 if (mCurrentUser == UserHandle.USER_NULL) {
1208 return NOT_SET;
1209 }
Christine Franks78a4dd42019-02-08 11:09:30 -08001210 return clampNightDisplayColorTemperature(Secure.getIntForUser(
1211 getContext().getContentResolver(), Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE,
1212 NOT_SET,
1213 mCurrentUser));
1214 }
1215
1216 private int clampNightDisplayColorTemperature(int colorTemperature) {
1217 if (colorTemperature == NOT_SET) {
1218 colorTemperature = getContext().getResources().getInteger(
1219 R.integer.config_nightDisplayColorTemperatureDefault);
1220 }
1221 final int minimumTemperature = ColorDisplayManager
1222 .getMinimumColorTemperature(getContext());
1223 final int maximumTemperature = ColorDisplayManager
1224 .getMaximumColorTemperature(getContext());
1225 if (colorTemperature < minimumTemperature) {
1226 colorTemperature = minimumTemperature;
1227 } else if (colorTemperature > maximumTemperature) {
1228 colorTemperature = maximumTemperature;
1229 }
1230
1231 return colorTemperature;
1232 }
Christine Franks83cc5412018-07-03 14:46:07 -07001233 }
1234
Christine Franks245ffd42018-11-16 13:45:14 -08001235 /**
1236 * Local service that allows color transforms to be enabled from other system services.
1237 */
1238 public final class ColorDisplayServiceInternal {
1239
1240 /**
1241 * Set the current CCT value for the display white balance transform, and if the transform
1242 * is enabled, apply it.
1243 *
1244 * @param cct the color temperature in Kelvin.
1245 */
1246 public boolean setDisplayWhiteBalanceColorTemperature(int cct) {
1247 // Update the transform matrix even if it can't be applied.
Christine Franks245ffd42018-11-16 13:45:14 -08001248 mDisplayWhiteBalanceTintController.setMatrix(cct);
1249
1250 if (mDisplayWhiteBalanceTintController.isActivated()) {
Christine Franksc7fb9452019-02-04 08:45:33 -08001251 mHandler.sendEmptyMessage(MSG_APPLY_DISPLAY_WHITE_BALANCE);
Christine Franks245ffd42018-11-16 13:45:14 -08001252 return true;
1253 }
1254 return false;
1255 }
1256
1257 /**
Daniel Solomon37816412019-04-10 15:17:41 -07001258 * Reset the CCT value for the display white balance transform to its default value.
1259 */
1260 public boolean resetDisplayWhiteBalanceColorTemperature() {
1261 return setDisplayWhiteBalanceColorTemperature(getContext().getResources()
1262 .getInteger(R.integer.config_displayWhiteBalanceColorTemperatureDefault));
1263 }
1264
1265 /**
Christine Franks245ffd42018-11-16 13:45:14 -08001266 * Sets the listener and returns whether display white balance is currently enabled.
1267 */
1268 public boolean setDisplayWhiteBalanceListener(DisplayWhiteBalanceListener listener) {
1269 mDisplayWhiteBalanceListener = listener;
1270 return mDisplayWhiteBalanceTintController.isActivated();
1271 }
Daniel Solomon8b72c5b2018-11-25 11:07:13 -08001272
Christine Franksf3529b22019-01-03 13:20:17 -08001273 /**
Christine Franks66783a82019-03-28 11:45:56 -07001274 * Returns whether Display white balance is currently enabled.
1275 */
1276 public boolean isDisplayWhiteBalanceEnabled() {
1277 return isDisplayWhiteBalanceSettingEnabled();
1278 }
1279
1280 /**
Christine Franksf3529b22019-01-03 13:20:17 -08001281 * Adds a {@link WeakReference<ColorTransformController>} for a newly started activity, and
1282 * invokes {@link ColorTransformController#applyAppSaturation(float[], float[])} if needed.
1283 */
Christine Franks55194dc2019-01-15 13:47:06 -08001284 public boolean attachColorTransformController(String packageName, @UserIdInt int userId,
Christine Franksf3529b22019-01-03 13:20:17 -08001285 WeakReference<ColorTransformController> controller) {
1286 return mAppSaturationController
Christine Franks55194dc2019-01-15 13:47:06 -08001287 .addColorTransformController(packageName, userId, controller);
Christine Franksf3529b22019-01-03 13:20:17 -08001288 }
Christine Franks245ffd42018-11-16 13:45:14 -08001289 }
1290
1291 /**
1292 * Listener for changes in display white balance status.
1293 */
1294 public interface DisplayWhiteBalanceListener {
1295
1296 /**
1297 * Notify that the display white balance status has changed, either due to preemption by
1298 * another transform or the feature being turned off.
1299 */
Christine Franks66783a82019-03-28 11:45:56 -07001300 void onDisplayWhiteBalanceStatusChanged(boolean activated);
Christine Franks245ffd42018-11-16 13:45:14 -08001301 }
1302
Christine Franks09c229e2018-12-14 10:37:40 -08001303 private final class TintHandler extends Handler {
1304
Christine Franks83cc5412018-07-03 14:46:07 -07001305 private TintHandler(Looper looper) {
Christine Franks09c229e2018-12-14 10:37:40 -08001306 super(looper, null, true /* async */);
1307 }
1308
1309 @Override
1310 public void handleMessage(Message msg) {
1311 switch (msg.what) {
Christine Franks27912a32019-04-02 10:43:10 -07001312 case MSG_USER_CHANGED:
1313 onUserChanged(msg.arg1);
1314 break;
1315 case MSG_SET_UP:
1316 setUp();
1317 break;
Christine Franks09c229e2018-12-14 10:37:40 -08001318 case MSG_APPLY_GLOBAL_SATURATION:
1319 mGlobalSaturationTintController.setMatrix(msg.arg1);
1320 applyTint(mGlobalSaturationTintController, false);
1321 break;
Christine Franks83cc5412018-07-03 14:46:07 -07001322 case MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE:
1323 applyTint(mNightDisplayTintController, true);
1324 break;
1325 case MSG_APPLY_NIGHT_DISPLAY_ANIMATED:
1326 applyTint(mNightDisplayTintController, false);
1327 break;
Christine Franksc7fb9452019-02-04 08:45:33 -08001328 case MSG_APPLY_DISPLAY_WHITE_BALANCE:
1329 applyTint(mDisplayWhiteBalanceTintController, false);
1330 break;
Christine Franks09c229e2018-12-14 10:37:40 -08001331 }
1332 }
1333 }
1334
Christine Franksf3529b22019-01-03 13:20:17 -08001335 /**
1336 * Interface for applying transforms to a given AppWindow.
1337 */
1338 public interface ColorTransformController {
1339
Christine Franksd154fe52019-01-04 17:17:45 -08001340 /**
1341 * Apply the given saturation (grayscale) matrix to the associated AppWindow.
1342 */
Christine Franksf3529b22019-01-03 13:20:17 -08001343 void applyAppSaturation(@Size(9) float[] matrix, @Size(3) float[] translation);
1344 }
1345
Christine Franks83cc5412018-07-03 14:46:07 -07001346 @VisibleForTesting
1347 final class BinderService extends IColorDisplayManager.Stub {
Christine Franks57fdde82018-07-03 14:46:07 -07001348
Christine Franks39b03112018-07-03 14:46:07 -07001349 @Override
Christine Franksd154fe52019-01-04 17:17:45 -08001350 public void setColorMode(int colorMode) {
1351 getContext().enforceCallingOrSelfPermission(
1352 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1353 "Permission required to set display color mode");
1354 final long token = Binder.clearCallingIdentity();
1355 try {
1356 setColorModeInternal(colorMode);
1357 } finally {
1358 Binder.restoreCallingIdentity(token);
1359 }
1360 }
1361
1362 @Override
1363 public int getColorMode() {
1364 final long token = Binder.clearCallingIdentity();
1365 try {
1366 return getColorModeInternal();
1367 } finally {
1368 Binder.restoreCallingIdentity(token);
1369 }
1370 }
1371
1372 @Override
Christine Franks39b03112018-07-03 14:46:07 -07001373 public boolean isDeviceColorManaged() {
1374 final long token = Binder.clearCallingIdentity();
1375 try {
1376 return isDeviceColorManagedInternal();
1377 } finally {
1378 Binder.restoreCallingIdentity(token);
1379 }
1380 }
Christine Franks09c229e2018-12-14 10:37:40 -08001381
1382 @Override
1383 public boolean setSaturationLevel(int level) {
1384 final boolean hasTransformsPermission = getContext()
1385 .checkCallingPermission(Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS)
1386 == PackageManager.PERMISSION_GRANTED;
1387 final boolean hasLegacyPermission = getContext()
1388 .checkCallingPermission(Manifest.permission.CONTROL_DISPLAY_SATURATION)
1389 == PackageManager.PERMISSION_GRANTED;
1390 if (!hasTransformsPermission && !hasLegacyPermission) {
1391 throw new SecurityException("Permission required to set display saturation level");
1392 }
1393 final long token = Binder.clearCallingIdentity();
1394 try {
1395 final Message message = mHandler.obtainMessage(MSG_APPLY_GLOBAL_SATURATION);
1396 message.arg1 = level;
1397 mHandler.sendMessage(message);
1398 } finally {
1399 Binder.restoreCallingIdentity(token);
1400 }
1401 return true;
1402 }
Christine Franksf3529b22019-01-03 13:20:17 -08001403
1404 @Override
Christine Franks6d21d342019-02-07 15:09:03 -08001405 public boolean isSaturationActivated() {
1406 getContext().enforceCallingPermission(
1407 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1408 "Permission required to get display saturation level");
1409 final long token = Binder.clearCallingIdentity();
1410 try {
1411 return !mGlobalSaturationTintController.isActivatedStateNotSet()
1412 && mGlobalSaturationTintController.isActivated();
1413 } finally {
1414 Binder.restoreCallingIdentity(token);
1415 }
1416 }
1417
1418 @Override
Christine Franksf3529b22019-01-03 13:20:17 -08001419 public boolean setAppSaturationLevel(String packageName, int level) {
1420 getContext().enforceCallingPermission(
1421 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1422 "Permission required to set display saturation level");
1423 final long token = Binder.clearCallingIdentity();
1424 try {
1425 return setAppSaturationLevelInternal(packageName, level);
1426 } finally {
1427 Binder.restoreCallingIdentity(token);
1428 }
1429 }
1430
Christine Franks55194dc2019-01-15 13:47:06 -08001431 public int getTransformCapabilities() {
1432 getContext().enforceCallingPermission(
1433 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1434 "Permission required to query transform capabilities");
1435 final long token = Binder.clearCallingIdentity();
1436 try {
1437 return getTransformCapabilitiesInternal();
1438 } finally {
1439 Binder.restoreCallingIdentity(token);
1440 }
1441 }
1442
Christine Franksf3529b22019-01-03 13:20:17 -08001443 @Override
Christine Franks83cc5412018-07-03 14:46:07 -07001444 public boolean setNightDisplayActivated(boolean activated) {
1445 getContext().enforceCallingOrSelfPermission(
1446 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1447 "Permission required to set night display activated");
1448 final long token = Binder.clearCallingIdentity();
1449 try {
1450 mNightDisplayTintController.setActivated(activated);
1451 return true;
1452 } finally {
1453 Binder.restoreCallingIdentity(token);
1454 }
1455 }
1456
1457 @Override
1458 public boolean isNightDisplayActivated() {
1459 final long token = Binder.clearCallingIdentity();
1460 try {
1461 return mNightDisplayTintController.isActivated();
1462 } finally {
1463 Binder.restoreCallingIdentity(token);
1464 }
1465 }
1466
1467 @Override
1468 public boolean setNightDisplayColorTemperature(int temperature) {
1469 getContext().enforceCallingOrSelfPermission(
1470 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1471 "Permission required to set night display temperature");
1472 final long token = Binder.clearCallingIdentity();
1473 try {
1474 return mNightDisplayTintController.setColorTemperature(temperature);
1475 } finally {
1476 Binder.restoreCallingIdentity(token);
1477 }
1478 }
1479
1480 @Override
1481 public int getNightDisplayColorTemperature() {
1482 final long token = Binder.clearCallingIdentity();
1483 try {
1484 return mNightDisplayTintController.getColorTemperature();
1485 } finally {
1486 Binder.restoreCallingIdentity(token);
1487 }
1488 }
1489
1490 @Override
1491 public boolean setNightDisplayAutoMode(int autoMode) {
1492 getContext().enforceCallingOrSelfPermission(
1493 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1494 "Permission required to set night display auto mode");
1495 final long token = Binder.clearCallingIdentity();
1496 try {
1497 return setNightDisplayAutoModeInternal(autoMode);
1498 } finally {
1499 Binder.restoreCallingIdentity(token);
1500 }
1501 }
1502
1503 @Override
1504 public int getNightDisplayAutoMode() {
1505 getContext().enforceCallingOrSelfPermission(
1506 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1507 "Permission required to get night display auto mode");
1508 final long token = Binder.clearCallingIdentity();
1509 try {
1510 return getNightDisplayAutoModeInternal();
1511 } finally {
1512 Binder.restoreCallingIdentity(token);
1513 }
1514 }
1515
1516 @Override
1517 public int getNightDisplayAutoModeRaw() {
1518 final long token = Binder.clearCallingIdentity();
1519 try {
1520 return getNightDisplayAutoModeRawInternal();
1521 } finally {
1522 Binder.restoreCallingIdentity(token);
1523 }
1524 }
1525
1526 @Override
1527 public boolean setNightDisplayCustomStartTime(Time startTime) {
1528 getContext().enforceCallingOrSelfPermission(
1529 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1530 "Permission required to set night display custom start time");
1531 final long token = Binder.clearCallingIdentity();
1532 try {
1533 return setNightDisplayCustomStartTimeInternal(startTime);
1534 } finally {
1535 Binder.restoreCallingIdentity(token);
1536 }
1537 }
1538
1539 @Override
1540 public Time getNightDisplayCustomStartTime() {
1541 final long token = Binder.clearCallingIdentity();
1542 try {
1543 return getNightDisplayCustomStartTimeInternal();
1544 } finally {
1545 Binder.restoreCallingIdentity(token);
1546 }
1547 }
1548
1549 @Override
1550 public boolean setNightDisplayCustomEndTime(Time endTime) {
1551 getContext().enforceCallingOrSelfPermission(
1552 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1553 "Permission required to set night display custom end time");
1554 final long token = Binder.clearCallingIdentity();
1555 try {
1556 return setNightDisplayCustomEndTimeInternal(endTime);
1557 } finally {
1558 Binder.restoreCallingIdentity(token);
1559 }
1560 }
1561
1562 @Override
1563 public Time getNightDisplayCustomEndTime() {
1564 final long token = Binder.clearCallingIdentity();
1565 try {
1566 return getNightDisplayCustomEndTimeInternal();
1567 } finally {
1568 Binder.restoreCallingIdentity(token);
1569 }
1570 }
1571
1572 @Override
Christine Franks66783a82019-03-28 11:45:56 -07001573 public boolean setDisplayWhiteBalanceEnabled(boolean enabled) {
1574 getContext().enforceCallingOrSelfPermission(
1575 Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
1576 "Permission required to set night display activated");
1577 final long token = Binder.clearCallingIdentity();
1578 try {
1579 return setDisplayWhiteBalanceSettingEnabled(enabled);
1580 } finally {
1581 Binder.restoreCallingIdentity(token);
1582 }
1583 }
1584
1585 @Override
1586 public boolean isDisplayWhiteBalanceEnabled() {
1587 final long token = Binder.clearCallingIdentity();
1588 try {
1589 return isDisplayWhiteBalanceSettingEnabled();
1590 } finally {
1591 Binder.restoreCallingIdentity(token);
1592 }
1593 }
1594
1595 @Override
Christine Franksf3529b22019-01-03 13:20:17 -08001596 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Christine Franksd154fe52019-01-04 17:17:45 -08001597 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) {
1598 return;
1599 }
Christine Franksf3529b22019-01-03 13:20:17 -08001600
1601 final long token = Binder.clearCallingIdentity();
1602 try {
1603 dumpInternal(pw);
1604 } finally {
1605 Binder.restoreCallingIdentity(token);
1606 }
1607 }
Christine Franks39b03112018-07-03 14:46:07 -07001608 }
Justin Klaassen911e8892016-06-21 18:24:24 -07001609}