DisplayPowerController.java revision a15aa7d426972daecc0e8cd31dcf4d6bc656f1e9
1/*
2 * Copyright (C) 2012 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
19import com.android.internal.app.IBatteryStats;
20import com.android.server.LocalServices;
21import com.android.server.am.BatteryStatsService;
22import com.android.server.lights.LightsManager;
23
24import android.animation.Animator;
25import android.animation.ObjectAnimator;
26import android.content.Context;
27import android.content.res.Resources;
28import android.hardware.Sensor;
29import android.hardware.SensorEvent;
30import android.hardware.SensorEventListener;
31import android.hardware.SensorManager;
32import android.hardware.display.DisplayManagerInternal.DisplayPowerCallbacks;
33import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
34import android.os.Handler;
35import android.os.Looper;
36import android.os.Message;
37import android.os.PowerManager;
38import android.os.RemoteException;
39import android.os.SystemClock;
40import android.os.Trace;
41import android.util.MathUtils;
42import android.util.Slog;
43import android.util.Spline;
44import android.util.TimeUtils;
45import android.view.Display;
46import android.view.WindowManagerPolicy;
47
48import java.io.PrintWriter;
49
50/**
51 * Controls the power state of the display.
52 *
53 * Handles the proximity sensor, light sensor, and animations between states
54 * including the screen off animation.
55 *
56 * This component acts independently of the rest of the power manager service.
57 * In particular, it does not share any state and it only communicates
58 * via asynchronous callbacks to inform the power manager that something has
59 * changed.
60 *
61 * Everything this class does internally is serialized on its handler although
62 * it may be accessed by other threads from the outside.
63 *
64 * Note that the power manager service guarantees that it will hold a suspend
65 * blocker as long as the display is not ready.  So most of the work done here
66 * does not need to worry about holding a suspend blocker unless it happens
67 * independently of the display ready signal.
68   *
69 * For debugging, you can make the color fade and brightness animations run
70 * slower by changing the "animator duration scale" option in Development Settings.
71 */
72final class DisplayPowerController implements AutomaticBrightnessController.Callbacks {
73    private static final String TAG = "DisplayPowerController";
74
75    private static boolean DEBUG = false;
76    private static final boolean DEBUG_PRETEND_PROXIMITY_SENSOR_ABSENT = false;
77
78    private static final String SCREEN_ON_BLOCKED_TRACE_NAME = "Screen on blocked";
79
80    // If true, uses the color fade on animation.
81    // We might want to turn this off if we cannot get a guarantee that the screen
82    // actually turns on and starts showing new content after the call to set the
83    // screen state returns.  Playing the animation can also be somewhat slow.
84    private static final boolean USE_COLOR_FADE_ON_ANIMATION = false;
85
86    // The minimum reduction in brightness when dimmed.
87    private static final int SCREEN_DIM_MINIMUM_REDUCTION = 10;
88
89    private static final int COLOR_FADE_ON_ANIMATION_DURATION_MILLIS = 250;
90    private static final int COLOR_FADE_OFF_ANIMATION_DURATION_MILLIS = 400;
91
92    private static final int MSG_UPDATE_POWER_STATE = 1;
93    private static final int MSG_PROXIMITY_SENSOR_DEBOUNCED = 2;
94    private static final int MSG_SCREEN_ON_UNBLOCKED = 3;
95
96    private static final int PROXIMITY_UNKNOWN = -1;
97    private static final int PROXIMITY_NEGATIVE = 0;
98    private static final int PROXIMITY_POSITIVE = 1;
99
100    // Proximity sensor debounce delay in milliseconds for positive or negative transitions.
101    private static final int PROXIMITY_SENSOR_POSITIVE_DEBOUNCE_DELAY = 0;
102    private static final int PROXIMITY_SENSOR_NEGATIVE_DEBOUNCE_DELAY = 250;
103
104    // Trigger proximity if distance is less than 5 cm.
105    private static final float TYPICAL_PROXIMITY_THRESHOLD = 5.0f;
106
107    // Brightness animation ramp rate in brightness units per second.
108    private static final int BRIGHTNESS_RAMP_RATE_FAST = 200;
109    private static final int BRIGHTNESS_RAMP_RATE_SLOW = 40;
110
111    private final Object mLock = new Object();
112
113    private final Context mContext;
114
115    // Our handler.
116    private final DisplayControllerHandler mHandler;
117
118    // Asynchronous callbacks into the power manager service.
119    // Only invoked from the handler thread while no locks are held.
120    private final DisplayPowerCallbacks mCallbacks;
121
122    // Battery stats.
123    private final IBatteryStats mBatteryStats;
124
125    // The lights service.
126    private final LightsManager mLights;
127
128    // The sensor manager.
129    private final SensorManager mSensorManager;
130
131    // The window manager policy.
132    private final WindowManagerPolicy mWindowManagerPolicy;
133
134    // The display blanker.
135    private final DisplayBlanker mBlanker;
136
137    // The proximity sensor, or null if not available or needed.
138    private Sensor mProximitySensor;
139
140    // The doze screen brightness.
141    private final int mScreenBrightnessDozeConfig;
142
143    // The dim screen brightness.
144    private final int mScreenBrightnessDimConfig;
145
146    // The minimum screen brightness to use in a very dark room.
147    private final int mScreenBrightnessDarkConfig;
148
149    // The minimum allowed brightness.
150    private final int mScreenBrightnessRangeMinimum;
151
152    // The maximum allowed brightness.
153    private final int mScreenBrightnessRangeMaximum;
154
155    // True if auto-brightness should be used.
156    private boolean mUseSoftwareAutoBrightnessConfig;
157
158    // True if should use light sensor to automatically determine doze screen brightness.
159    private final boolean mAllowAutoBrightnessWhileDozingConfig;
160
161    // True if we should fade the screen while turning it off, false if we should play
162    // a stylish color fade animation instead.
163    private boolean mColorFadeFadesConfig;
164
165    // The pending power request.
166    // Initially null until the first call to requestPowerState.
167    // Guarded by mLock.
168    private DisplayPowerRequest mPendingRequestLocked;
169
170    // True if a request has been made to wait for the proximity sensor to go negative.
171    // Guarded by mLock.
172    private boolean mPendingWaitForNegativeProximityLocked;
173
174    // True if the pending power request or wait for negative proximity flag
175    // has been changed since the last update occurred.
176    // Guarded by mLock.
177    private boolean mPendingRequestChangedLocked;
178
179    // Set to true when the important parts of the pending power request have been applied.
180    // The important parts are mainly the screen state.  Brightness changes may occur
181    // concurrently.
182    // Guarded by mLock.
183    private boolean mDisplayReadyLocked;
184
185    // Set to true if a power state update is required.
186    // Guarded by mLock.
187    private boolean mPendingUpdatePowerStateLocked;
188
189    /* The following state must only be accessed by the handler thread. */
190
191    // The currently requested power state.
192    // The power controller will progressively update its internal state to match
193    // the requested power state.  Initially null until the first update.
194    private DisplayPowerRequest mPowerRequest;
195
196    // The current power state.
197    // Must only be accessed on the handler thread.
198    private DisplayPowerState mPowerState;
199
200    // True if the device should wait for negative proximity sensor before
201    // waking up the screen.  This is set to false as soon as a negative
202    // proximity sensor measurement is observed or when the device is forced to
203    // go to sleep by the user.  While true, the screen remains off.
204    private boolean mWaitingForNegativeProximity;
205
206    // The actual proximity sensor threshold value.
207    private float mProximityThreshold;
208
209    // Set to true if the proximity sensor listener has been registered
210    // with the sensor manager.
211    private boolean mProximitySensorEnabled;
212
213    // The debounced proximity sensor state.
214    private int mProximity = PROXIMITY_UNKNOWN;
215
216    // The raw non-debounced proximity sensor state.
217    private int mPendingProximity = PROXIMITY_UNKNOWN;
218    private long mPendingProximityDebounceTime = -1; // -1 if fully debounced
219
220    // True if the screen was turned off because of the proximity sensor.
221    // When the screen turns on again, we report user activity to the power manager.
222    private boolean mScreenOffBecauseOfProximity;
223
224    // The currently active screen on unblocker.  This field is non-null whenever
225    // we are waiting for a callback to release it and unblock the screen.
226    private ScreenOnUnblocker mPendingScreenOnUnblocker;
227
228    // True if we were in the process of turning off the screen.
229    // This allows us to recover more gracefully from situations where we abort
230    // turning off the screen.
231    private boolean mPendingScreenOff;
232
233    // True if we have unfinished business and are holding a suspend blocker.
234    private boolean mUnfinishedBusiness;
235
236    // The elapsed real time when the screen on was blocked.
237    private long mScreenOnBlockStartRealTime;
238
239    // Remembers whether certain kinds of brightness adjustments
240    // were recently applied so that we can decide how to transition.
241    private boolean mAppliedAutoBrightness;
242    private boolean mAppliedDimming;
243    private boolean mAppliedLowPower;
244
245    // The controller for the automatic brightness level.
246    private AutomaticBrightnessController mAutomaticBrightnessController;
247
248    // Animators.
249    private ObjectAnimator mColorFadeOnAnimator;
250    private ObjectAnimator mColorFadeOffAnimator;
251    private RampAnimator<DisplayPowerState> mScreenBrightnessRampAnimator;
252
253    /**
254     * Creates the display power controller.
255     */
256    public DisplayPowerController(Context context,
257            DisplayPowerCallbacks callbacks, Handler handler,
258            SensorManager sensorManager, DisplayBlanker blanker) {
259        mHandler = new DisplayControllerHandler(handler.getLooper());
260        mCallbacks = callbacks;
261
262        mBatteryStats = BatteryStatsService.getService();
263        mLights = LocalServices.getService(LightsManager.class);
264        mSensorManager = sensorManager;
265        mWindowManagerPolicy = LocalServices.getService(WindowManagerPolicy.class);
266        mBlanker = blanker;
267        mContext = context;
268
269        final Resources resources = context.getResources();
270        final int screenBrightnessSettingMinimum = clampAbsoluteBrightness(resources.getInteger(
271                com.android.internal.R.integer.config_screenBrightnessSettingMinimum));
272
273        mScreenBrightnessDozeConfig = clampAbsoluteBrightness(resources.getInteger(
274                com.android.internal.R.integer.config_screenBrightnessDoze));
275
276        mScreenBrightnessDimConfig = clampAbsoluteBrightness(resources.getInteger(
277                com.android.internal.R.integer.config_screenBrightnessDim));
278
279        mScreenBrightnessDarkConfig = clampAbsoluteBrightness(resources.getInteger(
280                com.android.internal.R.integer.config_screenBrightnessDark));
281        if (mScreenBrightnessDarkConfig > mScreenBrightnessDimConfig) {
282            Slog.w(TAG, "Expected config_screenBrightnessDark ("
283                    + mScreenBrightnessDarkConfig + ") to be less than or equal to "
284                    + "config_screenBrightnessDim (" + mScreenBrightnessDimConfig + ").");
285        }
286        if (mScreenBrightnessDarkConfig > mScreenBrightnessDimConfig) {
287            Slog.w(TAG, "Expected config_screenBrightnessDark ("
288                    + mScreenBrightnessDarkConfig + ") to be less than or equal to "
289                    + "config_screenBrightnessSettingMinimum ("
290                    + screenBrightnessSettingMinimum + ").");
291        }
292
293        int screenBrightnessRangeMinimum = Math.min(Math.min(
294                screenBrightnessSettingMinimum, mScreenBrightnessDimConfig),
295                mScreenBrightnessDarkConfig);
296
297        mScreenBrightnessRangeMaximum = PowerManager.BRIGHTNESS_ON;
298
299        mUseSoftwareAutoBrightnessConfig = resources.getBoolean(
300                com.android.internal.R.bool.config_automatic_brightness_available);
301
302        mAllowAutoBrightnessWhileDozingConfig = resources.getBoolean(
303                com.android.internal.R.bool.config_allowAutoBrightnessWhileDozing);
304
305        if (mUseSoftwareAutoBrightnessConfig) {
306            int[] lux = resources.getIntArray(
307                    com.android.internal.R.array.config_autoBrightnessLevels);
308            int[] screenBrightness = resources.getIntArray(
309                    com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
310            int lightSensorWarmUpTimeConfig = resources.getInteger(
311                    com.android.internal.R.integer.config_lightSensorWarmupTime);
312            final float dozeScaleFactor = resources.getFraction(
313                    com.android.internal.R.fraction.config_screenAutoBrightnessDozeScaleFactor,
314                    1, 1);
315
316            Spline screenAutoBrightnessSpline = createAutoBrightnessSpline(lux, screenBrightness);
317            if (screenAutoBrightnessSpline == null) {
318                Slog.e(TAG, "Error in config.xml.  config_autoBrightnessLcdBacklightValues "
319                        + "(size " + screenBrightness.length + ") "
320                        + "must be monotic and have exactly one more entry than "
321                        + "config_autoBrightnessLevels (size " + lux.length + ") "
322                        + "which must be strictly increasing.  "
323                        + "Auto-brightness will be disabled.");
324                mUseSoftwareAutoBrightnessConfig = false;
325            } else {
326                int bottom = clampAbsoluteBrightness(screenBrightness[0]);
327                if (mScreenBrightnessDarkConfig > bottom) {
328                    Slog.w(TAG, "config_screenBrightnessDark (" + mScreenBrightnessDarkConfig
329                            + ") should be less than or equal to the first value of "
330                            + "config_autoBrightnessLcdBacklightValues ("
331                            + bottom + ").");
332                }
333                if (bottom < screenBrightnessRangeMinimum) {
334                    screenBrightnessRangeMinimum = bottom;
335                }
336                mAutomaticBrightnessController = new AutomaticBrightnessController(this,
337                        handler.getLooper(), sensorManager, screenAutoBrightnessSpline,
338                        lightSensorWarmUpTimeConfig, screenBrightnessRangeMinimum,
339                        mScreenBrightnessRangeMaximum, dozeScaleFactor);
340            }
341        }
342
343        mScreenBrightnessRangeMinimum = screenBrightnessRangeMinimum;
344
345        mColorFadeFadesConfig = resources.getBoolean(
346                com.android.internal.R.bool.config_animateScreenLights);
347
348        if (!DEBUG_PRETEND_PROXIMITY_SENSOR_ABSENT) {
349            mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
350            if (mProximitySensor != null) {
351                mProximityThreshold = Math.min(mProximitySensor.getMaximumRange(),
352                        TYPICAL_PROXIMITY_THRESHOLD);
353            }
354        }
355
356    }
357
358    /**
359     * Returns true if the proximity sensor screen-off function is available.
360     */
361    public boolean isProximitySensorAvailable() {
362        return mProximitySensor != null;
363    }
364
365    /**
366     * Requests a new power state.
367     * The controller makes a copy of the provided object and then
368     * begins adjusting the power state to match what was requested.
369     *
370     * @param request The requested power state.
371     * @param waitForNegativeProximity If true, issues a request to wait for
372     * negative proximity before turning the screen back on, assuming the screen
373     * was turned off by the proximity sensor.
374     * @return True if display is ready, false if there are important changes that must
375     * be made asynchronously (such as turning the screen on), in which case the caller
376     * should grab a wake lock, watch for {@link DisplayPowerCallbacks#onStateChanged()}
377     * then try the request again later until the state converges.
378     */
379    public boolean requestPowerState(DisplayPowerRequest request,
380            boolean waitForNegativeProximity) {
381        if (DEBUG) {
382            Slog.d(TAG, "requestPowerState: "
383                    + request + ", waitForNegativeProximity=" + waitForNegativeProximity);
384        }
385
386        synchronized (mLock) {
387            boolean changed = false;
388
389            if (waitForNegativeProximity
390                    && !mPendingWaitForNegativeProximityLocked) {
391                mPendingWaitForNegativeProximityLocked = true;
392                changed = true;
393            }
394
395            if (mPendingRequestLocked == null) {
396                mPendingRequestLocked = new DisplayPowerRequest(request);
397                changed = true;
398            } else if (!mPendingRequestLocked.equals(request)) {
399                mPendingRequestLocked.copyFrom(request);
400                changed = true;
401            }
402
403            if (changed) {
404                mDisplayReadyLocked = false;
405            }
406
407            if (changed && !mPendingRequestChangedLocked) {
408                mPendingRequestChangedLocked = true;
409                sendUpdatePowerStateLocked();
410            }
411
412            return mDisplayReadyLocked;
413        }
414    }
415
416    private void sendUpdatePowerState() {
417        synchronized (mLock) {
418            sendUpdatePowerStateLocked();
419        }
420    }
421
422    private void sendUpdatePowerStateLocked() {
423        if (!mPendingUpdatePowerStateLocked) {
424            mPendingUpdatePowerStateLocked = true;
425            Message msg = mHandler.obtainMessage(MSG_UPDATE_POWER_STATE);
426            msg.setAsynchronous(true);
427            mHandler.sendMessage(msg);
428        }
429    }
430
431    private void initialize() {
432        // Initialize the power state object for the default display.
433        // In the future, we might manage multiple displays independently.
434        mPowerState = new DisplayPowerState(mBlanker,
435                mLights.getLight(LightsManager.LIGHT_ID_BACKLIGHT),
436                new ColorFade(Display.DEFAULT_DISPLAY));
437
438        mColorFadeOnAnimator = ObjectAnimator.ofFloat(
439                mPowerState, DisplayPowerState.COLOR_FADE_LEVEL, 0.0f, 1.0f);
440        mColorFadeOnAnimator.setDuration(COLOR_FADE_ON_ANIMATION_DURATION_MILLIS);
441        mColorFadeOnAnimator.addListener(mAnimatorListener);
442
443        mColorFadeOffAnimator = ObjectAnimator.ofFloat(
444                mPowerState, DisplayPowerState.COLOR_FADE_LEVEL, 1.0f, 0.0f);
445        mColorFadeOffAnimator.setDuration(COLOR_FADE_OFF_ANIMATION_DURATION_MILLIS);
446        mColorFadeOffAnimator.addListener(mAnimatorListener);
447
448        mScreenBrightnessRampAnimator = new RampAnimator<DisplayPowerState>(
449                mPowerState, DisplayPowerState.SCREEN_BRIGHTNESS);
450        mScreenBrightnessRampAnimator.setListener(mRampAnimatorListener);
451
452        // Initialize screen state for battery stats.
453        try {
454            mBatteryStats.noteScreenState(mPowerState.getScreenState());
455            mBatteryStats.noteScreenBrightness(mPowerState.getScreenBrightness());
456        } catch (RemoteException ex) {
457            // same process
458        }
459    }
460
461    private final Animator.AnimatorListener mAnimatorListener = new Animator.AnimatorListener() {
462        @Override
463        public void onAnimationStart(Animator animation) {
464        }
465        @Override
466        public void onAnimationEnd(Animator animation) {
467            sendUpdatePowerState();
468        }
469        @Override
470        public void onAnimationRepeat(Animator animation) {
471        }
472        @Override
473        public void onAnimationCancel(Animator animation) {
474        }
475    };
476
477    private final RampAnimator.Listener mRampAnimatorListener = new RampAnimator.Listener() {
478        @Override
479        public void onAnimationEnd() {
480            sendUpdatePowerState();
481        }
482    };
483
484    private void updatePowerState() {
485        // Update the power state request.
486        final boolean mustNotify;
487        boolean mustInitialize = false;
488        boolean autoBrightnessAdjustmentChanged = false;
489
490        synchronized (mLock) {
491            mPendingUpdatePowerStateLocked = false;
492            if (mPendingRequestLocked == null) {
493                return; // wait until first actual power request
494            }
495
496            if (mPowerRequest == null) {
497                mPowerRequest = new DisplayPowerRequest(mPendingRequestLocked);
498                mWaitingForNegativeProximity = mPendingWaitForNegativeProximityLocked;
499                mPendingWaitForNegativeProximityLocked = false;
500                mPendingRequestChangedLocked = false;
501                mustInitialize = true;
502            } else if (mPendingRequestChangedLocked) {
503                autoBrightnessAdjustmentChanged = (mPowerRequest.screenAutoBrightnessAdjustment
504                        != mPendingRequestLocked.screenAutoBrightnessAdjustment);
505                mPowerRequest.copyFrom(mPendingRequestLocked);
506                mWaitingForNegativeProximity |= mPendingWaitForNegativeProximityLocked;
507                mPendingWaitForNegativeProximityLocked = false;
508                mPendingRequestChangedLocked = false;
509                mDisplayReadyLocked = false;
510            }
511
512            mustNotify = !mDisplayReadyLocked;
513        }
514
515        // Initialize things the first time the power state is changed.
516        if (mustInitialize) {
517            initialize();
518        }
519
520        // Compute the basic display state using the policy.
521        // We might override this below based on other factors.
522        int state;
523        int brightness = PowerManager.BRIGHTNESS_DEFAULT;
524        boolean performScreenOffTransition = false;
525        switch (mPowerRequest.policy) {
526            case DisplayPowerRequest.POLICY_OFF:
527                state = Display.STATE_OFF;
528                performScreenOffTransition = true;
529                break;
530            case DisplayPowerRequest.POLICY_DOZE:
531                if (mPowerRequest.dozeScreenState != Display.STATE_UNKNOWN) {
532                    state = mPowerRequest.dozeScreenState;
533                } else {
534                    state = Display.STATE_DOZE;
535                }
536                if (!mAllowAutoBrightnessWhileDozingConfig) {
537                    brightness = mPowerRequest.dozeScreenBrightness;
538                }
539                break;
540            case DisplayPowerRequest.POLICY_DIM:
541            case DisplayPowerRequest.POLICY_BRIGHT:
542            default:
543                state = Display.STATE_ON;
544                break;
545        }
546        assert(state != Display.STATE_UNKNOWN);
547
548        // Apply the proximity sensor.
549        if (mProximitySensor != null) {
550            if (mPowerRequest.useProximitySensor && state != Display.STATE_OFF) {
551                setProximitySensorEnabled(true);
552                if (!mScreenOffBecauseOfProximity
553                        && mProximity == PROXIMITY_POSITIVE) {
554                    mScreenOffBecauseOfProximity = true;
555                    sendOnProximityPositiveWithWakelock();
556                }
557            } else if (mWaitingForNegativeProximity
558                    && mScreenOffBecauseOfProximity
559                    && mProximity == PROXIMITY_POSITIVE
560                    && state != Display.STATE_OFF) {
561                setProximitySensorEnabled(true);
562            } else {
563                setProximitySensorEnabled(false);
564                mWaitingForNegativeProximity = false;
565            }
566            if (mScreenOffBecauseOfProximity
567                    && mProximity != PROXIMITY_POSITIVE) {
568                mScreenOffBecauseOfProximity = false;
569                sendOnProximityNegativeWithWakelock();
570            }
571        } else {
572            mWaitingForNegativeProximity = false;
573        }
574        if (mScreenOffBecauseOfProximity) {
575            state = Display.STATE_OFF;
576        }
577
578        // Animate the screen state change unless already animating.
579        // The transition may be deferred, so after this point we will use the
580        // actual state instead of the desired one.
581        animateScreenStateChange(state, performScreenOffTransition);
582        state = mPowerState.getScreenState();
583
584        // Use zero brightness when screen is off.
585        // Use full brightness when screen brightness is boosted.
586        if (state == Display.STATE_OFF) {
587            brightness = PowerManager.BRIGHTNESS_OFF;
588        } else if (mPowerRequest.boostScreenBrightness) {
589            brightness = PowerManager.BRIGHTNESS_ON;
590        }
591
592        // Configure auto-brightness.
593        boolean autoBrightnessEnabled = false;
594        if (mAutomaticBrightnessController != null) {
595            final boolean autoBrightnessEnabledInDoze = mAllowAutoBrightnessWhileDozingConfig
596                    && (state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND);
597            autoBrightnessEnabled = mPowerRequest.useAutoBrightness
598                    && (state == Display.STATE_ON || autoBrightnessEnabledInDoze)
599                    && brightness < 0;
600            mAutomaticBrightnessController.configure(autoBrightnessEnabled,
601                    mPowerRequest.screenAutoBrightnessAdjustment, state != Display.STATE_ON);
602        }
603
604        // Apply auto-brightness.
605        boolean slowChange = false;
606        if (brightness < 0) {
607            if (autoBrightnessEnabled) {
608                brightness = mAutomaticBrightnessController.getAutomaticScreenBrightness();
609            }
610            if (brightness >= 0) {
611                // Use current auto-brightness value and slowly adjust to changes.
612                brightness = clampScreenBrightness(brightness);
613                if (mAppliedAutoBrightness && !autoBrightnessAdjustmentChanged) {
614                    slowChange = true; // slowly adapt to auto-brightness
615                }
616                mAppliedAutoBrightness = true;
617            } else {
618                mAppliedAutoBrightness = false;
619            }
620        } else {
621            mAppliedAutoBrightness = false;
622        }
623
624        // Use default brightness when dozing unless overridden.
625        if (brightness < 0 && (state == Display.STATE_DOZE
626                || state == Display.STATE_DOZE_SUSPEND)) {
627            brightness = mScreenBrightnessDozeConfig;
628        }
629
630        // Apply manual brightness.
631        // Use the current brightness setting from the request, which is expected
632        // provide a nominal default value for the case where auto-brightness
633        // is not ready yet.
634        if (brightness < 0) {
635            brightness = clampScreenBrightness(mPowerRequest.screenBrightness);
636        }
637
638        // Apply dimming by at least some minimum amount when user activity
639        // timeout is about to expire.
640        if (mPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
641            if (brightness > mScreenBrightnessRangeMinimum) {
642                brightness = Math.max(Math.min(brightness - SCREEN_DIM_MINIMUM_REDUCTION,
643                        mScreenBrightnessDimConfig), mScreenBrightnessRangeMinimum);
644            }
645            if (!mAppliedDimming) {
646                slowChange = false;
647            }
648            mAppliedDimming = true;
649        }
650
651        // If low power mode is enabled, cut the brightness level by half
652        // as long as it is above the minimum threshold.
653        if (mPowerRequest.lowPowerMode) {
654            if (brightness > mScreenBrightnessRangeMinimum) {
655                brightness = Math.max(brightness / 2, mScreenBrightnessRangeMinimum);
656            }
657            if (!mAppliedLowPower) {
658                slowChange = false;
659            }
660            mAppliedLowPower = true;
661        }
662
663        // Animate the screen brightness when the screen is on or dozing.
664        // Skip the animation when the screen is off or suspended.
665        if (state == Display.STATE_ON || state == Display.STATE_DOZE) {
666            animateScreenBrightness(brightness,
667                    slowChange ? BRIGHTNESS_RAMP_RATE_SLOW : BRIGHTNESS_RAMP_RATE_FAST);
668        } else {
669            animateScreenBrightness(brightness, 0);
670        }
671
672        // Determine whether the display is ready for use in the newly requested state.
673        // Note that we do not wait for the brightness ramp animation to complete before
674        // reporting the display is ready because we only need to ensure the screen is in the
675        // right power state even as it continues to converge on the desired brightness.
676        final boolean ready = mPendingScreenOnUnblocker == null
677                && !mColorFadeOnAnimator.isStarted()
678                && !mColorFadeOffAnimator.isStarted()
679                && mPowerState.waitUntilClean(mCleanListener);
680        final boolean finished = ready
681                && !mScreenBrightnessRampAnimator.isAnimating();
682
683        // Grab a wake lock if we have unfinished business.
684        if (!finished && !mUnfinishedBusiness) {
685            if (DEBUG) {
686                Slog.d(TAG, "Unfinished business...");
687            }
688            mCallbacks.acquireSuspendBlocker();
689            mUnfinishedBusiness = true;
690        }
691
692        // Notify the power manager when ready.
693        if (ready && mustNotify) {
694            // Send state change.
695            synchronized (mLock) {
696                if (!mPendingRequestChangedLocked) {
697                    mDisplayReadyLocked = true;
698
699                    if (DEBUG) {
700                        Slog.d(TAG, "Display ready!");
701                    }
702                }
703            }
704            sendOnStateChangedWithWakelock();
705        }
706
707        // Release the wake lock when we have no unfinished business.
708        if (finished && mUnfinishedBusiness) {
709            if (DEBUG) {
710                Slog.d(TAG, "Finished business...");
711            }
712            mUnfinishedBusiness = false;
713            mCallbacks.releaseSuspendBlocker();
714        }
715    }
716
717    @Override
718    public void updateBrightness() {
719        sendUpdatePowerState();
720    }
721
722    private void blockScreenOn() {
723        if (mPendingScreenOnUnblocker == null) {
724            Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, SCREEN_ON_BLOCKED_TRACE_NAME, 0);
725            mPendingScreenOnUnblocker = new ScreenOnUnblocker();
726            mScreenOnBlockStartRealTime = SystemClock.elapsedRealtime();
727            Slog.i(TAG, "Blocking screen on until initial contents have been drawn.");
728        }
729    }
730
731    private void unblockScreenOn() {
732        if (mPendingScreenOnUnblocker != null) {
733            mPendingScreenOnUnblocker = null;
734            long delay = SystemClock.elapsedRealtime() - mScreenOnBlockStartRealTime;
735            Slog.i(TAG, "Unblocked screen on after " + delay + " ms");
736            Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, SCREEN_ON_BLOCKED_TRACE_NAME, 0);
737        }
738    }
739
740    private boolean setScreenState(int state) {
741        if (mPowerState.getScreenState() != state) {
742            final boolean wasOn = (mPowerState.getScreenState() != Display.STATE_OFF);
743            mPowerState.setScreenState(state);
744
745            // Tell battery stats about the transition.
746            try {
747                mBatteryStats.noteScreenState(state);
748            } catch (RemoteException ex) {
749                // same process
750            }
751
752            // Tell the window manager what's happening.
753            // Temporarily block turning the screen on until the window manager is ready
754            // by leaving a black surface covering the screen.  This surface is essentially
755            // the final state of the color fade animation.
756            boolean isOn = (state != Display.STATE_OFF);
757            if (wasOn && !isOn) {
758                unblockScreenOn();
759                mWindowManagerPolicy.screenTurnedOff();
760            } else if (!wasOn && isOn) {
761                if (mPowerState.getColorFadeLevel() == 0.0f) {
762                    blockScreenOn();
763                } else {
764                    unblockScreenOn();
765                }
766                mWindowManagerPolicy.screenTurningOn(mPendingScreenOnUnblocker);
767            }
768        }
769        return mPendingScreenOnUnblocker == null;
770    }
771
772    private int clampScreenBrightness(int value) {
773        return MathUtils.constrain(
774                value, mScreenBrightnessRangeMinimum, mScreenBrightnessRangeMaximum);
775    }
776
777    private void animateScreenBrightness(int target, int rate) {
778        if (DEBUG) {
779            Slog.d(TAG, "Animating brightness: target=" + target +", rate=" + rate);
780        }
781        if (mScreenBrightnessRampAnimator.animateTo(target, rate)) {
782            try {
783                mBatteryStats.noteScreenBrightness(target);
784            } catch (RemoteException ex) {
785                // same process
786            }
787        }
788    }
789
790    private void animateScreenStateChange(int target, boolean performScreenOffTransition) {
791        // If there is already an animation in progress, don't interfere with it.
792        if (mColorFadeOnAnimator.isStarted()
793                || mColorFadeOffAnimator.isStarted()) {
794            return;
795        }
796
797        // If we were in the process of turning off the screen but didn't quite
798        // finish.  Then finish up now to prevent a jarring transition back
799        // to screen on if we skipped blocking screen on as usual.
800        if (mPendingScreenOff && target != Display.STATE_OFF) {
801            setScreenState(Display.STATE_OFF);
802            mPendingScreenOff = false;
803        }
804
805        if (target == Display.STATE_ON) {
806            // Want screen on.  The contents of the screen may not yet
807            // be visible if the color fade has not been dismissed because
808            // its last frame of animation is solid black.
809            if (!setScreenState(Display.STATE_ON)) {
810                return; // screen on blocked
811            }
812            if (USE_COLOR_FADE_ON_ANIMATION && mPowerRequest.isBrightOrDim()) {
813                // Perform screen on animation.
814                if (mPowerState.getColorFadeLevel() == 1.0f) {
815                    mPowerState.dismissColorFade();
816                } else if (mPowerState.prepareColorFade(mContext,
817                        mColorFadeFadesConfig ?
818                                ColorFade.MODE_FADE :
819                                        ColorFade.MODE_WARM_UP)) {
820                    mColorFadeOnAnimator.start();
821                } else {
822                    mColorFadeOnAnimator.end();
823                }
824            } else {
825                // Skip screen on animation.
826                mPowerState.setColorFadeLevel(1.0f);
827                mPowerState.dismissColorFade();
828            }
829        } else if (target == Display.STATE_DOZE) {
830            // Want screen dozing.
831            // Wait for brightness animation to complete beforehand when entering doze
832            // from screen on to prevent a perceptible jump because brightness may operate
833            // differently when the display is configured for dozing.
834            if (mScreenBrightnessRampAnimator.isAnimating()
835                    && mPowerState.getScreenState() == Display.STATE_ON) {
836                return;
837            }
838
839            // Set screen state.
840            if (!setScreenState(Display.STATE_DOZE)) {
841                return; // screen on blocked
842            }
843
844            // Dismiss the black surface without fanfare.
845            mPowerState.setColorFadeLevel(1.0f);
846            mPowerState.dismissColorFade();
847        } else if (target == Display.STATE_DOZE_SUSPEND) {
848            // Want screen dozing and suspended.
849            // Wait for brightness animation to complete beforehand unless already
850            // suspended because we may not be able to change it after suspension.
851            if (mScreenBrightnessRampAnimator.isAnimating()
852                    && mPowerState.getScreenState() != Display.STATE_DOZE_SUSPEND) {
853                return;
854            }
855
856            // If not already suspending, temporarily set the state to doze until the
857            // screen on is unblocked, then suspend.
858            if (mPowerState.getScreenState() != Display.STATE_DOZE_SUSPEND) {
859                if (!setScreenState(Display.STATE_DOZE)) {
860                    return; // screen on blocked
861                }
862                setScreenState(Display.STATE_DOZE_SUSPEND); // already on so can't block
863            }
864
865            // Dismiss the black surface without fanfare.
866            mPowerState.setColorFadeLevel(1.0f);
867            mPowerState.dismissColorFade();
868        } else {
869            // Want screen off.
870            mPendingScreenOff = true;
871            if (mPowerState.getColorFadeLevel() == 0.0f) {
872                // Turn the screen off.
873                // A black surface is already hiding the contents of the screen.
874                setScreenState(Display.STATE_OFF);
875                mPendingScreenOff = false;
876            } else if (performScreenOffTransition
877                    && mPowerState.prepareColorFade(mContext,
878                            mColorFadeFadesConfig ?
879                                    ColorFade.MODE_FADE : ColorFade.MODE_COOL_DOWN)
880                    && mPowerState.getScreenState() != Display.STATE_OFF) {
881                // Perform the screen off animation.
882                mColorFadeOffAnimator.start();
883            } else {
884                // Skip the screen off animation and add a black surface to hide the
885                // contents of the screen.
886                mColorFadeOffAnimator.end();
887            }
888        }
889    }
890
891    private final Runnable mCleanListener = new Runnable() {
892        @Override
893        public void run() {
894            sendUpdatePowerState();
895        }
896    };
897
898    private void setProximitySensorEnabled(boolean enable) {
899        if (enable) {
900            if (!mProximitySensorEnabled) {
901                // Register the listener.
902                // Proximity sensor state already cleared initially.
903                mProximitySensorEnabled = true;
904                mSensorManager.registerListener(mProximitySensorListener, mProximitySensor,
905                        SensorManager.SENSOR_DELAY_NORMAL, mHandler);
906            }
907        } else {
908            if (mProximitySensorEnabled) {
909                // Unregister the listener.
910                // Clear the proximity sensor state for next time.
911                mProximitySensorEnabled = false;
912                mProximity = PROXIMITY_UNKNOWN;
913                mPendingProximity = PROXIMITY_UNKNOWN;
914                mHandler.removeMessages(MSG_PROXIMITY_SENSOR_DEBOUNCED);
915                mSensorManager.unregisterListener(mProximitySensorListener);
916                clearPendingProximityDebounceTime(); // release wake lock (must be last)
917            }
918        }
919    }
920
921    private void handleProximitySensorEvent(long time, boolean positive) {
922        if (mProximitySensorEnabled) {
923            if (mPendingProximity == PROXIMITY_NEGATIVE && !positive) {
924                return; // no change
925            }
926            if (mPendingProximity == PROXIMITY_POSITIVE && positive) {
927                return; // no change
928            }
929
930            // Only accept a proximity sensor reading if it remains
931            // stable for the entire debounce delay.  We hold a wake lock while
932            // debouncing the sensor.
933            mHandler.removeMessages(MSG_PROXIMITY_SENSOR_DEBOUNCED);
934            if (positive) {
935                mPendingProximity = PROXIMITY_POSITIVE;
936                setPendingProximityDebounceTime(
937                        time + PROXIMITY_SENSOR_POSITIVE_DEBOUNCE_DELAY); // acquire wake lock
938            } else {
939                mPendingProximity = PROXIMITY_NEGATIVE;
940                setPendingProximityDebounceTime(
941                        time + PROXIMITY_SENSOR_NEGATIVE_DEBOUNCE_DELAY); // acquire wake lock
942            }
943
944            // Debounce the new sensor reading.
945            debounceProximitySensor();
946        }
947    }
948
949    private void debounceProximitySensor() {
950        if (mProximitySensorEnabled
951                && mPendingProximity != PROXIMITY_UNKNOWN
952                && mPendingProximityDebounceTime >= 0) {
953            final long now = SystemClock.uptimeMillis();
954            if (mPendingProximityDebounceTime <= now) {
955                // Sensor reading accepted.  Apply the change then release the wake lock.
956                mProximity = mPendingProximity;
957                updatePowerState();
958                clearPendingProximityDebounceTime(); // release wake lock (must be last)
959            } else {
960                // Need to wait a little longer.
961                // Debounce again later.  We continue holding a wake lock while waiting.
962                Message msg = mHandler.obtainMessage(MSG_PROXIMITY_SENSOR_DEBOUNCED);
963                msg.setAsynchronous(true);
964                mHandler.sendMessageAtTime(msg, mPendingProximityDebounceTime);
965            }
966        }
967    }
968
969    private void clearPendingProximityDebounceTime() {
970        if (mPendingProximityDebounceTime >= 0) {
971            mPendingProximityDebounceTime = -1;
972            mCallbacks.releaseSuspendBlocker(); // release wake lock
973        }
974    }
975
976    private void setPendingProximityDebounceTime(long debounceTime) {
977        if (mPendingProximityDebounceTime < 0) {
978            mCallbacks.acquireSuspendBlocker(); // acquire wake lock
979        }
980        mPendingProximityDebounceTime = debounceTime;
981    }
982
983    private void sendOnStateChangedWithWakelock() {
984        mCallbacks.acquireSuspendBlocker();
985        mHandler.post(mOnStateChangedRunnable);
986    }
987
988    private final Runnable mOnStateChangedRunnable = new Runnable() {
989        @Override
990        public void run() {
991            mCallbacks.onStateChanged();
992            mCallbacks.releaseSuspendBlocker();
993        }
994    };
995
996    private void sendOnProximityPositiveWithWakelock() {
997        mCallbacks.acquireSuspendBlocker();
998        mHandler.post(mOnProximityPositiveRunnable);
999    }
1000
1001    private final Runnable mOnProximityPositiveRunnable = new Runnable() {
1002        @Override
1003        public void run() {
1004            mCallbacks.onProximityPositive();
1005            mCallbacks.releaseSuspendBlocker();
1006        }
1007    };
1008
1009    private void sendOnProximityNegativeWithWakelock() {
1010        mCallbacks.acquireSuspendBlocker();
1011        mHandler.post(mOnProximityNegativeRunnable);
1012    }
1013
1014    private final Runnable mOnProximityNegativeRunnable = new Runnable() {
1015        @Override
1016        public void run() {
1017            mCallbacks.onProximityNegative();
1018            mCallbacks.releaseSuspendBlocker();
1019        }
1020    };
1021
1022    public void dump(final PrintWriter pw) {
1023        synchronized (mLock) {
1024            pw.println();
1025            pw.println("Display Power Controller Locked State:");
1026            pw.println("  mDisplayReadyLocked=" + mDisplayReadyLocked);
1027            pw.println("  mPendingRequestLocked=" + mPendingRequestLocked);
1028            pw.println("  mPendingRequestChangedLocked=" + mPendingRequestChangedLocked);
1029            pw.println("  mPendingWaitForNegativeProximityLocked="
1030                    + mPendingWaitForNegativeProximityLocked);
1031            pw.println("  mPendingUpdatePowerStateLocked=" + mPendingUpdatePowerStateLocked);
1032        }
1033
1034        pw.println();
1035        pw.println("Display Power Controller Configuration:");
1036        pw.println("  mScreenBrightnessDozeConfig=" + mScreenBrightnessDozeConfig);
1037        pw.println("  mScreenBrightnessDimConfig=" + mScreenBrightnessDimConfig);
1038        pw.println("  mScreenBrightnessDarkConfig=" + mScreenBrightnessDarkConfig);
1039        pw.println("  mScreenBrightnessRangeMinimum=" + mScreenBrightnessRangeMinimum);
1040        pw.println("  mScreenBrightnessRangeMaximum=" + mScreenBrightnessRangeMaximum);
1041        pw.println("  mUseSoftwareAutoBrightnessConfig=" + mUseSoftwareAutoBrightnessConfig);
1042        pw.println("  mAllowAutoBrightnessWhileDozingConfig=" +
1043                mAllowAutoBrightnessWhileDozingConfig);
1044        pw.println("  mColorFadeFadesConfig=" + mColorFadeFadesConfig);
1045
1046        mHandler.runWithScissors(new Runnable() {
1047            @Override
1048            public void run() {
1049                dumpLocal(pw);
1050            }
1051        }, 1000);
1052    }
1053
1054    private void dumpLocal(PrintWriter pw) {
1055        pw.println();
1056        pw.println("Display Power Controller Thread State:");
1057        pw.println("  mPowerRequest=" + mPowerRequest);
1058        pw.println("  mWaitingForNegativeProximity=" + mWaitingForNegativeProximity);
1059
1060        pw.println("  mProximitySensor=" + mProximitySensor);
1061        pw.println("  mProximitySensorEnabled=" + mProximitySensorEnabled);
1062        pw.println("  mProximityThreshold=" + mProximityThreshold);
1063        pw.println("  mProximity=" + proximityToString(mProximity));
1064        pw.println("  mPendingProximity=" + proximityToString(mPendingProximity));
1065        pw.println("  mPendingProximityDebounceTime="
1066                + TimeUtils.formatUptime(mPendingProximityDebounceTime));
1067        pw.println("  mScreenOffBecauseOfProximity=" + mScreenOffBecauseOfProximity);
1068        pw.println("  mAppliedAutoBrightness=" + mAppliedAutoBrightness);
1069        pw.println("  mAppliedDimming=" + mAppliedDimming);
1070        pw.println("  mAppliedLowPower=" + mAppliedLowPower);
1071        pw.println("  mPendingScreenOnUnblocker=" + mPendingScreenOnUnblocker);
1072        pw.println("  mPendingScreenOff=" + mPendingScreenOff);
1073
1074        pw.println("  mScreenBrightnessRampAnimator.isAnimating()=" +
1075                mScreenBrightnessRampAnimator.isAnimating());
1076
1077        if (mColorFadeOnAnimator != null) {
1078            pw.println("  mColorFadeOnAnimator.isStarted()=" +
1079                    mColorFadeOnAnimator.isStarted());
1080        }
1081        if (mColorFadeOffAnimator != null) {
1082            pw.println("  mColorFadeOffAnimator.isStarted()=" +
1083                    mColorFadeOffAnimator.isStarted());
1084        }
1085
1086        if (mPowerState != null) {
1087            mPowerState.dump(pw);
1088        }
1089
1090        if (mAutomaticBrightnessController != null) {
1091            mAutomaticBrightnessController.dump(pw);
1092        }
1093
1094    }
1095
1096    private static String proximityToString(int state) {
1097        switch (state) {
1098            case PROXIMITY_UNKNOWN:
1099                return "Unknown";
1100            case PROXIMITY_NEGATIVE:
1101                return "Negative";
1102            case PROXIMITY_POSITIVE:
1103                return "Positive";
1104            default:
1105                return Integer.toString(state);
1106        }
1107    }
1108
1109    private static Spline createAutoBrightnessSpline(int[] lux, int[] brightness) {
1110        try {
1111            final int n = brightness.length;
1112            float[] x = new float[n];
1113            float[] y = new float[n];
1114            y[0] = normalizeAbsoluteBrightness(brightness[0]);
1115            for (int i = 1; i < n; i++) {
1116                x[i] = lux[i - 1];
1117                y[i] = normalizeAbsoluteBrightness(brightness[i]);
1118            }
1119
1120            Spline spline = Spline.createSpline(x, y);
1121            if (DEBUG) {
1122                Slog.d(TAG, "Auto-brightness spline: " + spline);
1123                for (float v = 1f; v < lux[lux.length - 1] * 1.25f; v *= 1.25f) {
1124                    Slog.d(TAG, String.format("  %7.1f: %7.1f", v, spline.interpolate(v)));
1125                }
1126            }
1127            return spline;
1128        } catch (IllegalArgumentException ex) {
1129            Slog.e(TAG, "Could not create auto-brightness spline.", ex);
1130            return null;
1131        }
1132    }
1133
1134    private static float normalizeAbsoluteBrightness(int value) {
1135        return (float)clampAbsoluteBrightness(value) / PowerManager.BRIGHTNESS_ON;
1136    }
1137
1138    private static int clampAbsoluteBrightness(int value) {
1139        return MathUtils.constrain(value, PowerManager.BRIGHTNESS_OFF, PowerManager.BRIGHTNESS_ON);
1140    }
1141
1142    private final class DisplayControllerHandler extends Handler {
1143        public DisplayControllerHandler(Looper looper) {
1144            super(looper, null, true /*async*/);
1145        }
1146
1147        @Override
1148        public void handleMessage(Message msg) {
1149            switch (msg.what) {
1150                case MSG_UPDATE_POWER_STATE:
1151                    updatePowerState();
1152                    break;
1153
1154                case MSG_PROXIMITY_SENSOR_DEBOUNCED:
1155                    debounceProximitySensor();
1156                    break;
1157
1158                case MSG_SCREEN_ON_UNBLOCKED:
1159                    if (mPendingScreenOnUnblocker == msg.obj) {
1160                        unblockScreenOn();
1161                        updatePowerState();
1162                    }
1163                    break;
1164            }
1165        }
1166    }
1167
1168    private final SensorEventListener mProximitySensorListener = new SensorEventListener() {
1169        @Override
1170        public void onSensorChanged(SensorEvent event) {
1171            if (mProximitySensorEnabled) {
1172                final long time = SystemClock.uptimeMillis();
1173                final float distance = event.values[0];
1174                boolean positive = distance >= 0.0f && distance < mProximityThreshold;
1175                handleProximitySensorEvent(time, positive);
1176            }
1177        }
1178
1179        @Override
1180        public void onAccuracyChanged(Sensor sensor, int accuracy) {
1181            // Not used.
1182        }
1183    };
1184
1185    private final class ScreenOnUnblocker implements WindowManagerPolicy.ScreenOnListener {
1186        @Override
1187        public void onScreenOn() {
1188            Message msg = mHandler.obtainMessage(MSG_SCREEN_ON_UNBLOCKED, this);
1189            msg.setAsynchronous(true);
1190            mHandler.sendMessage(msg);
1191        }
1192    }
1193}
1194