Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 27a83db0 authored by Rupesh Bansal's avatar Rupesh Bansal
Browse files

Add DisplayPowerControllerInterface which will be used as a parent class

for new DisplayPowerController variant to incorporate the refactoring of
updatePowerState

We have introduced a new interface, DisplayPowerControllerInterface, and
the existing DisplayPowerController implements this class. In a
subsequent CL, we will introduce a new variant of DisplayPowerController which will have all
the suggested refactoring changes. We are using a sysprop
"persist.sys.use_new_display_power_controller", with default value 0,
to dynamically decide which variant is to be used.

By default, we will be using the existing DisplayPowerController.
Check the existing value
-> adb shell getprop persist.sys.use_new_display_power_controller // 1
means the new variant is being used, otherwise the old variant
Switch to new variant:
-> adb shell setprop persist.sys.use_new_display_power_controller "1" // Switches to the new
variant. Requries reboot after this

Bug: 241776244
Test: Manual
Test: atest DisplayPowerControllerTest
Change-Id: I314c66f4170996efbff24917608736ac33ff7e9c
parent b91f96a9
Loading
Loading
Loading
Loading
+38 −27
Original line number Diff line number Diff line
@@ -200,6 +200,8 @@ public final class DisplayManagerService extends SystemService {
    private static final String FORCE_WIFI_DISPLAY_ENABLE = "persist.debug.wfd.enable";

    private static final String PROP_DEFAULT_DISPLAY_TOP_INSET = "persist.sys.displayinset.top";
    private static final String PROP_USE_NEW_DISPLAY_POWER_CONTROLLER =
            "persist.sys.use_new_display_power_controller";
    private static final long WAIT_FOR_DEFAULT_DISPLAY_TIMEOUT = 10000;
    // This value needs to be in sync with the threshold
    // in RefreshRateConfigs::getFrameRateDivisor.
@@ -274,7 +276,7 @@ public final class DisplayManagerService extends SystemService {
            new CopyOnWriteArrayList<>();

    /** All {@link DisplayPowerController}s indexed by {@link LogicalDisplay} ID. */
    private final SparseArray<DisplayPowerController> mDisplayPowerControllers =
    private final SparseArray<DisplayPowerControllerInterface> mDisplayPowerControllers =
            new SparseArray<>();

    /** {@link DisplayBlanker} used by all {@link DisplayPowerController}s. */
@@ -497,7 +499,6 @@ public final class DisplayManagerService extends SystemService {
        ColorSpace[] colorSpaces = SurfaceControl.getCompositionColorSpaces();
        mWideColorSpace = colorSpaces[1];
        mAllowNonNativeRefreshRateOverride = mInjector.getAllowNonNativeRefreshRateOverride();

        mSystemReady = false;
    }

@@ -577,7 +578,7 @@ public final class DisplayManagerService extends SystemService {
                if (logicalDisplay.getDisplayInfoLocked().type != Display.TYPE_INTERNAL) {
                    return;
                }
                final DisplayPowerController dpc = mDisplayPowerControllers.get(
                final DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(
                        logicalDisplay.getDisplayIdLocked());
                if (dpc == null) {
                    return;
@@ -1557,7 +1558,7 @@ public final class DisplayManagerService extends SystemService {
        scheduleTraversalLocked(false);
        mPersistentDataStore.saveIfNeeded();

        DisplayPowerController dpc = mDisplayPowerControllers.get(displayId);
        DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(displayId);
        if (dpc != null) {
            dpc.onDisplayChanged();
        }
@@ -1575,7 +1576,8 @@ public final class DisplayManagerService extends SystemService {

    private void handleLogicalDisplayRemovedLocked(@NonNull LogicalDisplay display) {
        final int displayId = display.getDisplayIdLocked();
        final DisplayPowerController dpc = mDisplayPowerControllers.removeReturnOld(displayId);
        final DisplayPowerControllerInterface dpc =
                mDisplayPowerControllers.removeReturnOld(displayId);
        if (dpc != null) {
            dpc.stop();
        }
@@ -1604,7 +1606,7 @@ public final class DisplayManagerService extends SystemService {
            mHandler.post(work);
        }
        final int displayId = display.getDisplayIdLocked();
        DisplayPowerController dpc = mDisplayPowerControllers.get(displayId);
        DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(displayId);
        if (dpc != null) {
            dpc.onDisplayChanged();
        }
@@ -1615,7 +1617,7 @@ public final class DisplayManagerService extends SystemService {

    private void handleLogicalDisplayDeviceStateTransitionLocked(@NonNull LogicalDisplay display) {
        final int displayId = display.getDisplayIdLocked();
        final DisplayPowerController dpc = mDisplayPowerControllers.get(displayId);
        final DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(displayId);
        if (dpc != null) {
            dpc.onDeviceStateTransition();
        }
@@ -1852,14 +1854,14 @@ public final class DisplayManagerService extends SystemService {
            if (userId != mCurrentUserId) {
                return;
            }
            DisplayPowerController dpc = getDpcFromUniqueIdLocked(uniqueId);
            DisplayPowerControllerInterface dpc = getDpcFromUniqueIdLocked(uniqueId);
            if (dpc != null) {
                dpc.setBrightnessConfiguration(c);
            }
        }
    }

    private DisplayPowerController getDpcFromUniqueIdLocked(String uniqueId) {
    private DisplayPowerControllerInterface getDpcFromUniqueIdLocked(String uniqueId) {
        final DisplayDevice displayDevice = mDisplayDeviceRepo.getByUniqueIdLocked(uniqueId);
        final LogicalDisplay logicalDisplay = mLogicalDisplayMapper.getDisplayLocked(displayDevice);
        if (logicalDisplay != null) {
@@ -1900,7 +1902,7 @@ public final class DisplayManagerService extends SystemService {
                final BrightnessConfiguration config =
                        getBrightnessConfigForDisplayWithPdsFallbackLocked(uniqueId, userSerial);
                if (config != null) {
                    final DisplayPowerController dpc = mDisplayPowerControllers.get(
                    final DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(
                            logicalDisplay.getDisplayIdLocked());
                    if (dpc != null) {
                        dpc.setBrightnessConfiguration(config);
@@ -2132,8 +2134,8 @@ public final class DisplayManagerService extends SystemService {

    void setAutoBrightnessLoggingEnabled(boolean enabled) {
        synchronized (mSyncRoot) {
            final DisplayPowerController displayPowerController = mDisplayPowerControllers.get(
                    Display.DEFAULT_DISPLAY);
            final DisplayPowerControllerInterface displayPowerController =
                    mDisplayPowerControllers.get(Display.DEFAULT_DISPLAY);
            if (displayPowerController != null) {
                displayPowerController.setAutoBrightnessLoggingEnabled(enabled);
            }
@@ -2142,8 +2144,8 @@ public final class DisplayManagerService extends SystemService {

    void setDisplayWhiteBalanceLoggingEnabled(boolean enabled) {
        synchronized (mSyncRoot) {
            final DisplayPowerController displayPowerController = mDisplayPowerControllers.get(
                    Display.DEFAULT_DISPLAY);
            final DisplayPowerControllerInterface displayPowerController =
                    mDisplayPowerControllers.get(Display.DEFAULT_DISPLAY);
            if (displayPowerController != null) {
                displayPowerController.setDisplayWhiteBalanceLoggingEnabled(enabled);
            }
@@ -2170,8 +2172,8 @@ public final class DisplayManagerService extends SystemService {

    void setAmbientColorTemperatureOverride(float cct) {
        synchronized (mSyncRoot) {
            final DisplayPowerController displayPowerController = mDisplayPowerControllers.get(
                    Display.DEFAULT_DISPLAY);
            final DisplayPowerControllerInterface displayPowerController =
                    mDisplayPowerControllers.get(Display.DEFAULT_DISPLAY);
            if (displayPowerController != null) {
                displayPowerController.setAmbientColorTemperatureOverride(cct);
            }
@@ -2180,8 +2182,8 @@ public final class DisplayManagerService extends SystemService {

    void setDockedAndIdleEnabled(boolean enabled, int displayId) {
        synchronized (mSyncRoot) {
            final DisplayPowerController displayPowerController = mDisplayPowerControllers.get(
                    displayId);
            final DisplayPowerControllerInterface displayPowerController =
                    mDisplayPowerControllers.get(displayId);
            if (displayPowerController != null) {
                displayPowerController.setAutomaticScreenBrightnessMode(enabled);
            }
@@ -2554,10 +2556,19 @@ public final class DisplayManagerService extends SystemService {

        final BrightnessSetting brightnessSetting = new BrightnessSetting(mPersistentDataStore,
                display, mSyncRoot);
        final DisplayPowerController displayPowerController = new DisplayPowerController(
        final DisplayPowerController displayPowerController;

        if (SystemProperties.getInt(PROP_USE_NEW_DISPLAY_POWER_CONTROLLER, 0) == 1) {
            displayPowerController = new DisplayPowerController(
                    mContext, /* injector= */ null, mDisplayPowerCallbacks, mPowerHandler,
                    mSensorManager, mDisplayBlanker, display, mBrightnessTracker, brightnessSetting,
                    () -> handleBrightnessChange(display));
        } else {
            displayPowerController = new DisplayPowerController(
                    mContext, /* injector= */ null, mDisplayPowerCallbacks, mPowerHandler,
                    mSensorManager, mDisplayBlanker, display, mBrightnessTracker, brightnessSetting,
                    () -> handleBrightnessChange(display));
        }
        mDisplayPowerControllers.append(display.getDisplayIdLocked(), displayPowerController);
    }

@@ -3212,7 +3223,7 @@ public final class DisplayManagerService extends SystemService {
                                    uniqueId, userSerial);
                    if (config == null) {
                        // Get default configuration
                        DisplayPowerController dpc = getDpcFromUniqueIdLocked(uniqueId);
                        DisplayPowerControllerInterface dpc = getDpcFromUniqueIdLocked(uniqueId);
                        if (dpc != null) {
                            config = dpc.getDefaultBrightnessConfiguration();
                        }
@@ -3263,7 +3274,7 @@ public final class DisplayManagerService extends SystemService {
            final long token = Binder.clearCallingIdentity();
            try {
                synchronized (mSyncRoot) {
                    DisplayPowerController dpc = mDisplayPowerControllers.get(displayId);
                    DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(displayId);
                    if (dpc != null) {
                        return dpc.getBrightnessInfo();
                    }
@@ -3310,7 +3321,7 @@ public final class DisplayManagerService extends SystemService {
            final long token = Binder.clearCallingIdentity();
            try {
                synchronized (mSyncRoot) {
                    DisplayPowerController dpc = mDisplayPowerControllers.get(displayId);
                    DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(displayId);
                    if (dpc != null) {
                        dpc.setBrightness(brightness);
                    }
@@ -3330,7 +3341,7 @@ public final class DisplayManagerService extends SystemService {
            final long token = Binder.clearCallingIdentity();
            try {
                synchronized (mSyncRoot) {
                    DisplayPowerController dpc = mDisplayPowerControllers.get(displayId);
                    DisplayPowerControllerInterface dpc = mDisplayPowerControllers.get(displayId);
                    if (dpc != null) {
                        brightness = dpc.getScreenBrightnessSetting();
                    }
@@ -3534,7 +3545,7 @@ public final class DisplayManagerService extends SystemService {
                            id).getPrimaryDisplayDeviceLocked();
                    final int flags = displayDevice.getDisplayDeviceInfoLocked().flags;
                    if ((flags & DisplayDeviceInfo.FLAG_NEVER_BLANK) == 0) {
                        final DisplayPowerController displayPowerController =
                        final DisplayPowerControllerInterface displayPowerController =
                                mDisplayPowerControllers.get(id);
                        ready &= displayPowerController.requestPowerState(request,
                                waitForNegativeProximity);
+27 −6
Original line number Diff line number Diff line
@@ -104,7 +104,7 @@ import java.io.PrintWriter;
 * slower by changing the "animator duration scale" option in Development Settings.
 */
final class DisplayPowerController implements AutomaticBrightnessController.Callbacks,
        DisplayWhiteBalanceController.Callbacks {
        DisplayWhiteBalanceController.Callbacks, DisplayPowerControllerInterface {
    private static final String SCREEN_ON_BLOCKED_TRACE_NAME = "Screen on blocked";
    private static final String SCREEN_OFF_BLOCKED_TRACE_NAME = "Screen off blocked";

@@ -682,6 +682,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
    /**
     * Returns true if the proximity sensor screen-off function is available.
     */
    @Override
    public boolean isProximitySensorAvailable() {
        return mProximitySensor != null;
    }
@@ -693,6 +694,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
     * @param includePackage if false will null out the package name in events
     */
    @Nullable
    @Override
    public ParceledListSlice<BrightnessChangeEvent> getBrightnessEvents(
            @UserIdInt int userId, boolean includePackage) {
        if (mBrightnessTracker == null) {
@@ -701,6 +703,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        return mBrightnessTracker.getEvents(userId, includePackage);
    }

    @Override
    public void onSwitchUser(@UserIdInt int newUserId) {
        handleSettingsChange(true /* userSwitch */);
        if (mBrightnessTracker != null) {
@@ -709,6 +712,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
    }

    @Nullable
    @Override
    public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats(
            @UserIdInt int userId) {
        if (mBrightnessTracker == null) {
@@ -720,6 +724,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
    /**
     * Persist the brightness slider events and ambient brightness stats to disk.
     */
    @Override
    public void persistBrightnessTrackerState() {
        if (mBrightnessTracker != null) {
            mBrightnessTracker.persistBrightnessTrackerState();
@@ -781,6 +786,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        }
    }

    @Override
    public BrightnessConfiguration getDefaultBrightnessConfiguration() {
        if (mAutomaticBrightnessController == null) {
            return null;
@@ -794,6 +800,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
     * of each display need to be properly reflected in AutomaticBrightnessController.
     */
    @GuardedBy("DisplayManagerService.mSyncRoot")
    @Override
    public void onDisplayChanged() {
        final DisplayDevice device = mLogicalDisplay.getPrimaryDisplayDeviceLocked();
        if (device == null) {
@@ -823,6 +830,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
     * This process involves turning off some displays so we need updatePowerState() to run and
     * calculate the new state.
     */
    @Override
    public void onDeviceStateTransition() {
        sendUpdatePowerState();
    }
@@ -833,6 +841,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
     * This method should be called when the DisplayPowerController is no longer in use; i.e. when
     * the {@link #mDisplayId display} has been removed.
     */
    @Override
    public void stop() {
        synchronized (mLock) {
            mStopped = true;
@@ -1063,6 +1072,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        }
    }

    @Override
    public void setAutomaticScreenBrightnessMode(boolean isIdle) {
        if (mAutomaticBrightnessController != null) {
            if (isIdle) {
@@ -1766,27 +1776,32 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
     * Ignores the proximity sensor until the sensor state changes, but only if the sensor is
     * currently enabled and forcing the screen to be dark.
     */
    @Override
    public void ignoreProximitySensorUntilChanged() {
        mHandler.sendEmptyMessage(MSG_IGNORE_PROXIMITY);
    }

    @Override
    public void setBrightnessConfiguration(BrightnessConfiguration c) {
        Message msg = mHandler.obtainMessage(MSG_CONFIGURE_BRIGHTNESS, c);
        msg.sendToTarget();
    }

    @Override
    public void setTemporaryBrightness(float brightness) {
        Message msg = mHandler.obtainMessage(MSG_SET_TEMPORARY_BRIGHTNESS,
                Float.floatToIntBits(brightness), 0 /*unused*/);
        msg.sendToTarget();
    }

    @Override
    public void setTemporaryAutoBrightnessAdjustment(float adjustment) {
        Message msg = mHandler.obtainMessage(MSG_SET_TEMPORARY_AUTO_BRIGHTNESS_ADJUSTMENT,
                Float.floatToIntBits(adjustment), 0 /*unused*/);
        msg.sendToTarget();
    }

    @Override
    public BrightnessInfo getBrightnessInfo() {
        synchronized (mCachedBrightnessInfo) {
            return new BrightnessInfo(
@@ -2347,7 +2362,8 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        return Float.isNaN(adj) ? 0.0f : clampAutoBrightnessAdjustment(adj);
    }

    float getScreenBrightnessSetting() {
    @Override
    public float getScreenBrightnessSetting() {
        float brightness = mBrightnessSetting.getBrightness();
        if (Float.isNaN(brightness)) {
            brightness = mScreenBrightnessDefault;
@@ -2362,7 +2378,8 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        return clampScreenBrightnessForVr(brightnessFloat);
    }

    void setBrightness(float brightnessValue) {
    @Override
    public void setBrightness(float brightnessValue) {
        // Update the setting, which will eventually call back into DPC to have us actually update
        // the display with the new value.
        mBrightnessSetting.setBrightness(brightnessValue);
@@ -2511,6 +2528,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        }
    };

    @Override
    public void dump(final PrintWriter pw) {
        synchronized (mLock) {
            pw.println();
@@ -2919,7 +2937,8 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        }
    }

    void setAutoBrightnessLoggingEnabled(boolean enabled) {
    @Override
    public void setAutoBrightnessLoggingEnabled(boolean enabled) {
        if (mAutomaticBrightnessController != null) {
            mAutomaticBrightnessController.setLoggingEnabled(enabled);
        }
@@ -2930,14 +2949,16 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
        sendUpdatePowerState();
    }

    void setDisplayWhiteBalanceLoggingEnabled(boolean enabled) {
    @Override
    public void setDisplayWhiteBalanceLoggingEnabled(boolean enabled) {
        if (mDisplayWhiteBalanceController != null) {
            mDisplayWhiteBalanceController.setLoggingEnabled(enabled);
            mDisplayWhiteBalanceSettings.setLoggingEnabled(enabled);
        }
    }

    void setAmbientColorTemperatureOverride(float cct) {
    @Override
    public void setAmbientColorTemperatureOverride(float cct) {
        if (mDisplayWhiteBalanceController != null) {
            mDisplayWhiteBalanceController.setAmbientColorTemperatureOverride(cct);
            // The ambient color temperature override is only applied when the ambient color
+164 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.server.display;

import android.content.pm.ParceledListSlice;
import android.hardware.display.AmbientBrightnessDayStats;
import android.hardware.display.BrightnessChangeEvent;
import android.hardware.display.BrightnessConfiguration;
import android.hardware.display.BrightnessInfo;
import android.hardware.display.DisplayManagerInternal;

import java.io.PrintWriter;

/**
 * An interface to manage the display's power state and brightness
 */
public interface DisplayPowerControllerInterface {

    /**
     * Notified when the display is changed. We use this to apply any changes that might be needed
     * when displays get swapped on foldable devices.
     */
    void onDisplayChanged();

    /**
     * Unregisters all listeners and interrupts all running threads; halting future work.
     *
     * This method should be called when the DisplayPowerController is no longer in use; i.e. when
     * the display has been removed.
     */
    void stop();

    /**
     * Used to manage the displays preparing to transition from one device state to another.
     */
    void onDeviceStateTransition();

    /**
     * Used to update the display's BrightnessConfiguration
     * @param config The new BrightnessConfiguration
     */
    void setBrightnessConfiguration(BrightnessConfiguration config);

    /**
     * Used to set the ambient color temperature of the Display
     * @param ambientColorTemperature The target ambientColorTemperature
     */
    void setAmbientColorTemperatureOverride(float ambientColorTemperature);

    /**
     * Used to decide the associated AutomaticBrightnessController's BrightnessMode
     * @param isIdle Flag which represents if the Idle BrightnessMode is to be set
     */
    void setAutomaticScreenBrightnessMode(boolean isIdle);

    /**
     * Used to enable/disable the logging of the WhileBalance associated entities
     * @param enabled Flag which represents if the logging is the be enabled
     */
    void setDisplayWhiteBalanceLoggingEnabled(boolean enabled);

    /**
     * Used to dump the state.
     * @param writer The PrintWriter used to dump the state.
     */
    void dump(PrintWriter writer);

    /**
     * Used to get the ambient brightness stats
     */
    ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats(int userId);

    /**
     * Get the default brightness configuration
     */
    BrightnessConfiguration getDefaultBrightnessConfiguration();

    /**
     * Set the screen brightness of the associated display
     * @param brightness The value to which the brightness is to be set
     */
    void setBrightness(float brightness);

    /**
     * Checks if the proximity sensor is available
     */
    boolean isProximitySensorAvailable();

    /**
     * Persist the brightness slider events and ambient brightness stats to disk.
     */
    void persistBrightnessTrackerState();

    /**
     * Ignores the proximity sensor until the sensor state changes, but only if the sensor is
     * currently enabled and forcing the screen to be dark.
     */
    void ignoreProximitySensorUntilChanged();

    /**
     * Requests a new power state.
     *
     * @param request The requested power state.
     * @param waitForNegativeProximity If true, issues a request to wait for
     * negative proximity before turning the screen back on,
     * assuming the screen was turned off by the proximity sensor.
     * @return True if display is ready, false if there are important changes that must
     * be made asynchronously.
     */
    boolean requestPowerState(DisplayManagerInternal.DisplayPowerRequest request,
            boolean waitForNegativeProximity);

    /**
     * Sets up the temporary autobrightness adjustment when the user is yet to settle down to a
     * value.
     */
    void setTemporaryAutoBrightnessAdjustment(float adjustment);

    /**
     * Gets the screen brightness setting
     */
    float getScreenBrightnessSetting();

    /**
     * Sets up the temporary brightness for the associated display
     */
    void setTemporaryBrightness(float brightness);

    /**
     * Gets the associated {@link BrightnessInfo}
     */
    BrightnessInfo getBrightnessInfo();

    /**
     * Get the {@link BrightnessChangeEvent}s for the specified user.
     */
    ParceledListSlice<BrightnessChangeEvent> getBrightnessEvents(int userId, boolean hasUsageStats);

    /**
     * Sets up the logging for the associated {@link AutomaticBrightnessController}
     * @param enabled Flag to represent if the logging is to be enabled
     */
    void setAutoBrightnessLoggingEnabled(boolean enabled);

    /**
     * Handles the changes to be done to update the brightness when the user is changed
     * @param newUserId The new userId
     */
    void onSwitchUser(int newUserId);
}