blob: 030c91532135e8384716edf227fce69c8bdb441c [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
17package com.android.server.display;
18
Justin Klaassen639214e2016-07-14 21:00:06 -070019import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.TypeEvaluator;
22import android.animation.ValueAnimator;
Justin Klaassen4346f632016-08-08 15:01:47 -070023import android.annotation.NonNull;
Justin Klaassen908b86c2016-08-08 09:18:42 -070024import android.annotation.Nullable;
Justin Klaassen911e8892016-06-21 18:24:24 -070025import android.app.AlarmManager;
26import android.content.BroadcastReceiver;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
Justin Klaassen2696d992016-07-11 21:26:46 -070031import android.database.ContentObserver;
32import android.net.Uri;
Justin Klaassen639214e2016-07-14 21:00:06 -070033import android.opengl.Matrix;
Justin Klaassen911e8892016-06-21 18:24:24 -070034import android.os.Handler;
35import android.os.Looper;
36import android.os.UserHandle;
37import android.provider.Settings.Secure;
Justin Klaassen639214e2016-07-14 21:00:06 -070038import android.util.MathUtils;
Justin Klaassen911e8892016-06-21 18:24:24 -070039import android.util.Slog;
Justin Klaassen639214e2016-07-14 21:00:06 -070040import android.view.animation.AnimationUtils;
Justin Klaassen911e8892016-06-21 18:24:24 -070041
Christine Franks5397f032017-11-01 18:35:16 -070042import com.android.internal.app.ColorDisplayController;
Justin Klaassen911e8892016-06-21 18:24:24 -070043import com.android.server.SystemService;
44import com.android.server.twilight.TwilightListener;
45import com.android.server.twilight.TwilightManager;
46import com.android.server.twilight.TwilightState;
47
Christine Franks03213462017-08-25 13:57:26 -070048import java.time.LocalDateTime;
49import java.time.LocalTime;
50import java.time.ZoneId;
Christine Franks8ad71492017-10-24 19:04:22 -070051
52import com.android.internal.R;
Justin Klaassen911e8892016-06-21 18:24:24 -070053
Justin Klaassen639214e2016-07-14 21:00:06 -070054import static com.android.server.display.DisplayTransformManager.LEVEL_COLOR_MATRIX_NIGHT_DISPLAY;
55
Justin Klaassen911e8892016-06-21 18:24:24 -070056/**
57 * Tints the display at night.
58 */
Christine Franks5397f032017-11-01 18:35:16 -070059public final class ColorDisplayService extends SystemService
60 implements ColorDisplayController.Callback {
Justin Klaassen911e8892016-06-21 18:24:24 -070061
Christine Franks5397f032017-11-01 18:35:16 -070062 private static final String TAG = "ColorDisplayService";
Justin Klaassen911e8892016-06-21 18:24:24 -070063
64 /**
Christine Franks7b83b4282017-01-18 14:55:00 -080065 * The transition time, in milliseconds, for Night Display to turn on/off.
66 */
67 private static final long TRANSITION_DURATION = 3000L;
68
69 /**
Justin Klaassen639214e2016-07-14 21:00:06 -070070 * The identity matrix, used if one of the given matrices is {@code null}.
71 */
72 private static final float[] MATRIX_IDENTITY = new float[16];
73 static {
74 Matrix.setIdentityM(MATRIX_IDENTITY, 0);
75 }
76
77 /**
78 * Evaluator used to animate color matrix transitions.
79 */
80 private static final ColorMatrixEvaluator COLOR_MATRIX_EVALUATOR = new ColorMatrixEvaluator();
81
Justin Klaassen2696d992016-07-11 21:26:46 -070082 private final Handler mHandler;
83
Christine Franks6418d0b2017-02-13 09:48:00 -080084 private float[] mMatrixNight = new float[16];
85
Christine Franks2a125472017-07-26 17:51:16 -070086 private final float[] mColorTempCoefficients = new float[9];
Christine Franks6418d0b2017-02-13 09:48:00 -080087
Justin Klaassen911e8892016-06-21 18:24:24 -070088 private int mCurrentUser = UserHandle.USER_NULL;
Justin Klaassen2696d992016-07-11 21:26:46 -070089 private ContentObserver mUserSetupObserver;
Justin Klaassen911e8892016-06-21 18:24:24 -070090 private boolean mBootCompleted;
91
Christine Franks5397f032017-11-01 18:35:16 -070092 private ColorDisplayController mController;
Justin Klaassen639214e2016-07-14 21:00:06 -070093 private ValueAnimator mColorMatrixAnimator;
Justin Klaassen911e8892016-06-21 18:24:24 -070094 private Boolean mIsActivated;
95 private AutoMode mAutoMode;
96
Christine Franks5397f032017-11-01 18:35:16 -070097 public ColorDisplayService(Context context) {
Justin Klaassen911e8892016-06-21 18:24:24 -070098 super(context);
Justin Klaassen2696d992016-07-11 21:26:46 -070099 mHandler = new Handler(Looper.getMainLooper());
Justin Klaassen911e8892016-06-21 18:24:24 -0700100 }
101
102 @Override
103 public void onStart() {
104 // Nothing to publish.
105 }
106
107 @Override
Justin Klaassen2696d992016-07-11 21:26:46 -0700108 public void onBootPhase(int phase) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800109 if (phase >= PHASE_BOOT_COMPLETED) {
Justin Klaassen2696d992016-07-11 21:26:46 -0700110 mBootCompleted = true;
111
112 // Register listeners now that boot is complete.
113 if (mCurrentUser != UserHandle.USER_NULL && mUserSetupObserver == null) {
114 setUp();
115 }
116 }
117 }
118
119 @Override
Justin Klaassen911e8892016-06-21 18:24:24 -0700120 public void onStartUser(int userHandle) {
121 super.onStartUser(userHandle);
122
Justin Klaassen911e8892016-06-21 18:24:24 -0700123 if (mCurrentUser == UserHandle.USER_NULL) {
Justin Klaassen2696d992016-07-11 21:26:46 -0700124 onUserChanged(userHandle);
Justin Klaassen911e8892016-06-21 18:24:24 -0700125 }
126 }
127
128 @Override
129 public void onSwitchUser(int userHandle) {
130 super.onSwitchUser(userHandle);
131
Justin Klaassen2696d992016-07-11 21:26:46 -0700132 onUserChanged(userHandle);
Justin Klaassen911e8892016-06-21 18:24:24 -0700133 }
134
135 @Override
136 public void onStopUser(int userHandle) {
137 super.onStopUser(userHandle);
138
Justin Klaassen911e8892016-06-21 18:24:24 -0700139 if (mCurrentUser == userHandle) {
Justin Klaassen2696d992016-07-11 21:26:46 -0700140 onUserChanged(UserHandle.USER_NULL);
Justin Klaassen911e8892016-06-21 18:24:24 -0700141 }
142 }
143
Justin Klaassen2696d992016-07-11 21:26:46 -0700144 private void onUserChanged(int userHandle) {
145 final ContentResolver cr = getContext().getContentResolver();
Justin Klaassen911e8892016-06-21 18:24:24 -0700146
Justin Klaassen2696d992016-07-11 21:26:46 -0700147 if (mCurrentUser != UserHandle.USER_NULL) {
148 if (mUserSetupObserver != null) {
149 cr.unregisterContentObserver(mUserSetupObserver);
150 mUserSetupObserver = null;
151 } else if (mBootCompleted) {
152 tearDown();
153 }
154 }
155
156 mCurrentUser = userHandle;
157
158 if (mCurrentUser != UserHandle.USER_NULL) {
159 if (!isUserSetupCompleted(cr, mCurrentUser)) {
160 mUserSetupObserver = new ContentObserver(mHandler) {
161 @Override
162 public void onChange(boolean selfChange, Uri uri) {
163 if (isUserSetupCompleted(cr, mCurrentUser)) {
164 cr.unregisterContentObserver(this);
165 mUserSetupObserver = null;
166
167 if (mBootCompleted) {
168 setUp();
169 }
170 }
171 }
172 };
173 cr.registerContentObserver(Secure.getUriFor(Secure.USER_SETUP_COMPLETE),
174 false /* notifyForDescendents */, mUserSetupObserver, mCurrentUser);
175 } else if (mBootCompleted) {
176 setUp();
Justin Klaassen911e8892016-06-21 18:24:24 -0700177 }
178 }
179 }
180
Justin Klaassen2696d992016-07-11 21:26:46 -0700181 private static boolean isUserSetupCompleted(ContentResolver cr, int userHandle) {
182 return Secure.getIntForUser(cr, Secure.USER_SETUP_COMPLETE, 0, userHandle) == 1;
183 }
184
185 private void setUp() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700186 Slog.d(TAG, "setUp: currentUser=" + mCurrentUser);
187
Justin Klaassen911e8892016-06-21 18:24:24 -0700188 // Create a new controller for the current user and start listening for changes.
Christine Franks5397f032017-11-01 18:35:16 -0700189 mController = new ColorDisplayController(getContext(), mCurrentUser);
Justin Klaassen911e8892016-06-21 18:24:24 -0700190 mController.setListener(this);
191
Christine Franks218e6562017-11-27 10:20:14 -0800192 setCoefficientMatrix(getContext(), DisplayTransformManager.isNativeModeEnabled());
Christine Franks8ad71492017-10-24 19:04:22 -0700193
Christine Franks6418d0b2017-02-13 09:48:00 -0800194 // Prepare color transformation matrix.
195 setMatrix(mController.getColorTemperature(), mMatrixNight);
196
Justin Klaassen911e8892016-06-21 18:24:24 -0700197 // Initialize the current auto mode.
198 onAutoModeChanged(mController.getAutoMode());
199
200 // Force the initialization current activated state.
201 if (mIsActivated == null) {
202 onActivated(mController.isActivated());
203 }
Christine Franks6418d0b2017-02-13 09:48:00 -0800204
205 // Transition the screen to the current temperature.
206 applyTint(false);
Justin Klaassen911e8892016-06-21 18:24:24 -0700207 }
208
Justin Klaassen2696d992016-07-11 21:26:46 -0700209 private void tearDown() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700210 Slog.d(TAG, "tearDown: currentUser=" + mCurrentUser);
211
Justin Klaassen2696d992016-07-11 21:26:46 -0700212 if (mController != null) {
213 mController.setListener(null);
214 mController = null;
215 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700216
217 if (mAutoMode != null) {
218 mAutoMode.onStop();
219 mAutoMode = null;
220 }
221
Justin Klaassen639214e2016-07-14 21:00:06 -0700222 if (mColorMatrixAnimator != null) {
223 mColorMatrixAnimator.end();
224 mColorMatrixAnimator = null;
225 }
226
Justin Klaassen911e8892016-06-21 18:24:24 -0700227 mIsActivated = null;
Justin Klaassen911e8892016-06-21 18:24:24 -0700228 }
229
230 @Override
231 public void onActivated(boolean activated) {
232 if (mIsActivated == null || mIsActivated != activated) {
233 Slog.i(TAG, activated ? "Turning on night display" : "Turning off night display");
234
Justin Klaassen908b86c2016-08-08 09:18:42 -0700235 mIsActivated = activated;
236
Christine Frankse5bb03e2017-02-10 17:36:10 -0800237 if (mAutoMode != null) {
238 mAutoMode.onActivated(activated);
239 }
240
Christine Franks6418d0b2017-02-13 09:48:00 -0800241 applyTint(false);
Justin Klaassen911e8892016-06-21 18:24:24 -0700242 }
243 }
244
245 @Override
246 public void onAutoModeChanged(int autoMode) {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700247 Slog.d(TAG, "onAutoModeChanged: autoMode=" + autoMode);
248
Justin Klaassen911e8892016-06-21 18:24:24 -0700249 if (mAutoMode != null) {
250 mAutoMode.onStop();
251 mAutoMode = null;
252 }
253
Christine Franks5397f032017-11-01 18:35:16 -0700254 if (autoMode == ColorDisplayController.AUTO_MODE_CUSTOM) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700255 mAutoMode = new CustomAutoMode();
Christine Franks5397f032017-11-01 18:35:16 -0700256 } else if (autoMode == ColorDisplayController.AUTO_MODE_TWILIGHT) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700257 mAutoMode = new TwilightAutoMode();
258 }
259
260 if (mAutoMode != null) {
261 mAutoMode.onStart();
262 }
263 }
264
265 @Override
Christine Franks03213462017-08-25 13:57:26 -0700266 public void onCustomStartTimeChanged(LocalTime startTime) {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700267 Slog.d(TAG, "onCustomStartTimeChanged: startTime=" + startTime);
268
Justin Klaassen911e8892016-06-21 18:24:24 -0700269 if (mAutoMode != null) {
270 mAutoMode.onCustomStartTimeChanged(startTime);
271 }
272 }
273
274 @Override
Christine Franks03213462017-08-25 13:57:26 -0700275 public void onCustomEndTimeChanged(LocalTime endTime) {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700276 Slog.d(TAG, "onCustomEndTimeChanged: endTime=" + endTime);
277
Justin Klaassen911e8892016-06-21 18:24:24 -0700278 if (mAutoMode != null) {
279 mAutoMode.onCustomEndTimeChanged(endTime);
280 }
281 }
282
Christine Franks6418d0b2017-02-13 09:48:00 -0800283 @Override
284 public void onColorTemperatureChanged(int colorTemperature) {
285 setMatrix(colorTemperature, mMatrixNight);
286 applyTint(true);
287 }
288
Christine Franks8ad71492017-10-24 19:04:22 -0700289 @Override
Christine Franks218e6562017-11-27 10:20:14 -0800290 public void onDisplayColorModeChanged(int mode) {
291 // Cancel the night display tint animator if it's running.
292 if (mColorMatrixAnimator != null) {
293 mColorMatrixAnimator.cancel();
294 }
Christine Franks8ad71492017-10-24 19:04:22 -0700295
Chia-I Wu1e0e7172018-03-14 15:45:29 -0700296 setCoefficientMatrix(getContext(), DisplayTransformManager.isColorModeNative(mode));
Christine Franks8ad71492017-10-24 19:04:22 -0700297 setMatrix(mController.getColorTemperature(), mMatrixNight);
Christine Franks218e6562017-11-27 10:20:14 -0800298
299 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
300 dtm.setColorMode(mode, mIsActivated ? mMatrixNight : MATRIX_IDENTITY);
Christine Franks8ad71492017-10-24 19:04:22 -0700301 }
302
Daniel Solomon317a3572018-03-30 18:36:37 -0700303 @Override
304 public void onAccessibilityTransformChanged(boolean state) {
305 onDisplayColorModeChanged(mController.getColorMode());
306 }
307
Christine Franks218e6562017-11-27 10:20:14 -0800308 /**
309 * Set coefficients based on native mode. Use DisplayTransformManager#isNativeModeEnabled while
310 * setting is stable; when setting is changing, pass native mode selection directly.
311 */
312 private void setCoefficientMatrix(Context context, boolean isNative) {
Christine Franks8ad71492017-10-24 19:04:22 -0700313 final String[] coefficients = context.getResources().getStringArray(isNative
314 ? R.array.config_nightDisplayColorTemperatureCoefficientsNative
315 : R.array.config_nightDisplayColorTemperatureCoefficients);
316 for (int i = 0; i < 9 && i < coefficients.length; i++) {
317 mColorTempCoefficients[i] = Float.parseFloat(coefficients[i]);
318 }
319 }
320
Christine Franks6418d0b2017-02-13 09:48:00 -0800321 /**
322 * Applies current color temperature matrix, or removes it if deactivated.
323 *
324 * @param immediate {@code true} skips transition animation
325 */
326 private void applyTint(boolean immediate) {
327 // Cancel the old animator if still running.
328 if (mColorMatrixAnimator != null) {
329 mColorMatrixAnimator.cancel();
330 }
331
Christine Franks6418d0b2017-02-13 09:48:00 -0800332 final DisplayTransformManager dtm = getLocalService(DisplayTransformManager.class);
333 final float[] from = dtm.getColorMatrix(LEVEL_COLOR_MATRIX_NIGHT_DISPLAY);
334 final float[] to = mIsActivated ? mMatrixNight : MATRIX_IDENTITY;
335
336 if (immediate) {
337 dtm.setColorMatrix(LEVEL_COLOR_MATRIX_NIGHT_DISPLAY, to);
338 } else {
339 mColorMatrixAnimator = ValueAnimator.ofObject(COLOR_MATRIX_EVALUATOR,
340 from == null ? MATRIX_IDENTITY : from, to);
341 mColorMatrixAnimator.setDuration(TRANSITION_DURATION);
342 mColorMatrixAnimator.setInterpolator(AnimationUtils.loadInterpolator(
343 getContext(), android.R.interpolator.fast_out_slow_in));
344 mColorMatrixAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
345 @Override
346 public void onAnimationUpdate(ValueAnimator animator) {
347 final float[] value = (float[]) animator.getAnimatedValue();
348 dtm.setColorMatrix(LEVEL_COLOR_MATRIX_NIGHT_DISPLAY, value);
349 }
350 });
351 mColorMatrixAnimator.addListener(new AnimatorListenerAdapter() {
352
353 private boolean mIsCancelled;
354
355 @Override
356 public void onAnimationCancel(Animator animator) {
357 mIsCancelled = true;
358 }
359
360 @Override
361 public void onAnimationEnd(Animator animator) {
362 if (!mIsCancelled) {
363 // Ensure final color matrix is set at the end of the animation. If the
364 // animation is cancelled then don't set the final color matrix so the new
365 // animator can pick up from where this one left off.
366 dtm.setColorMatrix(LEVEL_COLOR_MATRIX_NIGHT_DISPLAY, to);
367 }
368 mColorMatrixAnimator = null;
369 }
370 });
371 mColorMatrixAnimator.start();
372 }
373 }
374
375 /**
376 * Set the color transformation {@code MATRIX_NIGHT} to the given color temperature.
377 *
378 * @param colorTemperature color temperature in Kelvin
Christine Frankse5bb03e2017-02-10 17:36:10 -0800379 * @param outTemp the 4x4 display transformation matrix for that color temperature
Christine Franks6418d0b2017-02-13 09:48:00 -0800380 */
381 private void setMatrix(int colorTemperature, float[] outTemp) {
382 if (outTemp.length != 16) {
383 Slog.d(TAG, "The display transformation matrix must be 4x4");
384 return;
385 }
386
387 Matrix.setIdentityM(mMatrixNight, 0);
388
389 final float squareTemperature = colorTemperature * colorTemperature;
390 final float red = squareTemperature * mColorTempCoefficients[0]
Christine Franks2a125472017-07-26 17:51:16 -0700391 + colorTemperature * mColorTempCoefficients[1] + mColorTempCoefficients[2];
392 final float green = squareTemperature * mColorTempCoefficients[3]
393 + colorTemperature * mColorTempCoefficients[4] + mColorTempCoefficients[5];
394 final float blue = squareTemperature * mColorTempCoefficients[6]
395 + colorTemperature * mColorTempCoefficients[7] + mColorTempCoefficients[8];
Christine Franks6418d0b2017-02-13 09:48:00 -0800396 outTemp[0] = red;
397 outTemp[5] = green;
398 outTemp[10] = blue;
399 }
400
Christine Franks03213462017-08-25 13:57:26 -0700401 /**
402 * Returns the first date time corresponding to the local time that occurs before the
403 * provided date time.
404 *
405 * @param compareTime the LocalDateTime to compare against
406 * @return the prior LocalDateTime corresponding to this local time
407 */
408 public static LocalDateTime getDateTimeBefore(LocalTime localTime, LocalDateTime compareTime) {
409 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
410 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
411
412 // Check if the local time has passed, if so return the same time yesterday.
413 return ldt.isAfter(compareTime) ? ldt.minusDays(1) : ldt;
414 }
415
416 /**
417 * Returns the first date time corresponding to this local time that occurs after the
418 * provided date time.
419 *
420 * @param compareTime the LocalDateTime to compare against
421 * @return the next LocalDateTime corresponding to this local time
422 */
423 public static LocalDateTime getDateTimeAfter(LocalTime localTime, LocalDateTime compareTime) {
424 final LocalDateTime ldt = LocalDateTime.of(compareTime.getYear(), compareTime.getMonth(),
425 compareTime.getDayOfMonth(), localTime.getHour(), localTime.getMinute());
426
427 // Check if the local time has passed, if so return the same time tomorrow.
428 return ldt.isBefore(compareTime) ? ldt.plusDays(1) : ldt;
429 }
430
Christine Franks5397f032017-11-01 18:35:16 -0700431 private abstract class AutoMode implements ColorDisplayController.Callback {
Justin Klaassen911e8892016-06-21 18:24:24 -0700432 public abstract void onStart();
Christine Frankse5bb03e2017-02-10 17:36:10 -0800433
Justin Klaassen911e8892016-06-21 18:24:24 -0700434 public abstract void onStop();
435 }
436
437 private class CustomAutoMode extends AutoMode implements AlarmManager.OnAlarmListener {
438
439 private final AlarmManager mAlarmManager;
440 private final BroadcastReceiver mTimeChangedReceiver;
441
Christine Franks03213462017-08-25 13:57:26 -0700442 private LocalTime mStartTime;
443 private LocalTime mEndTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700444
Christine Franks03213462017-08-25 13:57:26 -0700445 private LocalDateTime mLastActivatedTime;
Justin Klaassen911e8892016-06-21 18:24:24 -0700446
Christine Frankse5bb03e2017-02-10 17:36:10 -0800447 CustomAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -0700448 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
449 mTimeChangedReceiver = new BroadcastReceiver() {
450 @Override
451 public void onReceive(Context context, Intent intent) {
452 updateActivated();
453 }
454 };
455 }
456
457 private void updateActivated() {
Christine Franks03213462017-08-25 13:57:26 -0700458 final LocalDateTime now = LocalDateTime.now();
459 final LocalDateTime start = getDateTimeBefore(mStartTime, now);
460 final LocalDateTime end = getDateTimeAfter(mEndTime, start);
461 boolean activate = now.isBefore(end);
Justin Klaassen911e8892016-06-21 18:24:24 -0700462
Christine Frankse5bb03e2017-02-10 17:36:10 -0800463 if (mLastActivatedTime != null) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800464 // Maintain the existing activated state if within the current period.
Christine Franks03213462017-08-25 13:57:26 -0700465 if (mLastActivatedTime.isBefore(now) && mLastActivatedTime.isAfter(start)
466 && (mLastActivatedTime.isAfter(end) || now.isBefore(end))) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800467 activate = mController.isActivated();
Justin Klaassen911e8892016-06-21 18:24:24 -0700468 }
469 }
470
Christine Frankse5bb03e2017-02-10 17:36:10 -0800471 if (mIsActivated == null || mIsActivated != activate) {
472 mController.setActivated(activate);
Justin Klaassen911e8892016-06-21 18:24:24 -0700473 }
Christine Franks03213462017-08-25 13:57:26 -0700474
Justin Klaassen4346f632016-08-08 15:01:47 -0700475 updateNextAlarm(mIsActivated, now);
Justin Klaassen911e8892016-06-21 18:24:24 -0700476 }
477
Christine Franks03213462017-08-25 13:57:26 -0700478 private void updateNextAlarm(@Nullable Boolean activated, @NonNull LocalDateTime now) {
Justin Klaassen4346f632016-08-08 15:01:47 -0700479 if (activated != null) {
Christine Franks03213462017-08-25 13:57:26 -0700480 final LocalDateTime next = activated ? getDateTimeAfter(mEndTime, now)
481 : getDateTimeAfter(mStartTime, now);
482 final long millis = next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
483 mAlarmManager.setExact(AlarmManager.RTC, millis, TAG, this, null);
Justin Klaassen911e8892016-06-21 18:24:24 -0700484 }
485 }
486
487 @Override
488 public void onStart() {
489 final IntentFilter intentFilter = new IntentFilter(Intent.ACTION_TIME_CHANGED);
490 intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
491 getContext().registerReceiver(mTimeChangedReceiver, intentFilter);
492
493 mStartTime = mController.getCustomStartTime();
494 mEndTime = mController.getCustomEndTime();
495
Christine Franks1454eae2017-05-31 10:52:22 -0700496 mLastActivatedTime = mController.getLastActivatedTime();
Christine Frankse5bb03e2017-02-10 17:36:10 -0800497
Justin Klaassen911e8892016-06-21 18:24:24 -0700498 // Force an update to initialize state.
499 updateActivated();
500 }
501
502 @Override
503 public void onStop() {
504 getContext().unregisterReceiver(mTimeChangedReceiver);
505
506 mAlarmManager.cancel(this);
507 mLastActivatedTime = null;
508 }
509
510 @Override
511 public void onActivated(boolean activated) {
Christine Franks1454eae2017-05-31 10:52:22 -0700512 mLastActivatedTime = mController.getLastActivatedTime();
Christine Franks03213462017-08-25 13:57:26 -0700513 updateNextAlarm(activated, LocalDateTime.now());
Justin Klaassen911e8892016-06-21 18:24:24 -0700514 }
515
516 @Override
Christine Franks03213462017-08-25 13:57:26 -0700517 public void onCustomStartTimeChanged(LocalTime startTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700518 mStartTime = startTime;
519 mLastActivatedTime = null;
520 updateActivated();
521 }
522
523 @Override
Christine Franks03213462017-08-25 13:57:26 -0700524 public void onCustomEndTimeChanged(LocalTime endTime) {
Justin Klaassen911e8892016-06-21 18:24:24 -0700525 mEndTime = endTime;
526 mLastActivatedTime = null;
527 updateActivated();
528 }
529
530 @Override
531 public void onAlarm() {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700532 Slog.d(TAG, "onAlarm");
Justin Klaassen911e8892016-06-21 18:24:24 -0700533 updateActivated();
534 }
535 }
536
537 private class TwilightAutoMode extends AutoMode implements TwilightListener {
538
539 private final TwilightManager mTwilightManager;
Justin Klaassen911e8892016-06-21 18:24:24 -0700540
Christine Frankse5bb03e2017-02-10 17:36:10 -0800541 TwilightAutoMode() {
Justin Klaassen911e8892016-06-21 18:24:24 -0700542 mTwilightManager = getLocalService(TwilightManager.class);
Justin Klaassen911e8892016-06-21 18:24:24 -0700543 }
544
Justin Klaassen908b86c2016-08-08 09:18:42 -0700545 private void updateActivated(TwilightState state) {
Justin Klaassen3da4c442017-05-05 15:19:33 -0700546 if (state == null) {
547 // If there isn't a valid TwilightState then just keep the current activated
548 // state.
549 return;
550 }
551
552 boolean activate = state.isNight();
Christine Franks03213462017-08-25 13:57:26 -0700553 final LocalDateTime lastActivatedTime = mController.getLastActivatedTime();
Justin Klaassen3da4c442017-05-05 15:19:33 -0700554 if (lastActivatedTime != null) {
Christine Franks03213462017-08-25 13:57:26 -0700555 final LocalDateTime now = LocalDateTime.now();
556 final LocalDateTime sunrise = state.sunrise();
557 final LocalDateTime sunset = state.sunset();
Christine Frankse5bb03e2017-02-10 17:36:10 -0800558 // Maintain the existing activated state if within the current period.
Christine Franks03213462017-08-25 13:57:26 -0700559 if (lastActivatedTime.isBefore(now) && (lastActivatedTime.isBefore(sunrise)
560 ^ lastActivatedTime.isBefore(sunset))) {
Christine Frankse5bb03e2017-02-10 17:36:10 -0800561 activate = mController.isActivated();
Justin Klaassen911e8892016-06-21 18:24:24 -0700562 }
563 }
Justin Klaassen908b86c2016-08-08 09:18:42 -0700564
Christine Frankse5bb03e2017-02-10 17:36:10 -0800565 if (mIsActivated == null || mIsActivated != activate) {
566 mController.setActivated(activate);
Justin Klaassen908b86c2016-08-08 09:18:42 -0700567 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700568 }
569
570 @Override
571 public void onStart() {
572 mTwilightManager.registerListener(this, mHandler);
573
574 // Force an update to initialize state.
Justin Klaassen908b86c2016-08-08 09:18:42 -0700575 updateActivated(mTwilightManager.getLastTwilightState());
Justin Klaassen911e8892016-06-21 18:24:24 -0700576 }
577
578 @Override
579 public void onStop() {
580 mTwilightManager.unregisterListener(this);
581 }
582
583 @Override
Justin Klaassen908b86c2016-08-08 09:18:42 -0700584 public void onActivated(boolean activated) {
Justin Klaassen908b86c2016-08-08 09:18:42 -0700585 }
586
587 @Override
588 public void onTwilightStateChanged(@Nullable TwilightState state) {
Justin Klaassenec8837a2016-08-23 12:04:42 -0700589 Slog.d(TAG, "onTwilightStateChanged: isNight="
590 + (state == null ? null : state.isNight()));
Justin Klaassen908b86c2016-08-08 09:18:42 -0700591 updateActivated(state);
Justin Klaassen911e8892016-06-21 18:24:24 -0700592 }
593 }
Justin Klaassen639214e2016-07-14 21:00:06 -0700594
595 /**
596 * Interpolates between two 4x4 color transform matrices (in column-major order).
597 */
598 private static class ColorMatrixEvaluator implements TypeEvaluator<float[]> {
599
600 /**
601 * Result matrix returned by {@link #evaluate(float, float[], float[])}.
602 */
603 private final float[] mResultMatrix = new float[16];
604
605 @Override
606 public float[] evaluate(float fraction, float[] startValue, float[] endValue) {
607 for (int i = 0; i < mResultMatrix.length; i++) {
608 mResultMatrix[i] = MathUtils.lerp(startValue[i], endValue[i], fraction);
609 }
610 return mResultMatrix;
611 }
612 }
Justin Klaassen911e8892016-06-21 18:24:24 -0700613}