Merge "Remove SoundTriggerInternal dump" into udc-dev
diff --git a/core/java/android/app/admin/LockTaskPolicy.java b/core/java/android/app/admin/LockTaskPolicy.java
index f5d1cb4..b671d57 100644
--- a/core/java/android/app/admin/LockTaskPolicy.java
+++ b/core/java/android/app/admin/LockTaskPolicy.java
@@ -38,6 +38,7 @@
     /**
      * @hide
      */
+    // We default on the power button menu, in order to be consistent with pre-P behaviour
     public static final int DEFAULT_LOCK_TASK_FLAG =
             DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
 
@@ -72,18 +73,28 @@
     /**
      * @hide
      */
-    public LockTaskPolicy(@NonNull Set<String> packages) {
-        Objects.requireNonNull(packages);
-        mPackages.addAll(packages);
+    public LockTaskPolicy(@Nullable Set<String> packages) {
+        if (packages != null) {
+            mPackages.addAll(packages);
+        }
         setValue(this);
     }
 
     /**
      * @hide
      */
-    public LockTaskPolicy(@NonNull Set<String> packages, int flags) {
-        Objects.requireNonNull(packages);
-        mPackages = new HashSet<>(packages);
+    public LockTaskPolicy(int flags) {
+        mFlags = flags;
+        setValue(this);
+    }
+
+    /**
+     * @hide
+     */
+    public LockTaskPolicy(@Nullable Set<String> packages, int flags) {
+        if (packages != null) {
+            mPackages.addAll(packages);
+        }
         mFlags = flags;
         setValue(this);
     }
diff --git a/core/java/android/inputmethodservice/IInputMethodWrapper.java b/core/java/android/inputmethodservice/IInputMethodWrapper.java
index ed6a88f..70b72c8 100644
--- a/core/java/android/inputmethodservice/IInputMethodWrapper.java
+++ b/core/java/android/inputmethodservice/IInputMethodWrapper.java
@@ -304,7 +304,9 @@
                 return;
             }
             case DO_SET_STYLUS_WINDOW_IDLE_TIMEOUT: {
-                inputMethod.setStylusWindowIdleTimeoutForTest((long) msg.obj);
+                if (isValid(inputMethod, target, "DO_SET_STYLUS_WINDOW_IDLE_TIMEOUT")) {
+                    inputMethod.setStylusWindowIdleTimeoutForTest((long) msg.obj);
+                }
                 return;
             }
         }
diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java
index 7383e63..9f9c222 100755
--- a/core/java/android/os/Build.java
+++ b/core/java/android/os/Build.java
@@ -493,7 +493,7 @@
          * @hide
          */
         @TestApi
-        public static final int RESOURCES_SDK_INT = SDK_INT;
+        public static final int RESOURCES_SDK_INT = SDK_INT + ACTIVE_CODENAMES.length;
 
         /**
          * The current lowest supported value of app target SDK. Applications targeting
diff --git a/core/java/android/view/DisplayInfo.java b/core/java/android/view/DisplayInfo.java
index e31adcf..f2373fb 100644
--- a/core/java/android/view/DisplayInfo.java
+++ b/core/java/android/view/DisplayInfo.java
@@ -341,6 +341,9 @@
     @Nullable
     public DisplayShape displayShape;
 
+    /**
+     * Refresh rate range limitation based on the current device layout
+     */
     @Nullable
     public SurfaceControl.RefreshRateRange layoutLimitedRefreshRate;
 
@@ -354,7 +357,7 @@
      * RefreshRateRange limitation for @Temperature.ThrottlingStatus
      */
     @NonNull
-    public SparseArray<SurfaceControl.RefreshRateRange> refreshRateThermalThrottling =
+    public SparseArray<SurfaceControl.RefreshRateRange> thermalRefreshRateThrottling =
             new SparseArray<>();
 
     public static final @android.annotation.NonNull Creator<DisplayInfo> CREATOR = new Creator<DisplayInfo>() {
@@ -434,7 +437,7 @@
                 && Objects.equals(displayShape, other.displayShape)
                 && Objects.equals(layoutLimitedRefreshRate, other.layoutLimitedRefreshRate)
                 && BrightnessSynchronizer.floatEquals(hdrSdrRatio, other.hdrSdrRatio)
-                && refreshRateThermalThrottling.contentEquals(other.refreshRateThermalThrottling);
+                && thermalRefreshRateThrottling.contentEquals(other.thermalRefreshRateThrottling);
     }
 
     @Override
@@ -491,7 +494,7 @@
         displayShape = other.displayShape;
         layoutLimitedRefreshRate = other.layoutLimitedRefreshRate;
         hdrSdrRatio = other.hdrSdrRatio;
-        refreshRateThermalThrottling = other.refreshRateThermalThrottling;
+        thermalRefreshRateThrottling = other.thermalRefreshRateThrottling;
     }
 
     public void readFromParcel(Parcel source) {
@@ -554,7 +557,7 @@
         displayShape = source.readTypedObject(DisplayShape.CREATOR);
         layoutLimitedRefreshRate = source.readTypedObject(SurfaceControl.RefreshRateRange.CREATOR);
         hdrSdrRatio = source.readFloat();
-        refreshRateThermalThrottling = source.readSparseArray(null,
+        thermalRefreshRateThrottling = source.readSparseArray(null,
                 SurfaceControl.RefreshRateRange.class);
     }
 
@@ -616,7 +619,7 @@
         dest.writeTypedObject(displayShape, flags);
         dest.writeTypedObject(layoutLimitedRefreshRate, flags);
         dest.writeFloat(hdrSdrRatio);
-        dest.writeSparseArray(refreshRateThermalThrottling);
+        dest.writeSparseArray(thermalRefreshRateThrottling);
     }
 
     @Override
@@ -884,8 +887,8 @@
         } else {
             sb.append(hdrSdrRatio);
         }
-        sb.append(", refreshRateThermalThrottling ");
-        sb.append(refreshRateThermalThrottling);
+        sb.append(", thermalRefreshRateThrottling ");
+        sb.append(thermalRefreshRateThrottling);
         sb.append("}");
         return sb.toString();
     }
diff --git a/media/java/android/media/tv/ITvInputSessionWrapper.java b/media/java/android/media/tv/ITvInputSessionWrapper.java
index 80a3e70..d749b91 100644
--- a/media/java/android/media/tv/ITvInputSessionWrapper.java
+++ b/media/java/android/media/tv/ITvInputSessionWrapper.java
@@ -223,7 +223,8 @@
                 break;
             }
             case DO_TIME_SHIFT_SET_MODE: {
-                mTvInputSessionImpl.timeShiftSetMode((Integer) msg.obj);
+                mTvInputSessionImpl.timeShiftSetMode(msg.arg1);
+                break;
             }
             case DO_TIME_SHIFT_ENABLE_POSITION_TRACKING: {
                 mTvInputSessionImpl.timeShiftEnablePositionTracking((Boolean) msg.obj);
diff --git a/packages/SettingsLib/Spa/build.gradle b/packages/SettingsLib/Spa/build.gradle
index 4fd2b5d..e68ef85 100644
--- a/packages/SettingsLib/Spa/build.gradle
+++ b/packages/SettingsLib/Spa/build.gradle
@@ -14,17 +14,27 @@
  * limitations under the License.
  */
 
+import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
+
 buildscript {
     ext {
         BUILD_TOOLS_VERSION = "30.0.3"
         MIN_SDK = 21
         TARGET_SDK = 33
         jetpack_compose_version = '1.4.0-beta01'
-        jetpack_compose_compiler_version = '1.4.0'
+        jetpack_compose_compiler_version = '1.4.4'
     }
 }
 plugins {
-    id 'com.android.application' version '8.0.0-beta05' apply false
-    id 'com.android.library' version '8.0.0-beta05' apply false
-    id 'org.jetbrains.kotlin.android' version '1.8.0' apply false
+    id 'com.android.application' version '8.0.0' apply false
+    id 'com.android.library' version '8.0.0' apply false
+    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
+}
+subprojects {
+    tasks.withType(KotlinCompile).configureEach {
+        kotlinOptions {
+            jvmTarget = "17"
+            freeCompilerArgs = ["-Xjvm-default=all"]
+        }
+    }
 }
diff --git a/packages/SettingsLib/Spa/gallery/build.gradle b/packages/SettingsLib/Spa/gallery/build.gradle
index 416a403..212aa7b 100644
--- a/packages/SettingsLib/Spa/gallery/build.gradle
+++ b/packages/SettingsLib/Spa/gallery/build.gradle
@@ -42,12 +42,8 @@
         }
     }
     compileOptions {
-        sourceCompatibility JavaVersion.VERSION_11
-        targetCompatibility JavaVersion.VERSION_11
-    }
-    kotlinOptions {
-        jvmTarget = '11'
-        freeCompilerArgs = ["-Xjvm-default=all"]
+        sourceCompatibility JavaVersion.VERSION_17
+        targetCompatibility JavaVersion.VERSION_17
     }
     buildFeatures {
         compose true
diff --git a/packages/SettingsLib/Spa/spa/build.gradle b/packages/SettingsLib/Spa/spa/build.gradle
index 9962c93..fb945a3 100644
--- a/packages/SettingsLib/Spa/spa/build.gradle
+++ b/packages/SettingsLib/Spa/spa/build.gradle
@@ -51,10 +51,6 @@
         sourceCompatibility JavaVersion.VERSION_17
         targetCompatibility JavaVersion.VERSION_17
     }
-    kotlinOptions {
-        jvmTarget = '17'
-        freeCompilerArgs = ["-Xjvm-default=all"]
-    }
     buildFeatures {
         compose true
     }
@@ -79,7 +75,7 @@
     api "androidx.compose.ui:ui-tooling-preview:$jetpack_compose_version"
     api "androidx.lifecycle:lifecycle-livedata-ktx"
     api "androidx.lifecycle:lifecycle-runtime-compose"
-    api "androidx.navigation:navigation-compose:2.6.0-alpha07"
+    api "androidx.navigation:navigation-compose:2.6.0-alpha08"
     api "com.github.PhilJay:MPAndroidChart:v3.1.0-alpha"
     api "com.google.android.material:material:1.7.0-alpha03"
     debugApi "androidx.compose.ui:ui-tooling:$jetpack_compose_version"
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Spinner.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Spinner.kt
index f0df9a6..8cbf7cc 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Spinner.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Spinner.kt
@@ -19,7 +19,6 @@
 import androidx.compose.foundation.background
 import androidx.compose.foundation.layout.Box
 import androidx.compose.foundation.layout.PaddingValues
-import androidx.compose.foundation.layout.height
 import androidx.compose.foundation.layout.padding
 import androidx.compose.foundation.selection.selectableGroup
 import androidx.compose.material.icons.Icons
@@ -40,7 +39,6 @@
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.graphics.Color
 import androidx.compose.ui.tooling.preview.Preview
-import androidx.compose.ui.unit.DpOffset
 import androidx.compose.ui.unit.dp
 import com.android.settingslib.spa.framework.theme.SettingsDimension
 import com.android.settingslib.spa.framework.theme.SettingsTheme
@@ -60,13 +58,17 @@
 
     Box(
         modifier = Modifier
-            .padding(SettingsDimension.itemPadding)
+            .padding(
+                start = SettingsDimension.itemPaddingStart,
+                top = SettingsDimension.itemPaddingAround,
+                end = SettingsDimension.itemPaddingEnd,
+                bottom = SettingsDimension.itemPaddingAround,
+            )
             .selectableGroup(),
     ) {
         val contentPadding = PaddingValues(horizontal = SettingsDimension.itemPaddingEnd)
         Button(
             onClick = { expanded = true },
-            modifier = Modifier.height(36.dp),
             colors = ButtonDefaults.buttonColors(
                 containerColor = SettingsTheme.colorScheme.spinnerHeaderContainer,
                 contentColor = SettingsTheme.colorScheme.onSpinnerHeaderContainer,
@@ -86,7 +88,6 @@
             expanded = expanded,
             onDismissRequest = { expanded = false },
             modifier = Modifier.background(SettingsTheme.colorScheme.spinnerItemContainer),
-            offset = DpOffset(x = 0.dp, y = 4.dp),
         ) {
             for (option in options) {
                 DropdownMenuItem(
@@ -116,7 +117,9 @@
 ) {
     Text(
         text = option?.text ?: "",
-        modifier = modifier.padding(end = SettingsDimension.itemPaddingEnd),
+        modifier = modifier
+            .padding(end = SettingsDimension.itemPaddingEnd)
+            .padding(vertical = SettingsDimension.itemPaddingAround),
         color = color,
         style = MaterialTheme.typography.labelLarge,
     )
diff --git a/packages/SettingsLib/Spa/testutils/build.gradle b/packages/SettingsLib/Spa/testutils/build.gradle
index e7f7db2..23a9add 100644
--- a/packages/SettingsLib/Spa/testutils/build.gradle
+++ b/packages/SettingsLib/Spa/testutils/build.gradle
@@ -41,10 +41,6 @@
         sourceCompatibility JavaVersion.VERSION_17
         targetCompatibility JavaVersion.VERSION_17
     }
-    kotlinOptions {
-        jvmTarget = '17'
-        freeCompilerArgs = ["-Xjvm-default=all"]
-    }
     buildFeatures {
         compose true
     }
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java
index 0f370ac..b141db1 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java
+++ b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java
@@ -199,7 +199,8 @@
                     if (mShouldShowComplications) {
                         return (requiredTypes & getAvailableComplicationTypes()) == requiredTypes;
                     }
-                    return (requiredTypes & mSupportedTypes) == requiredTypes;
+                    final int typesToAlwaysShow = mSupportedTypes & getAvailableComplicationTypes();
+                    return (requiredTypes & typesToAlwaysShow) == requiredTypes;
                 })
                 .collect(Collectors.toCollection(HashSet::new))
                 : mComplications);
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewController.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewController.java
index d3fe2c5..8c0cfba 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewController.java
@@ -23,6 +23,7 @@
 import android.text.TextUtils;
 
 import androidx.annotation.IntDef;
+import androidx.annotation.VisibleForTesting;
 
 import com.android.keyguard.logging.KeyguardLogger;
 import com.android.systemui.Dumpable;
@@ -74,7 +75,9 @@
 
     // Executor that will show the next message after a delay
     private final DelayableExecutor mExecutor;
-    @Nullable private ShowNextIndication mShowNextIndicationRunnable;
+
+    @VisibleForTesting
+    @Nullable ShowNextIndication mShowNextIndicationRunnable;
 
     // List of indication types to show. The next indication to show is always at index 0
     private final List<Integer> mIndicationQueue = new ArrayList<>();
@@ -111,6 +114,12 @@
         cancelScheduledIndication();
     }
 
+    /** Destroy ViewController, removing any listeners. */
+    public void destroy() {
+        super.destroy();
+        onViewDetached();
+    }
+
     /**
      * Update the indication type with the given String.
      * @param type of indication
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java b/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java
index 09cc2c5..cce708e 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java
@@ -120,6 +120,7 @@
     private final QSLogger mLogger;
     private final FooterActionsController mFooterActionsController;
     private final FooterActionsViewModel.Factory mFooterActionsViewModelFactory;
+    private final FooterActionsViewBinder mFooterActionsViewBinder;
     private final ListeningAndVisibilityLifecycleOwner mListeningAndVisibilityLifecycleOwner;
     private boolean mShowCollapsedOnKeyguard;
     private boolean mLastKeyguardAndExpanded;
@@ -177,6 +178,7 @@
             DumpManager dumpManager, QSLogger qsLogger,
             FooterActionsController footerActionsController,
             FooterActionsViewModel.Factory footerActionsViewModelFactory,
+            FooterActionsViewBinder footerActionsViewBinder,
             LargeScreenShadeInterpolator largeScreenShadeInterpolator,
             FeatureFlags featureFlags) {
         mRemoteInputQuickSettingsDisabler = remoteInputQsDisabler;
@@ -193,6 +195,7 @@
         mDumpManager = dumpManager;
         mFooterActionsController = footerActionsController;
         mFooterActionsViewModelFactory = footerActionsViewModelFactory;
+        mFooterActionsViewBinder = footerActionsViewBinder;
         mListeningAndVisibilityLifecycleOwner = new ListeningAndVisibilityLifecycleOwner();
     }
 
@@ -285,7 +288,7 @@
 
         if (!ComposeFacade.INSTANCE.isComposeAvailable()) {
             Log.d(TAG, "Binding the View implementation of the QS footer actions");
-            FooterActionsViewBinder.bind(footerActionsView, mQSFooterActionsViewModel,
+            mFooterActionsViewBinder.bind(footerActionsView, mQSFooterActionsViewModel,
                     mListeningAndVisibilityLifecycleOwner);
             return;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt b/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt
index 1921586..9c9ad33 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt
@@ -33,27 +33,27 @@
 import com.android.systemui.R
 import com.android.systemui.animation.Expandable
 import com.android.systemui.common.ui.binder.IconViewBinder
+import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.lifecycle.repeatWhenAttached
 import com.android.systemui.people.ui.view.PeopleViewBinder.bind
 import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsButtonViewModel
 import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsForegroundServicesButtonViewModel
 import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsSecurityButtonViewModel
 import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsViewModel
+import javax.inject.Inject
 import kotlin.math.roundToInt
-import kotlinx.coroutines.flow.collect
 import kotlinx.coroutines.launch
 
 /** A ViewBinder for [FooterActionsViewBinder]. */
-object FooterActionsViewBinder {
+@SysUISingleton
+class FooterActionsViewBinder @Inject constructor() {
     /** Create a view that can later be [bound][bind] to a [FooterActionsViewModel]. */
-    @JvmStatic
     fun create(context: Context): LinearLayout {
         return LayoutInflater.from(context).inflate(R.layout.footer_actions, /* root= */ null)
             as LinearLayout
     }
 
     /** Bind [view] to [viewModel]. */
-    @JvmStatic
     fun bind(
         view: LinearLayout,
         viewModel: FooterActionsViewModel,
@@ -98,6 +98,11 @@
         var previousForegroundServices: FooterActionsForegroundServicesButtonViewModel? = null
         var previousUserSwitcher: FooterActionsButtonViewModel? = null
 
+        // Set the initial visibility on the View directly so that we don't briefly show it for a
+        // few frames before [viewModel.isVisible] is collected.
+        view.isInvisible = !viewModel.isVisible.value
+
+        // Listen for ViewModel updates when the View is attached.
         view.repeatWhenAttached {
             val attachedScope = this.lifecycleScope
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModel.kt b/packages/SystemUI/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModel.kt
index 3a9098a..b3596a2 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModel.kt
@@ -64,7 +64,7 @@
      * the UI should still participate to the layout it is included in (i.e. in the View world it
      * should be INVISIBLE, not GONE).
      */
-    private val _isVisible = MutableStateFlow(true)
+    private val _isVisible = MutableStateFlow(false)
     val isVisible: StateFlow<Boolean> = _isVisible.asStateFlow()
 
     /** The alpha the UI rendering this ViewModel should have. */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
index 142689e..ea5a1c0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
@@ -335,6 +335,9 @@
             R.id.keyguard_indication_text_bottom);
         mInitialTextColorState = mTopIndicationView != null
                 ? mTopIndicationView.getTextColors() : ColorStateList.valueOf(Color.WHITE);
+        if (mRotateTextViewController != null) {
+            mRotateTextViewController.destroy();
+        }
         mRotateTextViewController = new KeyguardIndicationRotateTextViewController(
                 mLockScreenIndicationView,
                 mExecutor,
diff --git a/packages/SystemUI/src/com/android/systemui/util/ViewController.java b/packages/SystemUI/src/com/android/systemui/util/ViewController.java
index 0dd5788..1f118d1 100644
--- a/packages/SystemUI/src/com/android/systemui/util/ViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/util/ViewController.java
@@ -109,6 +109,11 @@
         }
     }
 
+    /** Destroy ViewController, removing any listeners. */
+    public void destroy() {
+        mView.removeOnAttachStateChangeListener(mOnAttachStateListener);
+    }
+
     /**
      * Called when the view is attached and a call to {@link #init()} has been made in either order.
      */
diff --git a/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java
index f143c467..7b41605 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java
@@ -376,6 +376,34 @@
         }
     }
 
+    @Test
+    public void testHomeControlsDoNotShowIfNotAvailable_featureEnabled() {
+        when(mFeatureFlags.isEnabled(Flags.ALWAYS_SHOW_HOME_CONTROLS_ON_DREAMS)).thenReturn(true);
+
+        final DreamOverlayStateController stateController = getDreamOverlayStateController(true);
+        stateController.setShouldShowComplications(true);
+
+        final Complication homeControlsComplication = Mockito.mock(Complication.class);
+        when(homeControlsComplication.getRequiredTypeAvailability())
+                .thenReturn(Complication.COMPLICATION_TYPE_HOME_CONTROLS);
+
+        stateController.addComplication(homeControlsComplication);
+
+        final DreamOverlayStateController.Callback callback =
+                Mockito.mock(DreamOverlayStateController.Callback.class);
+
+        stateController.addCallback(callback);
+        mExecutor.runAllReady();
+
+        // No home controls since it is not available.
+        assertThat(stateController.getComplications()).doesNotContain(homeControlsComplication);
+
+        stateController.setAvailableComplicationTypes(Complication.COMPLICATION_TYPE_HOME_CONTROLS
+                | Complication.COMPLICATION_TYPE_WEATHER);
+        mExecutor.runAllReady();
+        assertThat(stateController.getComplications()).contains(homeControlsComplication);
+    }
+
     private DreamOverlayStateController getDreamOverlayStateController(boolean overlayEnabled) {
         return new DreamOverlayStateController(mExecutor, overlayEnabled, mFeatureFlags);
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewControllerTest.java
index c3b0e5226..d934f76 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardIndicationRotateTextViewControllerTest.java
@@ -23,9 +23,11 @@
 import static com.android.systemui.keyguard.KeyguardIndicationRotateTextViewController.INDICATION_TYPE_OWNER_INFO;
 
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.verify;
@@ -88,6 +90,54 @@
     }
 
     @Test
+    public void onViewDetached_removesStatusBarStateListener() {
+        mController.onViewDetached();
+        verify(mStatusBarStateController).removeCallback(mStatusBarStateListener);
+    }
+
+    @Test
+    public void onViewDetached_removesAllScheduledIndications() {
+        // GIVEN show next indication runnable is set
+        final KeyguardIndicationRotateTextViewController.ShowNextIndication mockShowNextIndication =
+                mock(KeyguardIndicationRotateTextViewController.ShowNextIndication.class);
+        mController.mShowNextIndicationRunnable = mockShowNextIndication;
+
+        // WHEN the view is detached
+        mController.onViewDetached();
+
+        // THEN delayed execution is cancelled & runnable set to null
+        verify(mockShowNextIndication).cancelDelayedExecution();
+        assertNull(mController.mShowNextIndicationRunnable);
+    }
+
+    @Test
+    public void destroy_removesStatusBarStateListener() {
+        mController.destroy();
+        verify(mStatusBarStateController).removeCallback(mStatusBarStateListener);
+    }
+
+    @Test
+    public void destroy_removesOnAttachStateChangeListener() {
+        mController.destroy();
+        verify(mView).removeOnAttachStateChangeListener(any());
+    }
+
+    @Test
+    public void destroy_removesAllScheduledIndications() {
+        // GIVEN show next indication runnable is set
+        final KeyguardIndicationRotateTextViewController.ShowNextIndication mockShowNextIndication =
+                mock(KeyguardIndicationRotateTextViewController.ShowNextIndication.class);
+        mController.mShowNextIndicationRunnable = mockShowNextIndication;
+
+        // WHEN the controller is destroyed
+        mController.destroy();
+
+        // THEN delayed execution is cancelled & runnable set to null
+        verify(mockShowNextIndication).cancelDelayedExecution();
+        assertNull(mController.mShowNextIndicationRunnable);
+    }
+
+    @Test
     public void testInitialState_noIndication() {
         assertFalse(mController.hasIndications());
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
index 0ab0e2b..87ca9df 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
@@ -106,6 +106,7 @@
     @Mock private QSSquishinessController mSquishinessController;
     @Mock private FooterActionsViewModel mFooterActionsViewModel;
     @Mock private FooterActionsViewModel.Factory mFooterActionsViewModelFactory;
+    @Mock private FooterActionsViewBinder mFooterActionsViewBinder;
     @Mock private LargeScreenShadeInterpolator mLargeScreenShadeInterpolator;
     @Mock private FeatureFlags mFeatureFlags;
     private View mQsFragmentView;
@@ -558,6 +559,7 @@
                 mock(QSLogger.class),
                 mock(FooterActionsController.class),
                 mFooterActionsViewModelFactory,
+                mFooterActionsViewBinder,
                 mLargeScreenShadeInterpolator,
                 mFeatureFlags);
     }
@@ -584,7 +586,7 @@
         when(mQsFragmentView.findViewById(R.id.header)).thenReturn(mHeader);
         when(mQsFragmentView.findViewById(android.R.id.edit)).thenReturn(new View(mContext));
         when(mQsFragmentView.findViewById(R.id.qs_footer_actions)).thenAnswer(
-                invocation -> FooterActionsViewBinder.create(mContext));
+                invocation -> new FooterActionsViewBinder().create(mContext));
     }
 
     private void setUpInflater() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt
index 59f0d96..2cc6709 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt
@@ -376,13 +376,13 @@
     @Test
     fun isVisible() {
         val underTest = utils.footerActionsViewModel()
-        assertThat(underTest.isVisible.value).isTrue()
-
-        underTest.onVisibilityChangeRequested(visible = false)
         assertThat(underTest.isVisible.value).isFalse()
 
         underTest.onVisibilityChangeRequested(visible = true)
         assertThat(underTest.isVisible.value).isTrue()
+
+        underTest.onVisibilityChangeRequested(visible = false)
+        assertThat(underTest.isVisible.value).isFalse()
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
index 4438b98..f7fcab1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
@@ -325,6 +325,21 @@
     }
 
     @Test
+    public void createController_setIndicationAreaAgain_destroysPreviousRotateTextViewController() {
+        // GIVEN a controller with a mocked rotate text view controlller
+        final KeyguardIndicationRotateTextViewController mockedRotateTextViewController =
+                mock(KeyguardIndicationRotateTextViewController.class);
+        createController();
+        mController.mRotateTextViewController = mockedRotateTextViewController;
+
+        // WHEN a new indication area is set
+        mController.setIndicationArea(mIndicationArea);
+
+        // THEN the previous rotateTextViewController is destroyed
+        verify(mockedRotateTextViewController).destroy();
+    }
+
+    @Test
     public void createController_addsAlignmentListener() {
         createController();
 
diff --git a/services/core/java/com/android/server/audio/SoundDoseHelper.java b/services/core/java/com/android/server/audio/SoundDoseHelper.java
index a57dd40..7cdea8d 100644
--- a/services/core/java/com/android/server/audio/SoundDoseHelper.java
+++ b/services/core/java/com/android/server/audio/SoundDoseHelper.java
@@ -87,10 +87,11 @@
     private static final int SAFE_MEDIA_VOLUME_ACTIVE = 3;  // unconfirmed
 
     private static final int MSG_CONFIGURE_SAFE_MEDIA = SAFE_MEDIA_VOLUME_MSG_START + 1;
-    private static final int MSG_PERSIST_SAFE_VOLUME_STATE = SAFE_MEDIA_VOLUME_MSG_START + 2;
-    private static final int MSG_PERSIST_MUSIC_ACTIVE_MS = SAFE_MEDIA_VOLUME_MSG_START + 3;
-    private static final int MSG_PERSIST_CSD_VALUES = SAFE_MEDIA_VOLUME_MSG_START + 4;
-    /*package*/ static final int MSG_CSD_UPDATE_ATTENUATION = SAFE_MEDIA_VOLUME_MSG_START + 5;
+    private static final int MSG_CONFIGURE_SAFE_MEDIA_FORCED = SAFE_MEDIA_VOLUME_MSG_START + 2;
+    private static final int MSG_PERSIST_SAFE_VOLUME_STATE = SAFE_MEDIA_VOLUME_MSG_START + 3;
+    private static final int MSG_PERSIST_MUSIC_ACTIVE_MS = SAFE_MEDIA_VOLUME_MSG_START + 4;
+    private static final int MSG_PERSIST_CSD_VALUES = SAFE_MEDIA_VOLUME_MSG_START + 5;
+    /*package*/ static final int MSG_CSD_UPDATE_ATTENUATION = SAFE_MEDIA_VOLUME_MSG_START + 6;
 
     private static final int UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX = (20 * 3600 * 1000); // 20 hours
 
@@ -611,8 +612,7 @@
     }
 
     /*package*/ void configureSafeMedia(boolean forced, String caller) {
-        int msg = MSG_CONFIGURE_SAFE_MEDIA;
-
+        int msg = forced ? MSG_CONFIGURE_SAFE_MEDIA_FORCED : MSG_CONFIGURE_SAFE_MEDIA;
         mAudioHandler.removeMessages(msg);
 
         long time = 0;
@@ -622,7 +622,7 @@
         }
 
         mAudioHandler.sendMessageAtTime(
-                mAudioHandler.obtainMessage(msg, /*arg1=*/forced ? 1 : 0, /*arg2=*/0, caller),
+                mAudioHandler.obtainMessage(msg, /*arg1=*/0, /*arg2=*/0, caller),
                 time);
     }
 
@@ -664,8 +664,10 @@
 
     /*package*/ void handleMessage(Message msg) {
         switch (msg.what) {
+            case MSG_CONFIGURE_SAFE_MEDIA_FORCED:
             case MSG_CONFIGURE_SAFE_MEDIA:
-                onConfigureSafeMedia((msg.arg1 == 1), (String) msg.obj);
+                onConfigureSafeMedia((msg.what == MSG_CONFIGURE_SAFE_MEDIA_FORCED),
+                        (String) msg.obj);
                 break;
             case MSG_PERSIST_SAFE_VOLUME_STATE:
                 onPersistSafeVolumeState(msg.arg1);
diff --git a/services/core/java/com/android/server/display/LogicalDisplay.java b/services/core/java/com/android/server/display/LogicalDisplay.java
index dab00d8..0b6d1c8 100644
--- a/services/core/java/com/android/server/display/LogicalDisplay.java
+++ b/services/core/java/com/android/server/display/LogicalDisplay.java
@@ -181,6 +181,19 @@
      */
     private String mThermalBrightnessThrottlingDataId;
 
+    /**
+     * Refresh rate range limitation based on the current device layout
+     */
+    @Nullable
+    private SurfaceControl.RefreshRateRange mLayoutLimitedRefreshRate;
+
+    /**
+     * RefreshRateRange limitation for @Temperature.ThrottlingStatus
+     */
+    @NonNull
+    private SparseArray<SurfaceControl.RefreshRateRange> mThermalRefreshRateThrottling =
+            new SparseArray<>();
+
     public LogicalDisplay(int displayId, int layerStack, DisplayDevice primaryDisplayDevice) {
         mDisplayId = displayId;
         mLayerStack = layerStack;
@@ -339,24 +352,24 @@
      */
     public void updateLayoutLimitedRefreshRateLocked(
             @Nullable SurfaceControl.RefreshRateRange layoutLimitedRefreshRate) {
-        if (!Objects.equals(layoutLimitedRefreshRate, mBaseDisplayInfo.layoutLimitedRefreshRate)) {
-            mBaseDisplayInfo.layoutLimitedRefreshRate = layoutLimitedRefreshRate;
-            mInfo.set(null);
+        if (!Objects.equals(layoutLimitedRefreshRate, mLayoutLimitedRefreshRate)) {
+            mLayoutLimitedRefreshRate = layoutLimitedRefreshRate;
+            mDirty = true;
         }
     }
     /**
-     * Updates refreshRateThermalThrottling
+     * Updates thermalRefreshRateThrottling
      *
-     * @param refreshRanges new refreshRateThermalThrottling ranges limited by layout or default
+     * @param refreshRanges new thermalRefreshRateThrottling ranges limited by layout or default
      */
     public void updateThermalRefreshRateThrottling(
             @Nullable SparseArray<SurfaceControl.RefreshRateRange> refreshRanges) {
         if (refreshRanges == null) {
             refreshRanges = new SparseArray<>();
         }
-        if (!mBaseDisplayInfo.refreshRateThermalThrottling.contentEquals(refreshRanges)) {
-            mBaseDisplayInfo.refreshRateThermalThrottling = refreshRanges;
-            mInfo.set(null);
+        if (!mThermalRefreshRateThrottling.contentEquals(refreshRanges)) {
+            mThermalRefreshRateThrottling = refreshRanges;
+            mDirty = true;
         }
     }
 
@@ -499,6 +512,9 @@
                 mBaseDisplayInfo.removeMode = Display.REMOVE_MODE_DESTROY_CONTENT;
             }
 
+            mBaseDisplayInfo.layoutLimitedRefreshRate = mLayoutLimitedRefreshRate;
+            mBaseDisplayInfo.thermalRefreshRateThrottling = mThermalRefreshRateThrottling;
+
             mPrimaryDisplayDeviceInfo = deviceInfo;
             mInfo.set(null);
             mDirty = false;
@@ -952,6 +968,8 @@
         pw.println("mDisplayGroupName=" + mDisplayGroupName);
         pw.println("mThermalBrightnessThrottlingDataId=" + mThermalBrightnessThrottlingDataId);
         pw.println("mLeadDisplayId=" + mLeadDisplayId);
+        pw.println("mLayoutLimitedRefreshRate=" + mLayoutLimitedRefreshRate);
+        pw.println("mThermalRefreshRateThrottling=" + mThermalRefreshRateThrottling);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/display/mode/DisplayModeDirector.java b/services/core/java/com/android/server/display/mode/DisplayModeDirector.java
index 03b49f0..fd94be9 100644
--- a/services/core/java/com/android/server/display/mode/DisplayModeDirector.java
+++ b/services/core/java/com/android/server/display/mode/DisplayModeDirector.java
@@ -103,10 +103,6 @@
     private static final int MSG_REFRESH_RATE_IN_HBM_SUNLIGHT_CHANGED = 7;
     private static final int MSG_REFRESH_RATE_IN_HBM_HDR_CHANGED = 8;
 
-    // Special ID used to indicate that given vote is to be applied globally, rather than to a
-    // specific display.
-    private static final int GLOBAL_ID = -1;
-
     private static final float FLOAT_TOLERANCE = RefreshRateRange.FLOAT_TOLERANCE;
 
     private final Object mLock = new Object();
@@ -129,10 +125,6 @@
     @Nullable
     private DisplayDeviceConfig mDefaultDisplayDeviceConfig;
 
-    // A map from the display ID to the collection of votes and their priority. The latter takes
-    // the form of another map from the priority to the vote itself so that each priority is
-    // guaranteed to have exactly one vote, which is also easily and efficiently replaceable.
-    private SparseArray<SparseArray<Vote>> mVotesByDisplay;
     // A map from the display ID to the supported modes on that display.
     private SparseArray<Display.Mode[]> mSupportedModesByDisplay;
     // A map from the display ID to the default mode of that display.
@@ -146,6 +138,8 @@
 
     private final boolean mSupportsFrameRateOverride;
 
+    private final VotesStorage mVotesStorage;
+
     /**
      * The allowed refresh rate switching type. This is used by SurfaceFlinger.
      */
@@ -161,7 +155,6 @@
         mContext = context;
         mHandler = new DisplayModeDirectorHandler(handler.getLooper());
         mInjector = injector;
-        mVotesByDisplay = new SparseArray<>();
         mSupportedModesByDisplay = new SparseArray<>();
         mDefaultModeByDisplay = new SparseArray<>();
         mAppRequestObserver = new AppRequestObserver();
@@ -171,15 +164,11 @@
         mBrightnessObserver = new BrightnessObserver(context, handler, injector);
         mDefaultDisplayDeviceConfig = null;
         mUdfpsObserver = new UdfpsObserver();
-        final BallotBox ballotBox = (displayId, priority, vote) -> {
-            synchronized (mLock) {
-                updateVoteLocked(displayId, priority, vote);
-            }
-        };
-        mDisplayObserver = new DisplayObserver(context, handler, ballotBox);
-        mSensorObserver = new SensorObserver(context, ballotBox, injector);
-        mSkinThermalStatusObserver = new SkinThermalStatusObserver(injector, ballotBox);
-        mHbmObserver = new HbmObserver(injector, ballotBox, BackgroundThread.getHandler(),
+        mVotesStorage = new VotesStorage(this::notifyDesiredDisplayModeSpecsChangedLocked);
+        mDisplayObserver = new DisplayObserver(context, handler, mVotesStorage);
+        mSensorObserver = new SensorObserver(context, mVotesStorage, injector);
+        mSkinThermalStatusObserver = new SkinThermalStatusObserver(injector, mVotesStorage);
+        mHbmObserver = new HbmObserver(injector, mVotesStorage, BackgroundThread.getHandler(),
                 mDeviceConfigDisplaySettings);
         mAlwaysRespectAppRequest = false;
         mSupportsFrameRateOverride = injector.supportsFrameRateOverride();
@@ -226,29 +215,7 @@
         mLoggingEnabled = loggingEnabled;
         mBrightnessObserver.setLoggingEnabled(loggingEnabled);
         mSkinThermalStatusObserver.setLoggingEnabled(loggingEnabled);
-    }
-
-    @NonNull
-    private SparseArray<Vote> getVotesLocked(int displayId) {
-        SparseArray<Vote> displayVotes = mVotesByDisplay.get(displayId);
-        final SparseArray<Vote> votes;
-        if (displayVotes != null) {
-            votes = displayVotes.clone();
-        } else {
-            votes = new SparseArray<>();
-        }
-
-        SparseArray<Vote> globalVotes = mVotesByDisplay.get(GLOBAL_ID);
-        if (globalVotes != null) {
-            for (int i = 0; i < globalVotes.size(); i++) {
-                int priority = globalVotes.keyAt(i);
-                if (votes.indexOfKey(priority) < 0) {
-                    votes.put(priority, globalVotes.valueAt(i));
-                }
-            }
-        }
-
-        return votes;
+        mVotesStorage.setLoggingEnabled(loggingEnabled);
     }
 
     private static final class VoteSummary {
@@ -407,7 +374,7 @@
     @NonNull
     public DesiredDisplayModeSpecs getDesiredDisplayModeSpecs(int displayId) {
         synchronized (mLock) {
-            SparseArray<Vote> votes = getVotesLocked(displayId);
+            SparseArray<Vote> votes = mVotesStorage.getVotes(displayId);
             Display.Mode[] modes = mSupportedModesByDisplay.get(displayId);
             Display.Mode defaultMode = mDefaultModeByDisplay.get(displayId);
             if (modes == null || defaultMode == null) {
@@ -780,10 +747,8 @@
     @VisibleForTesting
     @Nullable
     Vote getVote(int displayId, int priority) {
-        synchronized (mLock) {
-            SparseArray<Vote> votes = getVotesLocked(displayId);
-            return votes.get(priority);
-        }
+        SparseArray<Vote> votes = mVotesStorage.getVotes(displayId);
+        return votes.get(priority);
     }
 
     /**
@@ -806,18 +771,6 @@
                 final Display.Mode mode = mDefaultModeByDisplay.valueAt(i);
                 pw.println("    " + id + " -> " + mode);
             }
-            pw.println("  mVotesByDisplay:");
-            for (int i = 0; i < mVotesByDisplay.size(); i++) {
-                pw.println("    " + mVotesByDisplay.keyAt(i) + ":");
-                SparseArray<Vote> votes = mVotesByDisplay.valueAt(i);
-                for (int p = Vote.MAX_PRIORITY; p >= Vote.MIN_PRIORITY; p--) {
-                    Vote vote = votes.get(p);
-                    if (vote == null) {
-                        continue;
-                    }
-                    pw.println("      " + Vote.priorityToString(p) + " -> " + vote);
-                }
-            }
             pw.println("  mModeSwitchingType: " + switchingTypeToString(mModeSwitchingType));
             pw.println("  mAlwaysRespectAppRequest: " + mAlwaysRespectAppRequest);
             mSettingsObserver.dumpLocked(pw);
@@ -827,44 +780,10 @@
             mHbmObserver.dumpLocked(pw);
             mSkinThermalStatusObserver.dumpLocked(pw);
         }
-
+        mVotesStorage.dump(pw);
         mSensorObserver.dump(pw);
     }
 
-    private void updateVoteLocked(int priority, Vote vote) {
-        updateVoteLocked(GLOBAL_ID, priority, vote);
-    }
-
-    private void updateVoteLocked(int displayId, int priority, Vote vote) {
-        if (mLoggingEnabled) {
-            Slog.i(TAG, "updateVoteLocked(displayId=" + displayId
-                    + ", priority=" + Vote.priorityToString(priority)
-                    + ", vote=" + vote + ")");
-        }
-        if (priority < Vote.MIN_PRIORITY || priority > Vote.MAX_PRIORITY) {
-            Slog.w(TAG, "Received a vote with an invalid priority, ignoring:"
-                    + " priority=" + Vote.priorityToString(priority)
-                    + ", vote=" + vote, new Throwable());
-            return;
-        }
-        final SparseArray<Vote> votes = getOrCreateVotesByDisplay(displayId);
-
-        if (vote != null) {
-            votes.put(priority, vote);
-        } else {
-            votes.remove(priority);
-        }
-
-        if (votes.size() == 0) {
-            if (mLoggingEnabled) {
-                Slog.i(TAG, "No votes left for display " + displayId + ", removing.");
-            }
-            mVotesByDisplay.remove(displayId);
-        }
-
-        notifyDesiredDisplayModeSpecsChangedLocked();
-    }
-
     @GuardedBy("mLock")
     private float getMaxRefreshRateLocked(int displayId) {
         Display.Mode[] modes = mSupportedModesByDisplay.get(displayId);
@@ -890,16 +809,6 @@
         }
     }
 
-    private SparseArray<Vote> getOrCreateVotesByDisplay(int displayId) {
-        if (mVotesByDisplay.indexOfKey(displayId) >= 0) {
-            return mVotesByDisplay.get(displayId);
-        } else {
-            SparseArray<Vote> votes = new SparseArray<>();
-            mVotesByDisplay.put(displayId, votes);
-            return votes;
-        }
-    }
-
     private static String switchingTypeToString(@DisplayManager.SwitchingType int type) {
         switch (type) {
             case DisplayManager.SWITCHING_TYPE_NONE:
@@ -927,7 +836,7 @@
 
     @VisibleForTesting
     void injectVotesByDisplay(SparseArray<SparseArray<Vote>> votesByDisplay) {
-        mVotesByDisplay = votesByDisplay;
+        mVotesStorage.injectVotesByDisplay(votesByDisplay);
     }
 
     @VisibleForTesting
@@ -1157,225 +1066,6 @@
     }
 
     @VisibleForTesting
-    static final class Vote {
-        // DEFAULT_RENDER_FRAME_RATE votes for render frame rate [0, DEFAULT]. As the lowest
-        // priority vote, it's overridden by all other considerations. It acts to set a default
-        // frame rate for a device.
-        public static final int PRIORITY_DEFAULT_RENDER_FRAME_RATE = 0;
-
-        // PRIORITY_FLICKER_REFRESH_RATE votes for a single refresh rate like [60,60], [90,90] or
-        // null. It is used to set a preferred refresh rate value in case the higher priority votes
-        // result is a range.
-        public static final int PRIORITY_FLICKER_REFRESH_RATE = 1;
-
-        // High-brightness-mode may need a specific range of refresh-rates to function properly.
-        public static final int PRIORITY_HIGH_BRIGHTNESS_MODE = 2;
-
-        // SETTING_MIN_RENDER_FRAME_RATE is used to propose a lower bound of the render frame rate.
-        // It votes [minRefreshRate, Float.POSITIVE_INFINITY]
-        public static final int PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE = 3;
-
-        // APP_REQUEST_RENDER_FRAME_RATE_RANGE is used to for internal apps to limit the render
-        // frame rate in certain cases, mostly to preserve power.
-        // @see android.view.WindowManager.LayoutParams#preferredMinRefreshRate
-        // @see android.view.WindowManager.LayoutParams#preferredMaxRefreshRate
-        // It votes to [preferredMinRefreshRate, preferredMaxRefreshRate].
-        public static final int PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE = 4;
-
-        // We split the app request into different priorities in case we can satisfy one desire
-        // without the other.
-
-        // Application can specify preferred refresh rate with below attrs.
-        // @see android.view.WindowManager.LayoutParams#preferredRefreshRate
-        // @see android.view.WindowManager.LayoutParams#preferredDisplayModeId
-        //
-        // When the app specifies a LayoutParams#preferredDisplayModeId, in addition to the
-        // refresh rate, it also chooses a preferred size (resolution) as part of the selected
-        // mode id. The app preference is then translated to APP_REQUEST_BASE_MODE_REFRESH_RATE and
-        // optionally to APP_REQUEST_SIZE as well, if a mode id was selected.
-        // The system also forces some apps like denylisted app to run at a lower refresh rate.
-        // @see android.R.array#config_highRefreshRateBlacklist
-        //
-        // When summarizing the votes and filtering the allowed display modes, these votes determine
-        // which mode id should be the base mode id to be sent to SurfaceFlinger:
-        // - APP_REQUEST_BASE_MODE_REFRESH_RATE is used to validate the vote summary. If a summary
-        //   includes a base mode refresh rate, but it is not in the refresh rate range, then the
-        //   summary is considered invalid so we could drop a lower priority vote and try again.
-        // - APP_REQUEST_SIZE is used to filter out display modes of a different size.
-        //
-        // The preferred refresh rate is set on the main surface of the app outside of
-        // DisplayModeDirector.
-        // @see com.android.server.wm.WindowState#updateFrameRateSelectionPriorityIfNeeded
-        public static final int PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE = 5;
-        public static final int PRIORITY_APP_REQUEST_SIZE = 6;
-
-        // SETTING_PEAK_RENDER_FRAME_RATE has a high priority and will restrict the bounds of the
-        // rest of low priority voters. It votes [0, max(PEAK, MIN)]
-        public static final int PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE = 7;
-
-        // To avoid delay in switching between 60HZ -> 90HZ when activating LHBM, set refresh
-        // rate to max value (same as for PRIORITY_UDFPS) on lock screen
-        public static final int PRIORITY_AUTH_OPTIMIZER_RENDER_FRAME_RATE = 8;
-
-        // For concurrent displays we want to limit refresh rate on all displays
-        public static final int PRIORITY_LAYOUT_LIMITED_FRAME_RATE = 9;
-
-        // LOW_POWER_MODE force the render frame rate to [0, 60HZ] if
-        // Settings.Global.LOW_POWER_MODE is on.
-        public static final int PRIORITY_LOW_POWER_MODE = 10;
-
-        // PRIORITY_FLICKER_REFRESH_RATE_SWITCH votes for disabling refresh rate switching. If the
-        // higher priority voters' result is a range, it will fix the rate to a single choice.
-        // It's used to avoid refresh rate switches in certain conditions which may result in the
-        // user seeing the display flickering when the switches occur.
-        public static final int PRIORITY_FLICKER_REFRESH_RATE_SWITCH = 11;
-
-        // Force display to [0, 60HZ] if skin temperature is at or above CRITICAL.
-        public static final int PRIORITY_SKIN_TEMPERATURE = 12;
-
-        // The proximity sensor needs the refresh rate to be locked in order to function, so this is
-        // set to a high priority.
-        public static final int PRIORITY_PROXIMITY = 13;
-
-        // The Under-Display Fingerprint Sensor (UDFPS) needs the refresh rate to be locked in order
-        // to function, so this needs to be the highest priority of all votes.
-        public static final int PRIORITY_UDFPS = 14;
-
-        // Whenever a new priority is added, remember to update MIN_PRIORITY, MAX_PRIORITY, and
-        // APP_REQUEST_REFRESH_RATE_RANGE_PRIORITY_CUTOFF, as well as priorityToString.
-
-        public static final int MIN_PRIORITY = PRIORITY_DEFAULT_RENDER_FRAME_RATE;
-        public static final int MAX_PRIORITY = PRIORITY_UDFPS;
-
-        // The cutoff for the app request refresh rate range. Votes with priorities lower than this
-        // value will not be considered when constructing the app request refresh rate range.
-        public static final int APP_REQUEST_REFRESH_RATE_RANGE_PRIORITY_CUTOFF =
-                PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE;
-
-        /**
-         * A value signifying an invalid width or height in a vote.
-         */
-        public static final int INVALID_SIZE = -1;
-
-        /**
-         * The requested width of the display in pixels, or INVALID_SIZE;
-         */
-        public final int width;
-        /**
-         * The requested height of the display in pixels, or INVALID_SIZE;
-         */
-        public final int height;
-        /**
-         * Information about the refresh rate frame rate ranges DM would like to set the display to.
-         */
-        public final RefreshRateRanges refreshRateRanges;
-
-        /**
-         * Whether refresh rate switching should be disabled (i.e. the refresh rate range is
-         * a single value).
-         */
-        public final boolean disableRefreshRateSwitching;
-
-        /**
-         * The preferred refresh rate selected by the app. It is used to validate that the summary
-         * refresh rate ranges include this value, and are not restricted by a lower priority vote.
-         */
-        public final float appRequestBaseModeRefreshRate;
-
-        public static Vote forPhysicalRefreshRates(float minRefreshRate, float maxRefreshRate) {
-            return new Vote(INVALID_SIZE, INVALID_SIZE, minRefreshRate, maxRefreshRate, 0,
-                    Float.POSITIVE_INFINITY,
-                    minRefreshRate == maxRefreshRate, 0f);
-        }
-
-        public static Vote forRenderFrameRates(float minFrameRate, float maxFrameRate) {
-            return new Vote(INVALID_SIZE, INVALID_SIZE, 0, Float.POSITIVE_INFINITY, minFrameRate,
-                    maxFrameRate,
-                    false, 0f);
-        }
-
-        public static Vote forSize(int width, int height) {
-            return new Vote(width, height, 0, Float.POSITIVE_INFINITY, 0, Float.POSITIVE_INFINITY,
-                    false,
-                    0f);
-        }
-
-        public static Vote forDisableRefreshRateSwitching() {
-            return new Vote(INVALID_SIZE, INVALID_SIZE, 0, Float.POSITIVE_INFINITY, 0,
-                    Float.POSITIVE_INFINITY, true,
-                    0f);
-        }
-
-        public static Vote forBaseModeRefreshRate(float baseModeRefreshRate) {
-            return new Vote(INVALID_SIZE, INVALID_SIZE, 0, Float.POSITIVE_INFINITY, 0,
-                    Float.POSITIVE_INFINITY, false,
-                    baseModeRefreshRate);
-        }
-
-        private Vote(int width, int height,
-                float minPhysicalRefreshRate,
-                float maxPhysicalRefreshRate,
-                float minRenderFrameRate,
-                float maxRenderFrameRate,
-                boolean disableRefreshRateSwitching,
-                float baseModeRefreshRate) {
-            this.width = width;
-            this.height = height;
-            this.refreshRateRanges = new RefreshRateRanges(
-                    new RefreshRateRange(minPhysicalRefreshRate, maxPhysicalRefreshRate),
-                    new RefreshRateRange(minRenderFrameRate, maxRenderFrameRate));
-            this.disableRefreshRateSwitching = disableRefreshRateSwitching;
-            this.appRequestBaseModeRefreshRate = baseModeRefreshRate;
-        }
-
-        public static String priorityToString(int priority) {
-            switch (priority) {
-                case PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE:
-                    return "PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE";
-                case PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE:
-                    return "PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE";
-                case PRIORITY_APP_REQUEST_SIZE:
-                    return "PRIORITY_APP_REQUEST_SIZE";
-                case PRIORITY_DEFAULT_RENDER_FRAME_RATE:
-                    return "PRIORITY_DEFAULT_REFRESH_RATE";
-                case PRIORITY_FLICKER_REFRESH_RATE:
-                    return "PRIORITY_FLICKER_REFRESH_RATE";
-                case PRIORITY_FLICKER_REFRESH_RATE_SWITCH:
-                    return "PRIORITY_FLICKER_REFRESH_RATE_SWITCH";
-                case PRIORITY_HIGH_BRIGHTNESS_MODE:
-                    return "PRIORITY_HIGH_BRIGHTNESS_MODE";
-                case PRIORITY_PROXIMITY:
-                    return "PRIORITY_PROXIMITY";
-                case PRIORITY_LOW_POWER_MODE:
-                    return "PRIORITY_LOW_POWER_MODE";
-                case PRIORITY_SKIN_TEMPERATURE:
-                    return "PRIORITY_SKIN_TEMPERATURE";
-                case PRIORITY_UDFPS:
-                    return "PRIORITY_UDFPS";
-                case PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE:
-                    return "PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE";
-                case PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE:
-                    return "PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE";
-                case PRIORITY_AUTH_OPTIMIZER_RENDER_FRAME_RATE:
-                    return "PRIORITY_AUTH_OPTIMIZER_RENDER_FRAME_RATE";
-                case PRIORITY_LAYOUT_LIMITED_FRAME_RATE:
-                    return "PRIORITY_LAYOUT_LIMITED_FRAME_RATE";
-                default:
-                    return Integer.toString(priority);
-            }
-        }
-
-        @Override
-        public String toString() {
-            return "Vote{"
-                    + "width=" + width + ", height=" + height
-                    + ", refreshRateRanges=" + refreshRateRanges
-                    + ", disableRefreshRateSwitching=" + disableRefreshRateSwitching
-                    + ", appRequestBaseModeRefreshRate=" + appRequestBaseModeRefreshRate + "}";
-        }
-    }
-
-    @VisibleForTesting
     final class SettingsObserver extends ContentObserver {
         private final Uri mSmoothDisplaySetting =
                 Settings.System.getUriFor(Settings.System.SMOOTH_DISPLAY);
@@ -1510,7 +1200,7 @@
             } else {
                 vote = null;
             }
-            updateVoteLocked(Vote.PRIORITY_LOW_POWER_MODE, vote);
+            mVotesStorage.updateGlobalVote(Vote.PRIORITY_LOW_POWER_MODE, vote);
             mBrightnessObserver.onLowPowerModeEnabledLocked(inLowPowerMode);
         }
 
@@ -1529,13 +1219,14 @@
             Vote peakVote = peakRefreshRate == 0f
                     ? null
                     : Vote.forRenderFrameRates(0f, Math.max(minRefreshRate, peakRefreshRate));
-            updateVoteLocked(Vote.PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE, peakVote);
-            updateVoteLocked(Vote.PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE,
+            mVotesStorage.updateGlobalVote(Vote.PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE,
+                    peakVote);
+            mVotesStorage.updateGlobalVote(Vote.PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE,
                     Vote.forRenderFrameRates(minRefreshRate, Float.POSITIVE_INFINITY));
             Vote defaultVote =
                     defaultRefreshRate == 0f
                             ? null : Vote.forRenderFrameRates(0f, defaultRefreshRate);
-            updateVoteLocked(Vote.PRIORITY_DEFAULT_RENDER_FRAME_RATE, defaultVote);
+            mVotesStorage.updateGlobalVote(Vote.PRIORITY_DEFAULT_RENDER_FRAME_RATE, defaultVote);
 
             float maxRefreshRate;
             if (peakRefreshRate == 0f && defaultRefreshRate == 0f) {
@@ -1619,9 +1310,9 @@
                 sizeVote = null;
             }
 
-            updateVoteLocked(displayId, Vote.PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE,
+            mVotesStorage.updateVote(displayId, Vote.PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE,
                     baseModeRefreshRateVote);
-            updateVoteLocked(displayId, Vote.PRIORITY_APP_REQUEST_SIZE, sizeVote);
+            mVotesStorage.updateVote(displayId, Vote.PRIORITY_APP_REQUEST_SIZE, sizeVote);
         }
 
         private void setAppPreferredRefreshRateRangeLocked(int displayId,
@@ -1652,11 +1343,8 @@
                 mAppPreferredRefreshRateRangeByDisplay.remove(displayId);
                 vote = null;
             }
-            synchronized (mLock) {
-                updateVoteLocked(displayId,
-                        Vote.PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE,
-                        vote);
-            }
+            mVotesStorage.updateVote(displayId, Vote.PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE,
+                    vote);
         }
 
         private Display.Mode findModeByIdLocked(int displayId, int modeId) {
@@ -1696,23 +1384,22 @@
         // calling into us already holding its own lock.
         private final Context mContext;
         private final Handler mHandler;
-        private final BallotBox mBallotBox;
+        private final VotesStorage mVotesStorage;
 
-        DisplayObserver(Context context, Handler handler, BallotBox ballotBox) {
+        DisplayObserver(Context context, Handler handler, VotesStorage votesStorage) {
             mContext = context;
             mHandler = handler;
-            mBallotBox = ballotBox;
+            mVotesStorage = votesStorage;
         }
 
         public void observe() {
-            DisplayManager dm = mContext.getSystemService(DisplayManager.class);
-            dm.registerDisplayListener(this, mHandler);
+            mInjector.registerDisplayListener(this, mHandler);
 
             // Populate existing displays
             SparseArray<Display.Mode[]> modes = new SparseArray<>();
             SparseArray<Display.Mode> defaultModes = new SparseArray<>();
             DisplayInfo info = new DisplayInfo();
-            Display[] displays = dm.getDisplays(DISPLAY_CATEGORY_ALL_INCLUDING_DISABLED);
+            Display[] displays = mInjector.getDisplays();
             for (Display d : displays) {
                 final int displayId = d.getDisplayId();
                 d.getDisplayInfo(info);
@@ -1753,23 +1440,16 @@
 
         @Nullable
         private DisplayInfo getDisplayInfo(int displayId) {
-            Display d = mContext.getSystemService(DisplayManager.class).getDisplay(displayId);
-            if (d == null) {
-                // We can occasionally get a display added or changed event for a display that was
-                // subsequently removed, which means this returns null. Check this case and bail
-                // out early; if it gets re-attached we'll eventually get another call back for it.
-                return null;
-            }
             DisplayInfo info = new DisplayInfo();
-            d.getDisplayInfo(info);
-            return info;
+            // Display info might be invalid, in this case return null
+            return mInjector.getDisplayInfo(displayId, info) ? info : null;
         }
 
         private void updateLayoutLimitedFrameRate(int displayId, @Nullable DisplayInfo info) {
             Vote vote = info != null && info.layoutLimitedRefreshRate != null
                     ? Vote.forPhysicalRefreshRates(info.layoutLimitedRefreshRate.min,
                     info.layoutLimitedRefreshRate.max) : null;
-            mBallotBox.vote(displayId, Vote.PRIORITY_LAYOUT_LIMITED_FRAME_RATE, vote);
+            mVotesStorage.updateVote(displayId, Vote.PRIORITY_LAYOUT_LIMITED_FRAME_RATE, vote);
         }
 
         private void updateDisplayModes(int displayId, @Nullable DisplayInfo info) {
@@ -2091,8 +1771,8 @@
                 updateSensorStatus();
                 if (!changeable) {
                     // Revoke previous vote from BrightnessObserver
-                    updateVoteLocked(Vote.PRIORITY_FLICKER_REFRESH_RATE, null);
-                    updateVoteLocked(Vote.PRIORITY_FLICKER_REFRESH_RATE_SWITCH, null);
+                    mVotesStorage.updateGlobalVote(Vote.PRIORITY_FLICKER_REFRESH_RATE, null);
+                    mVotesStorage.updateGlobalVote(Vote.PRIORITY_FLICKER_REFRESH_RATE_SWITCH, null);
                 }
             }
         }
@@ -2417,8 +2097,9 @@
                 Slog.d(TAG, "Display brightness " + mBrightness + ", ambient lux " +  mAmbientLux
                         + ", Vote " + refreshRateVote);
             }
-            updateVoteLocked(Vote.PRIORITY_FLICKER_REFRESH_RATE, refreshRateVote);
-            updateVoteLocked(Vote.PRIORITY_FLICKER_REFRESH_RATE_SWITCH, refreshRateSwitchingVote);
+            mVotesStorage.updateGlobalVote(Vote.PRIORITY_FLICKER_REFRESH_RATE, refreshRateVote);
+            mVotesStorage.updateGlobalVote(Vote.PRIORITY_FLICKER_REFRESH_RATE_SWITCH,
+                    refreshRateSwitchingVote);
         }
 
         private boolean hasValidLowZone() {
@@ -2432,8 +2113,7 @@
         }
 
         private void updateDefaultDisplayState() {
-            Display display = mContext.getSystemService(DisplayManager.class)
-                    .getDisplay(Display.DEFAULT_DISPLAY);
+            Display display = mInjector.getDisplay(Display.DEFAULT_DISPLAY);
             if (display == null) {
                 return;
             }
@@ -2687,7 +2367,7 @@
             } else {
                 vote = null;
             }
-            DisplayModeDirector.this.updateVoteLocked(displayId, votePriority, vote);
+            mVotesStorage.updateVote(displayId, votePriority, vote);
         }
 
         void dumpLocked(PrintWriter pw) {
@@ -2713,7 +2393,7 @@
         private final String mProximitySensorName = null;
         private final String mProximitySensorType = Sensor.STRING_TYPE_PROXIMITY;
 
-        private final BallotBox mBallotBox;
+        private final VotesStorage mVotesStorage;
         private final Context mContext;
         private final Injector mInjector;
         @GuardedBy("mSensorObserverLock")
@@ -2725,9 +2405,9 @@
         @GuardedBy("mSensorObserverLock")
         private boolean mIsProxActive = false;
 
-        SensorObserver(Context context, BallotBox ballotBox, Injector injector) {
+        SensorObserver(Context context, VotesStorage votesStorage, Injector injector) {
             mContext = context;
-            mBallotBox = ballotBox;
+            mVotesStorage = votesStorage;
             mInjector = injector;
         }
 
@@ -2750,8 +2430,7 @@
             sensorManager.addProximityActiveListener(BackgroundThread.getExecutor(), this);
 
             synchronized (mSensorObserverLock) {
-                for (Display d : mDisplayManager.getDisplays(
-                        DISPLAY_CATEGORY_ALL_INCLUDING_DISABLED)) {
+                for (Display d : mInjector.getDisplays()) {
                     mDozeStateByDisplay.put(d.getDisplayId(), mInjector.isDozeState(d));
                 }
             }
@@ -2762,8 +2441,7 @@
         }
 
         private void recalculateVotesLocked() {
-            final Display[] displays = mDisplayManager.getDisplays(
-                    DISPLAY_CATEGORY_ALL_INCLUDING_DISABLED);
+            final Display[] displays = mInjector.getDisplays();
             for (Display d : displays) {
                 int displayId = d.getDisplayId();
                 Vote vote = null;
@@ -2775,7 +2453,7 @@
                         vote = Vote.forPhysicalRefreshRates(rate.min, rate.max);
                     }
                 }
-                mBallotBox.vote(displayId, Vote.PRIORITY_PROXIMITY, vote);
+                mVotesStorage.updateVote(displayId, Vote.PRIORITY_PROXIMITY, vote);
             }
         }
 
@@ -2794,7 +2472,7 @@
 
         @Override
         public void onDisplayAdded(int displayId) {
-            boolean isDozeState = mInjector.isDozeState(mDisplayManager.getDisplay(displayId));
+            boolean isDozeState = mInjector.isDozeState(mInjector.getDisplay(displayId));
             synchronized (mSensorObserverLock) {
                 mDozeStateByDisplay.put(displayId, isDozeState);
                 recalculateVotesLocked();
@@ -2806,7 +2484,7 @@
             boolean wasDozeState = mDozeStateByDisplay.get(displayId);
             synchronized (mSensorObserverLock) {
                 mDozeStateByDisplay.put(displayId,
-                        mInjector.isDozeState(mDisplayManager.getDisplay(displayId)));
+                        mInjector.isDozeState(mInjector.getDisplay(displayId)));
                 if (wasDozeState != mDozeStateByDisplay.get(displayId)) {
                     recalculateVotesLocked();
                 }
@@ -2828,7 +2506,7 @@
      * DisplayManagerInternal but originate in the display-device-config file.
      */
     public class HbmObserver implements DisplayManager.DisplayListener {
-        private final BallotBox mBallotBox;
+        private final VotesStorage mVotesStorage;
         private final Handler mHandler;
         private final SparseIntArray mHbmMode = new SparseIntArray();
         private final SparseBooleanArray mHbmActive = new SparseBooleanArray();
@@ -2839,10 +2517,10 @@
 
         private DisplayManagerInternal mDisplayManagerInternal;
 
-        HbmObserver(Injector injector, BallotBox ballotBox, Handler handler,
+        HbmObserver(Injector injector, VotesStorage votesStorage, Handler handler,
                 DeviceConfigDisplaySettings displaySettings) {
             mInjector = injector;
-            mBallotBox = ballotBox;
+            mVotesStorage = votesStorage;
             mHandler = handler;
             mDeviceConfigDisplaySettings = displaySettings;
         }
@@ -2912,7 +2590,7 @@
 
         @Override
         public void onDisplayRemoved(int displayId) {
-            mBallotBox.vote(displayId, Vote.PRIORITY_HIGH_BRIGHTNESS_MODE, null);
+            mVotesStorage.updateVote(displayId, Vote.PRIORITY_HIGH_BRIGHTNESS_MODE, null);
             mHbmMode.delete(displayId);
             mHbmActive.delete(displayId);
         }
@@ -2979,7 +2657,7 @@
                 }
 
             }
-            mBallotBox.vote(displayId, Vote.PRIORITY_HIGH_BRIGHTNESS_MODE, vote);
+            mVotesStorage.updateVote(displayId, Vote.PRIORITY_HIGH_BRIGHTNESS_MODE, vote);
         }
 
         void dumpLocked(PrintWriter pw) {
@@ -3176,8 +2854,13 @@
                 @NonNull ContentObserver observer);
 
         void registerDisplayListener(@NonNull DisplayManager.DisplayListener listener,
+                Handler handler);
+
+        void registerDisplayListener(@NonNull DisplayManager.DisplayListener listener,
                 Handler handler, long flags);
 
+        Display getDisplay(int displayId);
+
         Display[] getDisplays();
 
         boolean getDisplayInfo(int displayId, DisplayInfo displayInfo);
@@ -3222,11 +2905,22 @@
 
         @Override
         public void registerDisplayListener(DisplayManager.DisplayListener listener,
+                Handler handler) {
+            getDisplayManager().registerDisplayListener(listener, handler);
+        }
+
+        @Override
+        public void registerDisplayListener(DisplayManager.DisplayListener listener,
                 Handler handler, long flags) {
             getDisplayManager().registerDisplayListener(listener, handler, flags);
         }
 
         @Override
+        public Display getDisplay(int displayId) {
+            return getDisplayManager().getDisplay(displayId);
+        }
+
+        @Override
         public Display[] getDisplays() {
             return getDisplayManager().getDisplays(DISPLAY_CATEGORY_ALL_INCLUDING_DISABLED);
         }
@@ -3234,10 +2928,13 @@
         @Override
         public boolean getDisplayInfo(int displayId, DisplayInfo displayInfo) {
             Display display = getDisplayManager().getDisplay(displayId);
-            if (display != null) {
-                return display.getDisplayInfo(displayInfo);
+            if (display == null) {
+                // We can occasionally get a display added or changed event for a display that was
+                // subsequently removed, which means this returns null. Check this case and bail
+                // out early; if it gets re-attached we'll eventually get another call back for it.
+                return false;
             }
-            return false;
+            return display.getDisplayInfo(displayInfo);
         }
 
         @Override
@@ -3291,8 +2988,4 @@
                     ServiceManager.getService(Context.THERMAL_SERVICE));
         }
     }
-
-    interface BallotBox {
-        void vote(int displayId, int priority, Vote vote);
-    }
 }
diff --git a/services/core/java/com/android/server/display/mode/SkinThermalStatusObserver.java b/services/core/java/com/android/server/display/mode/SkinThermalStatusObserver.java
index c04735d..58e1550 100644
--- a/services/core/java/com/android/server/display/mode/SkinThermalStatusObserver.java
+++ b/services/core/java/com/android/server/display/mode/SkinThermalStatusObserver.java
@@ -37,7 +37,7 @@
         DisplayManager.DisplayListener {
     private static final String TAG = "SkinThermalStatusObserver";
 
-    private final DisplayModeDirector.BallotBox mBallotBox;
+    private final VotesStorage mVotesStorage;
     private final DisplayModeDirector.Injector mInjector;
 
     private boolean mLoggingEnabled;
@@ -52,15 +52,15 @@
             mThermalThrottlingByDisplay = new SparseArray<>();
 
     SkinThermalStatusObserver(DisplayModeDirector.Injector injector,
-            DisplayModeDirector.BallotBox ballotBox) {
-        this(injector, ballotBox, BackgroundThread.getHandler());
+            VotesStorage votesStorage) {
+        this(injector, votesStorage, BackgroundThread.getHandler());
     }
 
     @VisibleForTesting
     SkinThermalStatusObserver(DisplayModeDirector.Injector injector,
-            DisplayModeDirector.BallotBox ballotBox, Handler handler) {
+            VotesStorage votesStorage, Handler handler) {
         mInjector = injector;
-        mBallotBox = ballotBox;
+        mVotesStorage = votesStorage;
         mHandler = handler;
     }
 
@@ -112,8 +112,8 @@
     public void onDisplayRemoved(int displayId) {
         synchronized (mThermalObserverLock) {
             mThermalThrottlingByDisplay.remove(displayId);
-            mHandler.post(() -> mBallotBox.vote(displayId,
-                    DisplayModeDirector.Vote.PRIORITY_SKIN_TEMPERATURE, null));
+            mHandler.post(() -> mVotesStorage.updateVote(displayId,
+                    Vote.PRIORITY_SKIN_TEMPERATURE, null));
         }
         if (mLoggingEnabled) {
             Slog.d(TAG, "Display removed and voted: displayId=" + displayId);
@@ -138,7 +138,7 @@
         for (Display d : displays) {
             final int displayId = d.getDisplayId();
             d.getDisplayInfo(info);
-            localMap.put(displayId, info.refreshRateThermalThrottling);
+            localMap.put(displayId, info.thermalRefreshRateThrottling);
         }
         synchronized (mThermalObserverLock) {
             for (int i = 0; i < size; i++) {
@@ -154,7 +154,7 @@
         DisplayInfo displayInfo = new DisplayInfo();
         mInjector.getDisplayInfo(displayId, displayInfo);
         SparseArray<SurfaceControl.RefreshRateRange> throttlingMap =
-                displayInfo.refreshRateThermalThrottling;
+                displayInfo.thermalRefreshRateThrottling;
 
         synchronized (mThermalObserverLock) {
             mThermalThrottlingByDisplay.put(displayId, throttlingMap);
@@ -218,11 +218,11 @@
         SurfaceControl.RefreshRateRange foundRange = findBestMatchingRefreshRateRange(currentStatus,
                 throttlingMap);
         // if status <= currentStatus not found in the map reset vote
-        DisplayModeDirector.Vote vote = null;
+        Vote vote = null;
         if (foundRange != null) { // otherwise vote with found range
-            vote = DisplayModeDirector.Vote.forRenderFrameRates(foundRange.min, foundRange.max);
+            vote = Vote.forRenderFrameRates(foundRange.min, foundRange.max);
         }
-        mBallotBox.vote(displayId, DisplayModeDirector.Vote.PRIORITY_SKIN_TEMPERATURE, vote);
+        mVotesStorage.updateVote(displayId, Vote.PRIORITY_SKIN_TEMPERATURE, vote);
         if (mLoggingEnabled) {
             Slog.d(TAG, "Voted: vote=" + vote + ", display =" + displayId);
         }
@@ -244,11 +244,11 @@
 
     private void fallbackReportThrottlingIfNeeded(int displayId,
             @Temperature.ThrottlingStatus int currentStatus) {
-        DisplayModeDirector.Vote vote = null;
+        Vote vote = null;
         if (currentStatus >= Temperature.THROTTLING_CRITICAL) {
-            vote = DisplayModeDirector.Vote.forRenderFrameRates(0f, 60f);
+            vote = Vote.forRenderFrameRates(0f, 60f);
         }
-        mBallotBox.vote(displayId, DisplayModeDirector.Vote.PRIORITY_SKIN_TEMPERATURE, vote);
+        mVotesStorage.updateVote(displayId, Vote.PRIORITY_SKIN_TEMPERATURE, vote);
         if (mLoggingEnabled) {
             Slog.d(TAG, "Voted(fallback): vote=" + vote + ", display =" + displayId);
         }
diff --git a/services/core/java/com/android/server/display/mode/Vote.java b/services/core/java/com/android/server/display/mode/Vote.java
new file mode 100644
index 0000000..a42d8f2
--- /dev/null
+++ b/services/core/java/com/android/server/display/mode/Vote.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2023 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.mode;
+
+import android.view.SurfaceControl;
+
+final class Vote {
+    // DEFAULT_RENDER_FRAME_RATE votes for render frame rate [0, DEFAULT]. As the lowest
+    // priority vote, it's overridden by all other considerations. It acts to set a default
+    // frame rate for a device.
+    static final int PRIORITY_DEFAULT_RENDER_FRAME_RATE = 0;
+
+    // PRIORITY_FLICKER_REFRESH_RATE votes for a single refresh rate like [60,60], [90,90] or
+    // null. It is used to set a preferred refresh rate value in case the higher priority votes
+    // result is a range.
+    static final int PRIORITY_FLICKER_REFRESH_RATE = 1;
+
+    // High-brightness-mode may need a specific range of refresh-rates to function properly.
+    static final int PRIORITY_HIGH_BRIGHTNESS_MODE = 2;
+
+    // SETTING_MIN_RENDER_FRAME_RATE is used to propose a lower bound of the render frame rate.
+    // It votes [minRefreshRate, Float.POSITIVE_INFINITY]
+    static final int PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE = 3;
+
+    // APP_REQUEST_RENDER_FRAME_RATE_RANGE is used to for internal apps to limit the render
+    // frame rate in certain cases, mostly to preserve power.
+    // @see android.view.WindowManager.LayoutParams#preferredMinRefreshRate
+    // @see android.view.WindowManager.LayoutParams#preferredMaxRefreshRate
+    // It votes to [preferredMinRefreshRate, preferredMaxRefreshRate].
+    static final int PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE = 4;
+
+    // We split the app request into different priorities in case we can satisfy one desire
+    // without the other.
+
+    // Application can specify preferred refresh rate with below attrs.
+    // @see android.view.WindowManager.LayoutParams#preferredRefreshRate
+    // @see android.view.WindowManager.LayoutParams#preferredDisplayModeId
+    //
+    // When the app specifies a LayoutParams#preferredDisplayModeId, in addition to the
+    // refresh rate, it also chooses a preferred size (resolution) as part of the selected
+    // mode id. The app preference is then translated to APP_REQUEST_BASE_MODE_REFRESH_RATE and
+    // optionally to APP_REQUEST_SIZE as well, if a mode id was selected.
+    // The system also forces some apps like denylisted app to run at a lower refresh rate.
+    // @see android.R.array#config_highRefreshRateBlacklist
+    //
+    // When summarizing the votes and filtering the allowed display modes, these votes determine
+    // which mode id should be the base mode id to be sent to SurfaceFlinger:
+    // - APP_REQUEST_BASE_MODE_REFRESH_RATE is used to validate the vote summary. If a summary
+    //   includes a base mode refresh rate, but it is not in the refresh rate range, then the
+    //   summary is considered invalid so we could drop a lower priority vote and try again.
+    // - APP_REQUEST_SIZE is used to filter out display modes of a different size.
+    //
+    // The preferred refresh rate is set on the main surface of the app outside of
+    // DisplayModeDirector.
+    // @see com.android.server.wm.WindowState#updateFrameRateSelectionPriorityIfNeeded
+    static final int PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE = 5;
+    static final int PRIORITY_APP_REQUEST_SIZE = 6;
+
+    // SETTING_PEAK_RENDER_FRAME_RATE has a high priority and will restrict the bounds of the
+    // rest of low priority voters. It votes [0, max(PEAK, MIN)]
+    static final int PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE = 7;
+
+    // To avoid delay in switching between 60HZ -> 90HZ when activating LHBM, set refresh
+    // rate to max value (same as for PRIORITY_UDFPS) on lock screen
+    static final int PRIORITY_AUTH_OPTIMIZER_RENDER_FRAME_RATE = 8;
+
+    // For concurrent displays we want to limit refresh rate on all displays
+    static final int PRIORITY_LAYOUT_LIMITED_FRAME_RATE = 9;
+
+    // LOW_POWER_MODE force the render frame rate to [0, 60HZ] if
+    // Settings.Global.LOW_POWER_MODE is on.
+    static final int PRIORITY_LOW_POWER_MODE = 10;
+
+    // PRIORITY_FLICKER_REFRESH_RATE_SWITCH votes for disabling refresh rate switching. If the
+    // higher priority voters' result is a range, it will fix the rate to a single choice.
+    // It's used to avoid refresh rate switches in certain conditions which may result in the
+    // user seeing the display flickering when the switches occur.
+    static final int PRIORITY_FLICKER_REFRESH_RATE_SWITCH = 11;
+
+    // Force display to [0, 60HZ] if skin temperature is at or above CRITICAL.
+    static final int PRIORITY_SKIN_TEMPERATURE = 12;
+
+    // The proximity sensor needs the refresh rate to be locked in order to function, so this is
+    // set to a high priority.
+    static final int PRIORITY_PROXIMITY = 13;
+
+    // The Under-Display Fingerprint Sensor (UDFPS) needs the refresh rate to be locked in order
+    // to function, so this needs to be the highest priority of all votes.
+    static final int PRIORITY_UDFPS = 14;
+
+    // Whenever a new priority is added, remember to update MIN_PRIORITY, MAX_PRIORITY, and
+    // APP_REQUEST_REFRESH_RATE_RANGE_PRIORITY_CUTOFF, as well as priorityToString.
+
+    static final int MIN_PRIORITY = PRIORITY_DEFAULT_RENDER_FRAME_RATE;
+    static final int MAX_PRIORITY = PRIORITY_UDFPS;
+
+    // The cutoff for the app request refresh rate range. Votes with priorities lower than this
+    // value will not be considered when constructing the app request refresh rate range.
+    static final int APP_REQUEST_REFRESH_RATE_RANGE_PRIORITY_CUTOFF =
+            PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE;
+
+    /**
+     * A value signifying an invalid width or height in a vote.
+     */
+    static final int INVALID_SIZE = -1;
+
+    /**
+     * The requested width of the display in pixels, or INVALID_SIZE;
+     */
+    public final int width;
+    /**
+     * The requested height of the display in pixels, or INVALID_SIZE;
+     */
+    public final int height;
+    /**
+     * Information about the refresh rate frame rate ranges DM would like to set the display to.
+     */
+    public final SurfaceControl.RefreshRateRanges refreshRateRanges;
+
+    /**
+     * Whether refresh rate switching should be disabled (i.e. the refresh rate range is
+     * a single value).
+     */
+    public final boolean disableRefreshRateSwitching;
+
+    /**
+     * The preferred refresh rate selected by the app. It is used to validate that the summary
+     * refresh rate ranges include this value, and are not restricted by a lower priority vote.
+     */
+    public final float appRequestBaseModeRefreshRate;
+
+    static Vote forPhysicalRefreshRates(float minRefreshRate, float maxRefreshRate) {
+        return new Vote(INVALID_SIZE, INVALID_SIZE, minRefreshRate, maxRefreshRate, 0,
+                Float.POSITIVE_INFINITY,
+                minRefreshRate == maxRefreshRate, 0f);
+    }
+
+    static Vote forRenderFrameRates(float minFrameRate, float maxFrameRate) {
+        return new Vote(INVALID_SIZE, INVALID_SIZE, 0, Float.POSITIVE_INFINITY, minFrameRate,
+                maxFrameRate,
+                false, 0f);
+    }
+
+    static Vote forSize(int width, int height) {
+        return new Vote(width, height, 0, Float.POSITIVE_INFINITY, 0, Float.POSITIVE_INFINITY,
+                false,
+                0f);
+    }
+
+    static Vote forDisableRefreshRateSwitching() {
+        return new Vote(INVALID_SIZE, INVALID_SIZE, 0, Float.POSITIVE_INFINITY, 0,
+                Float.POSITIVE_INFINITY, true,
+                0f);
+    }
+
+    static Vote forBaseModeRefreshRate(float baseModeRefreshRate) {
+        return new Vote(INVALID_SIZE, INVALID_SIZE, 0, Float.POSITIVE_INFINITY, 0,
+                Float.POSITIVE_INFINITY, false,
+                baseModeRefreshRate);
+    }
+
+    private Vote(int width, int height,
+            float minPhysicalRefreshRate,
+            float maxPhysicalRefreshRate,
+            float minRenderFrameRate,
+            float maxRenderFrameRate,
+            boolean disableRefreshRateSwitching,
+            float baseModeRefreshRate) {
+        this.width = width;
+        this.height = height;
+        this.refreshRateRanges = new SurfaceControl.RefreshRateRanges(
+                new SurfaceControl.RefreshRateRange(minPhysicalRefreshRate, maxPhysicalRefreshRate),
+                new SurfaceControl.RefreshRateRange(minRenderFrameRate, maxRenderFrameRate));
+        this.disableRefreshRateSwitching = disableRefreshRateSwitching;
+        this.appRequestBaseModeRefreshRate = baseModeRefreshRate;
+    }
+
+    static String priorityToString(int priority) {
+        switch (priority) {
+            case PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE:
+                return "PRIORITY_APP_REQUEST_BASE_MODE_REFRESH_RATE";
+            case PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE:
+                return "PRIORITY_APP_REQUEST_RENDER_FRAME_RATE_RANGE";
+            case PRIORITY_APP_REQUEST_SIZE:
+                return "PRIORITY_APP_REQUEST_SIZE";
+            case PRIORITY_DEFAULT_RENDER_FRAME_RATE:
+                return "PRIORITY_DEFAULT_REFRESH_RATE";
+            case PRIORITY_FLICKER_REFRESH_RATE:
+                return "PRIORITY_FLICKER_REFRESH_RATE";
+            case PRIORITY_FLICKER_REFRESH_RATE_SWITCH:
+                return "PRIORITY_FLICKER_REFRESH_RATE_SWITCH";
+            case PRIORITY_HIGH_BRIGHTNESS_MODE:
+                return "PRIORITY_HIGH_BRIGHTNESS_MODE";
+            case PRIORITY_PROXIMITY:
+                return "PRIORITY_PROXIMITY";
+            case PRIORITY_LOW_POWER_MODE:
+                return "PRIORITY_LOW_POWER_MODE";
+            case PRIORITY_SKIN_TEMPERATURE:
+                return "PRIORITY_SKIN_TEMPERATURE";
+            case PRIORITY_UDFPS:
+                return "PRIORITY_UDFPS";
+            case PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE:
+                return "PRIORITY_USER_SETTING_MIN_RENDER_FRAME_RATE";
+            case PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE:
+                return "PRIORITY_USER_SETTING_PEAK_RENDER_FRAME_RATE";
+            case PRIORITY_AUTH_OPTIMIZER_RENDER_FRAME_RATE:
+                return "PRIORITY_AUTH_OPTIMIZER_RENDER_FRAME_RATE";
+            case PRIORITY_LAYOUT_LIMITED_FRAME_RATE:
+                return "PRIORITY_LAYOUT_LIMITED_FRAME_RATE";
+            default:
+                return Integer.toString(priority);
+        }
+    }
+
+    @Override
+    public String toString() {
+        return "Vote: {"
+                + "width: " + width + ", height: " + height
+                + ", refreshRateRanges: " + refreshRateRanges
+                + ", disableRefreshRateSwitching: " + disableRefreshRateSwitching
+                + ", appRequestBaseModeRefreshRate: "  + appRequestBaseModeRefreshRate + "}";
+    }
+}
diff --git a/services/core/java/com/android/server/display/mode/VotesStorage.java b/services/core/java/com/android/server/display/mode/VotesStorage.java
new file mode 100644
index 0000000..dadcebe
--- /dev/null
+++ b/services/core/java/com/android/server/display/mode/VotesStorage.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2023 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.mode;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.util.Slog;
+import android.util.SparseArray;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.io.PrintWriter;
+
+class VotesStorage {
+    private static final String TAG = "VotesStorage";
+    // Special ID used to indicate that given vote is to be applied globally, rather than to a
+    // specific display.
+    private static final int GLOBAL_ID = -1;
+
+    private boolean mLoggingEnabled;
+
+    private final Listener mListener;
+
+    private final Object mStorageLock = new Object();
+    // A map from the display ID to the collection of votes and their priority. The latter takes
+    // the form of another map from the priority to the vote itself so that each priority is
+    // guaranteed to have exactly one vote, which is also easily and efficiently replaceable.
+    @GuardedBy("mStorageLock")
+    private final SparseArray<SparseArray<Vote>> mVotesByDisplay = new SparseArray<>();
+
+    VotesStorage(@NonNull Listener listener) {
+        mListener = listener;
+    }
+    /** sets logging enabled/disabled for this class */
+    void setLoggingEnabled(boolean loggingEnabled) {
+        mLoggingEnabled = loggingEnabled;
+    }
+    /**
+     * gets all votes for specific display, note that global display votes are also added to result
+     */
+    @NonNull
+    SparseArray<Vote> getVotes(int displayId) {
+        SparseArray<Vote> votesLocal;
+        SparseArray<Vote> globalVotesLocal;
+        synchronized (mStorageLock) {
+            SparseArray<Vote> displayVotes = mVotesByDisplay.get(displayId);
+            votesLocal = displayVotes != null ? displayVotes.clone() : new SparseArray<>();
+            SparseArray<Vote> globalVotes = mVotesByDisplay.get(GLOBAL_ID);
+            globalVotesLocal = globalVotes != null ? globalVotes.clone() : new SparseArray<>();
+        }
+        for (int i = 0; i < globalVotesLocal.size(); i++) {
+            int priority = globalVotesLocal.keyAt(i);
+            if (!votesLocal.contains(priority)) {
+                votesLocal.put(priority, globalVotesLocal.valueAt(i));
+            }
+        }
+        return votesLocal;
+    }
+
+    /** updates vote storage for all displays */
+    void updateGlobalVote(int priority, @Nullable Vote vote) {
+        updateVote(GLOBAL_ID, priority, vote);
+    }
+
+    /** updates vote storage */
+    void updateVote(int displayId, int priority, @Nullable Vote vote) {
+        if (mLoggingEnabled) {
+            Slog.i(TAG, "updateVoteLocked(displayId=" + displayId
+                    + ", priority=" + Vote.priorityToString(priority)
+                    + ", vote=" + vote + ")");
+        }
+        if (priority < Vote.MIN_PRIORITY || priority > Vote.MAX_PRIORITY) {
+            Slog.w(TAG, "Received a vote with an invalid priority, ignoring:"
+                    + " priority=" + Vote.priorityToString(priority)
+                    + ", vote=" + vote);
+            return;
+        }
+        SparseArray<Vote> votes;
+        synchronized (mStorageLock) {
+            if (mVotesByDisplay.contains(displayId)) {
+                votes = mVotesByDisplay.get(displayId);
+            } else {
+                votes = new SparseArray<>();
+                mVotesByDisplay.put(displayId, votes);
+            }
+            if (vote != null) {
+                votes.put(priority, vote);
+            } else {
+                votes.remove(priority);
+            }
+        }
+        if (mLoggingEnabled) {
+            Slog.i(TAG, "Updated votes for display=" + displayId + " votes=" + votes);
+        }
+        mListener.onChanged();
+    }
+
+    /** dump class values, for debugging */
+    void dump(@NonNull PrintWriter pw) {
+        SparseArray<SparseArray<Vote>> votesByDisplayLocal = new SparseArray<>();
+        synchronized (mStorageLock) {
+            for (int i = 0; i < mVotesByDisplay.size(); i++) {
+                votesByDisplayLocal.put(mVotesByDisplay.keyAt(i),
+                        mVotesByDisplay.valueAt(i).clone());
+            }
+        }
+        pw.println("  mVotesByDisplay:");
+        for (int i = 0; i < votesByDisplayLocal.size(); i++) {
+            SparseArray<Vote> votes = votesByDisplayLocal.valueAt(i);
+            if (votes.size() == 0) {
+                continue;
+            }
+            pw.println("    " + votesByDisplayLocal.keyAt(i) + ":");
+            for (int p = Vote.MAX_PRIORITY; p >= Vote.MIN_PRIORITY; p--) {
+                Vote vote = votes.get(p);
+                if (vote == null) {
+                    continue;
+                }
+                pw.println("      " + Vote.priorityToString(p) + " -> " + vote);
+            }
+        }
+    }
+
+    @VisibleForTesting
+    void injectVotesByDisplay(SparseArray<SparseArray<Vote>> votesByDisplay) {
+        synchronized (mStorageLock) {
+            mVotesByDisplay.clear();
+            for (int i = 0; i < votesByDisplay.size(); i++) {
+                mVotesByDisplay.put(votesByDisplay.keyAt(i), votesByDisplay.valueAt(i));
+            }
+        }
+    }
+
+    interface Listener {
+        void onChanged();
+    }
+}
diff --git a/services/core/java/com/android/server/input/KeyboardBacklightController.java b/services/core/java/com/android/server/input/KeyboardBacklightController.java
index 048308e..48c346a 100644
--- a/services/core/java/com/android/server/input/KeyboardBacklightController.java
+++ b/services/core/java/com/android/server/input/KeyboardBacklightController.java
@@ -199,8 +199,11 @@
         }
         if (brightness.isPresent()) {
             int brightnessValue = Math.max(0, Math.min(MAX_BRIGHTNESS, brightness.getAsInt()));
-            int brightnessLevel = Arrays.binarySearch(BRIGHTNESS_VALUE_FOR_LEVEL, brightnessValue);
-            updateBacklightState(inputDevice.getId(), keyboardBacklight, brightnessLevel,
+            int index = Arrays.binarySearch(BRIGHTNESS_VALUE_FOR_LEVEL, brightnessValue);
+            if (index < 0) {
+                index = Math.min(NUM_BRIGHTNESS_CHANGE_STEPS, -(index + 1));
+            }
+            updateBacklightState(inputDevice.getId(), keyboardBacklight, index,
                     false /* isTriggeredByKeyPress */);
             if (DEBUG) {
                 Slog.d(TAG, "Restoring brightness level " + brightness.getAsInt());
diff --git a/services/core/java/com/android/server/input/KeyboardLayoutManager.java b/services/core/java/com/android/server/input/KeyboardLayoutManager.java
index 72c7dad..d8716b3 100644
--- a/services/core/java/com/android/server/input/KeyboardLayoutManager.java
+++ b/services/core/java/com/android/server/input/KeyboardLayoutManager.java
@@ -16,6 +16,8 @@
 
 package com.android.server.input;
 
+import android.annotation.AnyThread;
+import android.annotation.MainThread;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.UserIdInt;
@@ -99,6 +101,7 @@
     private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
     private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
     private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
+    private static final int MSG_CURRENT_IME_INFO_CHANGED = 5;
 
     private final Context mContext;
     private final NativeInputManagerService mNative;
@@ -108,16 +111,17 @@
     private final Handler mHandler;
 
     // Connected keyboards with associated keyboard layouts (either auto-detected or manually
-    // selected layout). If the mapped value is null/empty, it means that no layout has been
-    // configured for the keyboard and user might need to manually configure it from the Settings.
-    private final SparseArray<Set<String>> mConfiguredKeyboards = new SparseArray<>();
+    // selected layout).
+    private final SparseArray<KeyboardConfiguration> mConfiguredKeyboards = new SparseArray<>();
     private Toast mSwitchedKeyboardLayoutToast;
 
     // This cache stores "best-matched" layouts so that we don't need to run the matching
     // algorithm repeatedly.
     @GuardedBy("mKeyboardLayoutCache")
     private final Map<String, String> mKeyboardLayoutCache = new ArrayMap<>();
+    private final Object mImeInfoLock = new Object();
     @Nullable
+    @GuardedBy("mImeInfoLock")
     private ImeInfo mCurrentImeInfo;
 
     KeyboardLayoutManager(Context context, NativeInputManagerService nativeService,
@@ -155,26 +159,32 @@
     }
 
     @Override
+    @MainThread
     public void onInputDeviceAdded(int deviceId) {
         onInputDeviceChanged(deviceId);
-        if (useNewSettingsUi()) {
-            // Force native callback to set up keyboard layout overlay for newly added keyboards
-            reloadKeyboardLayouts();
-        }
     }
 
     @Override
+    @MainThread
     public void onInputDeviceRemoved(int deviceId) {
         mConfiguredKeyboards.remove(deviceId);
         maybeUpdateNotification();
     }
 
     @Override
+    @MainThread
     public void onInputDeviceChanged(int deviceId) {
         final InputDevice inputDevice = getInputDevice(deviceId);
         if (inputDevice == null || inputDevice.isVirtual() || !inputDevice.isFullKeyboard()) {
             return;
         }
+        KeyboardConfiguration config = mConfiguredKeyboards.get(deviceId);
+        if (config == null) {
+            config = new KeyboardConfiguration();
+            mConfiguredKeyboards.put(deviceId, config);
+        }
+
+        boolean needToShowNotification = false;
         if (!useNewSettingsUi()) {
             synchronized (mDataStore) {
                 String layout = getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
@@ -182,54 +192,66 @@
                     layout = getDefaultKeyboardLayout(inputDevice);
                     if (layout != null) {
                         setCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier(), layout);
-                    } else {
-                        mConfiguredKeyboards.put(inputDevice.getId(), new HashSet<>());
                     }
                 }
+                config.setCurrentLayout(layout);
+                if (layout == null) {
+                    // In old settings show notification always until user manually selects a
+                    // layout in the settings.
+                    needToShowNotification = true;
+                }
             }
         } else {
             final InputDeviceIdentifier identifier = inputDevice.getIdentifier();
             final String key = getLayoutDescriptor(identifier);
             Set<String> selectedLayouts = new HashSet<>();
-            boolean needToShowMissingLayoutNotification = false;
             for (ImeInfo imeInfo : getImeInfoListForLayoutMapping()) {
                 // Check if the layout has been previously configured
                 String layout = getKeyboardLayoutForInputDeviceInternal(identifier,
                         new ImeInfo(imeInfo.mUserId, imeInfo.mImeSubtypeHandle,
                                 imeInfo.mImeSubtype));
                 if (layout == null) {
-                    needToShowMissingLayoutNotification = true;
-                    continue;
+                    // If even one layout not configured properly, we need to ask user to configure
+                    // the keyboard properly from the Settings.
+                    selectedLayouts.clear();
+                    break;
                 }
                 selectedLayouts.add(layout);
             }
 
-            if (needToShowMissingLayoutNotification) {
-                // If even one layout not configured properly we will show configuration
-                // notification allowing user to set the keyboard layout.
-                selectedLayouts.clear();
-            }
-
             if (DEBUG) {
                 Slog.d(TAG,
                         "Layouts selected for input device: " + identifier + " -> selectedLayouts: "
                                 + selectedLayouts);
             }
-            mConfiguredKeyboards.set(inputDevice.getId(), selectedLayouts);
+
+            config.setConfiguredLayouts(selectedLayouts);
+
+            // Update current layout: If there is a change then need to reload.
+            synchronized (mImeInfoLock) {
+                String layout = getKeyboardLayoutForInputDeviceInternal(
+                        inputDevice.getIdentifier(), mCurrentImeInfo);
+                if (!Objects.equals(layout, config.getCurrentLayout())) {
+                    config.setCurrentLayout(layout);
+                    mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
+                }
+            }
 
             synchronized (mDataStore) {
                 try {
-                    if (!mDataStore.setSelectedKeyboardLayouts(key, selectedLayouts)) {
-                        // No need to show the notification only if layout selection didn't change
+                    if (mDataStore.setSelectedKeyboardLayouts(key, selectedLayouts)) {
+                        // Need to show the notification only if layout selection changed
                         // from the previous configuration
-                        return;
+                        needToShowNotification = true;
                     }
                 } finally {
                     mDataStore.saveIfNeeded();
                 }
             }
         }
-        maybeUpdateNotification();
+        if (needToShowNotification) {
+            maybeUpdateNotification();
+        }
     }
 
     private String getDefaultKeyboardLayout(final InputDevice inputDevice) {
@@ -323,12 +345,14 @@
         reloadKeyboardLayouts();
     }
 
+    @AnyThread
     public KeyboardLayout[] getKeyboardLayouts() {
         final ArrayList<KeyboardLayout> list = new ArrayList<>();
         visitAllKeyboardLayouts((resources, keyboardLayoutResId, layout) -> list.add(layout));
         return list.toArray(new KeyboardLayout[0]);
     }
 
+    @AnyThread
     public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
             final InputDeviceIdentifier identifier) {
         if (useNewSettingsUi()) {
@@ -375,6 +399,7 @@
                 KeyboardLayout[]::new);
     }
 
+    @AnyThread
     @Nullable
     public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
         Objects.requireNonNull(keyboardLayoutDescriptor,
@@ -543,6 +568,7 @@
         return key.toString();
     }
 
+    @AnyThread
     @Nullable
     public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
         if (useNewSettingsUi()) {
@@ -566,6 +592,7 @@
         }
     }
 
+    @AnyThread
     public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
             String keyboardLayoutDescriptor) {
         if (useNewSettingsUi()) {
@@ -592,6 +619,7 @@
         }
     }
 
+    @AnyThread
     public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
         if (useNewSettingsUi()) {
             Slog.e(TAG, "getEnabledKeyboardLayoutsForInputDevice API not supported");
@@ -608,6 +636,7 @@
         }
     }
 
+    @AnyThread
     public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
             String keyboardLayoutDescriptor) {
         if (useNewSettingsUi()) {
@@ -635,6 +664,7 @@
         }
     }
 
+    @AnyThread
     public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
             String keyboardLayoutDescriptor) {
         if (useNewSettingsUi()) {
@@ -667,6 +697,7 @@
         }
     }
 
+    @AnyThread
     public void switchKeyboardLayout(int deviceId, int direction) {
         if (useNewSettingsUi()) {
             Slog.e(TAG, "switchKeyboardLayout API not supported");
@@ -675,7 +706,7 @@
         mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
     }
 
-    // Must be called on handler.
+    @MainThread
     private void handleSwitchKeyboardLayout(int deviceId, int direction) {
         final InputDevice device = getInputDevice(deviceId);
         if (device != null) {
@@ -713,23 +744,14 @@
     }
 
     @Nullable
+    @AnyThread
     public String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
         String keyboardLayoutDescriptor;
         if (useNewSettingsUi()) {
-            InputDevice inputDevice = getInputDevice(identifier);
-            if (inputDevice == null) {
-                // getKeyboardLayoutOverlay() called before input device added completely. Need
-                // to wait till the device is added which will call reloadKeyboardLayouts()
-                return null;
+            synchronized (mImeInfoLock) {
+                keyboardLayoutDescriptor = getKeyboardLayoutForInputDeviceInternal(identifier,
+                        mCurrentImeInfo);
             }
-            if (mCurrentImeInfo == null) {
-                // Haven't received onInputMethodSubtypeChanged() callback from IMMS. Will reload
-                // keyboard layouts once we receive the callback.
-                return null;
-            }
-
-            keyboardLayoutDescriptor = getKeyboardLayoutForInputDeviceInternal(identifier,
-                    mCurrentImeInfo);
         } else {
             keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
         }
@@ -755,6 +777,7 @@
         return result;
     }
 
+    @AnyThread
     @Nullable
     public String getKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
             @UserIdInt int userId, @NonNull InputMethodInfo imeInfo,
@@ -773,6 +796,7 @@
         return layout;
     }
 
+    @AnyThread
     public void setKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
             @UserIdInt int userId, @NonNull InputMethodInfo imeInfo,
             @Nullable InputMethodSubtype imeSubtype,
@@ -783,8 +807,8 @@
         }
         Objects.requireNonNull(keyboardLayoutDescriptor,
                 "keyboardLayoutDescriptor must not be null");
-        String key = createLayoutKey(identifier, userId,
-                InputMethodSubtypeHandle.of(imeInfo, imeSubtype));
+        String key = createLayoutKey(identifier,
+                new ImeInfo(userId, InputMethodSubtypeHandle.of(imeInfo, imeSubtype), imeSubtype));
         synchronized (mDataStore) {
             try {
                 // Key for storing into data store = <device descriptor>,<userId>,<subtypeHandle>
@@ -803,6 +827,7 @@
         }
     }
 
+    @AnyThread
     public KeyboardLayout[] getKeyboardLayoutListForInputDevice(InputDeviceIdentifier identifier,
             @UserIdInt int userId, @NonNull InputMethodInfo imeInfo,
             @Nullable InputMethodSubtype imeSubtype) {
@@ -815,8 +840,8 @@
     }
 
     private KeyboardLayout[] getKeyboardLayoutListForInputDeviceInternal(
-            InputDeviceIdentifier identifier, ImeInfo imeInfo) {
-        String key = createLayoutKey(identifier, imeInfo.mUserId, imeInfo.mImeSubtypeHandle);
+            InputDeviceIdentifier identifier, @Nullable ImeInfo imeInfo) {
+        String key = createLayoutKey(identifier, imeInfo);
 
         // Fetch user selected layout and always include it in layout list.
         String userSelectedLayout;
@@ -826,7 +851,7 @@
 
         final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<>();
         String imeLanguageTag;
-        if (imeInfo.mImeSubtype == null) {
+        if (imeInfo == null || imeInfo.mImeSubtype == null) {
             imeLanguageTag = "";
         } else {
             ULocale imeLocale = imeInfo.mImeSubtype.getPhysicalKeyboardHintLanguageTag();
@@ -866,6 +891,7 @@
         return potentialLayouts.toArray(new KeyboardLayout[0]);
     }
 
+    @AnyThread
     public void onInputMethodSubtypeChanged(@UserIdInt int userId,
             @Nullable InputMethodSubtypeHandle subtypeHandle,
             @Nullable InputMethodSubtype subtype) {
@@ -879,25 +905,45 @@
             }
             return;
         }
-        if (mCurrentImeInfo == null || !subtypeHandle.equals(mCurrentImeInfo.mImeSubtypeHandle)
-                || mCurrentImeInfo.mUserId != userId) {
-            mCurrentImeInfo = new ImeInfo(userId, subtypeHandle, subtype);
-            mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
-            if (DEBUG) {
-                Slog.d(TAG, "InputMethodSubtype changed: userId=" + userId
-                        + " subtypeHandle=" + subtypeHandle);
+        synchronized (mImeInfoLock) {
+            if (mCurrentImeInfo == null || !subtypeHandle.equals(mCurrentImeInfo.mImeSubtypeHandle)
+                    || mCurrentImeInfo.mUserId != userId) {
+                mCurrentImeInfo = new ImeInfo(userId, subtypeHandle, subtype);
+                mHandler.sendEmptyMessage(MSG_CURRENT_IME_INFO_CHANGED);
+                if (DEBUG) {
+                    Slog.d(TAG, "InputMethodSubtype changed: userId=" + userId
+                            + " subtypeHandle=" + subtypeHandle);
+                }
+            }
+        }
+    }
+
+    @MainThread
+    private void onCurrentImeInfoChanged() {
+        synchronized (mImeInfoLock) {
+            for (int i = 0; i < mConfiguredKeyboards.size(); i++) {
+                InputDevice inputDevice = Objects.requireNonNull(
+                        getInputDevice(mConfiguredKeyboards.keyAt(i)));
+                String layout = getKeyboardLayoutForInputDeviceInternal(inputDevice.getIdentifier(),
+                        mCurrentImeInfo);
+                KeyboardConfiguration config = mConfiguredKeyboards.valueAt(i);
+                if (!Objects.equals(layout, config.getCurrentLayout())) {
+                    config.setCurrentLayout(layout);
+                    mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
+                    return;
+                }
             }
         }
     }
 
     @Nullable
     private String getKeyboardLayoutForInputDeviceInternal(InputDeviceIdentifier identifier,
-            ImeInfo imeInfo) {
+            @Nullable ImeInfo imeInfo) {
         InputDevice inputDevice = getInputDevice(identifier);
         if (inputDevice == null || inputDevice.isVirtual() || !inputDevice.isFullKeyboard()) {
             return null;
         }
-        String key = createLayoutKey(identifier, imeInfo.mUserId, imeInfo.mImeSubtypeHandle);
+        String key = createLayoutKey(identifier, imeInfo);
         String layout;
         synchronized (mDataStore) {
             layout = mDataStore.getKeyboardLayout(getLayoutDescriptor(identifier), key);
@@ -923,11 +969,7 @@
 
     @Nullable
     private static String getDefaultKeyboardLayoutBasedOnImeInfo(InputDevice inputDevice,
-            ImeInfo imeInfo, KeyboardLayout[] layoutList) {
-        if (imeInfo.mImeSubtypeHandle == null) {
-            return null;
-        }
-
+            @Nullable ImeInfo imeInfo, KeyboardLayout[] layoutList) {
         Arrays.sort(layoutList);
 
         // Check <VendorID, ProductID> matching for explicitly declared custom KCM files.
@@ -961,12 +1003,12 @@
             }
         }
 
-        InputMethodSubtype subtype = imeInfo.mImeSubtype;
-        // Can't auto select layout based on IME if subtype or language tag is null
-        if (subtype == null) {
+        if (imeInfo == null || imeInfo.mImeSubtypeHandle == null || imeInfo.mImeSubtype == null) {
+            // Can't auto select layout based on IME info is null
             return null;
         }
 
+        InputMethodSubtype subtype = imeInfo.mImeSubtype;
         // Check layout type, language tag information from IME for matching
         ULocale pkLocale = subtype.getPhysicalKeyboardHintLanguageTag();
         String pkLanguageTag =
@@ -1043,6 +1085,7 @@
         mNative.reloadKeyboardLayouts();
     }
 
+    @MainThread
     private void maybeUpdateNotification() {
         if (mConfiguredKeyboards.size() == 0) {
             hideKeyboardLayoutNotification();
@@ -1051,7 +1094,7 @@
         for (int i = 0; i < mConfiguredKeyboards.size(); i++) {
             // If we have a keyboard with no selected layouts, we should always show missing
             // layout notification even if there are other keyboards that are configured properly.
-            if (mConfiguredKeyboards.valueAt(i).isEmpty()) {
+            if (!mConfiguredKeyboards.valueAt(i).hasConfiguredLayouts()) {
                 showMissingKeyboardLayoutNotification();
                 return;
             }
@@ -1059,7 +1102,7 @@
         showConfiguredKeyboardLayoutNotification();
     }
 
-    // Must be called on handler.
+    @MainThread
     private void showMissingKeyboardLayoutNotification() {
         final Resources r = mContext.getResources();
         final String missingKeyboardLayoutNotificationContent = r.getString(
@@ -1084,6 +1127,7 @@
         }
     }
 
+    @MainThread
     private void showKeyboardLayoutNotification(@NonNull String intentTitle,
             @NonNull String intentContent, @Nullable InputDevice targetDevice) {
         final NotificationManager notificationManager = mContext.getSystemService(
@@ -1119,7 +1163,7 @@
                 notification, UserHandle.ALL);
     }
 
-    // Must be called on handler.
+    @MainThread
     private void hideKeyboardLayoutNotification() {
         NotificationManager notificationManager = mContext.getSystemService(
                 NotificationManager.class);
@@ -1132,6 +1176,7 @@
                 UserHandle.ALL);
     }
 
+    @MainThread
     private void showConfiguredKeyboardLayoutNotification() {
         final Resources r = mContext.getResources();
 
@@ -1144,8 +1189,8 @@
         }
 
         final InputDevice inputDevice = getInputDevice(mConfiguredKeyboards.keyAt(0));
-        final Set<String> selectedLayouts = mConfiguredKeyboards.valueAt(0);
-        if (inputDevice == null || selectedLayouts == null || selectedLayouts.isEmpty()) {
+        final KeyboardConfiguration config = mConfiguredKeyboards.valueAt(0);
+        if (inputDevice == null || !config.hasConfiguredLayouts()) {
             return;
         }
 
@@ -1153,10 +1198,11 @@
                 r.getString(
                         R.string.keyboard_layout_notification_selected_title,
                         inputDevice.getName()),
-                createConfiguredNotificationText(mContext, selectedLayouts),
+                createConfiguredNotificationText(mContext, config.getConfiguredLayouts()),
                 inputDevice);
     }
 
+    @MainThread
     private String createConfiguredNotificationText(@NonNull Context context,
             @NonNull Set<String> selectedLayouts) {
         final Resources r = context.getResources();
@@ -1199,6 +1245,9 @@
             case MSG_UPDATE_KEYBOARD_LAYOUTS:
                 updateKeyboardLayouts();
                 return true;
+            case MSG_CURRENT_IME_INFO_CHANGED:
+                onCurrentImeInfoChanged();
+                return true;
             default:
                 return false;
         }
@@ -1252,17 +1301,19 @@
         return imeInfoList;
     }
 
-    private String createLayoutKey(InputDeviceIdentifier identifier, int userId,
-            @NonNull InputMethodSubtypeHandle subtypeHandle) {
-        Objects.requireNonNull(subtypeHandle, "subtypeHandle must not be null");
-        return "layoutDescriptor:" + getLayoutDescriptor(identifier) + ",userId:" + userId
-                + ",subtypeHandle:" + subtypeHandle.toStringHandle();
+    private String createLayoutKey(InputDeviceIdentifier identifier, @Nullable ImeInfo imeInfo) {
+        if (imeInfo == null) {
+            return getLayoutDescriptor(identifier);
+        }
+        Objects.requireNonNull(imeInfo.mImeSubtypeHandle, "subtypeHandle must not be null");
+        return "layoutDescriptor:" + getLayoutDescriptor(identifier) + ",userId:" + imeInfo.mUserId
+                + ",subtypeHandle:" + imeInfo.mImeSubtypeHandle.toStringHandle();
     }
 
     private static boolean isLayoutCompatibleWithLanguageTag(KeyboardLayout layout,
             @NonNull String languageTag) {
         LocaleList layoutLocales = layout.getLocales();
-        if (layoutLocales.isEmpty()) {
+        if (layoutLocales.isEmpty() || TextUtils.isEmpty(languageTag)) {
             // KCM file doesn't have an associated language tag. This can be from
             // a 3rd party app so need to include it as a potential layout.
             return true;
@@ -1350,6 +1401,39 @@
         }
     }
 
+    private static class KeyboardConfiguration {
+        // If null or empty, it means no layout is configured for the device. And user needs to
+        // manually set up the device.
+        @Nullable
+        private Set<String> mConfiguredLayouts;
+
+        // If null, it means no layout is selected for the device.
+        @Nullable
+        private String mCurrentLayout;
+
+        private boolean hasConfiguredLayouts() {
+            return mConfiguredLayouts != null && !mConfiguredLayouts.isEmpty();
+        }
+
+        @Nullable
+        private Set<String> getConfiguredLayouts() {
+            return mConfiguredLayouts;
+        }
+
+        private void setConfiguredLayouts(Set<String> configuredLayouts) {
+            mConfiguredLayouts = configuredLayouts;
+        }
+
+        @Nullable
+        private String getCurrentLayout() {
+            return mCurrentLayout;
+        }
+
+        private void setCurrentLayout(String currentLayout) {
+            mCurrentLayout = currentLayout;
+        }
+    }
+
     private interface KeyboardLayoutVisitor {
         void visitKeyboardLayout(Resources resources,
                 int keyboardLayoutResId, KeyboardLayout layout);
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 0532a79..247a5c0 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -2987,6 +2987,7 @@
                 }
                 break;
             case KeyEvent.KEYCODE_H:
+            case KeyEvent.KEYCODE_ENTER:
                 if (event.isMetaPressed()) {
                     return handleHomeShortcuts(displayId, focusedToken, event);
                 }
diff --git a/services/core/java/com/android/server/wm/ActivityClientController.java b/services/core/java/com/android/server/wm/ActivityClientController.java
index 8bbcd27..c40d72c 100644
--- a/services/core/java/com/android/server/wm/ActivityClientController.java
+++ b/services/core/java/com/android/server/wm/ActivityClientController.java
@@ -807,11 +807,8 @@
                 if (under != null) {
                     under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
                 }
-                // Create a transition if the activity is playing in case the current activity
-                // didn't commit invisible. That's because if this activity has changed its
-                // visibility while playing transition, there won't able to commit visibility until
-                // the running transition finish.
-                final Transition transition = r.mTransitionController.inPlayingTransition(r)
+                // Create a transition to make sure the activity change is collected.
+                final Transition transition = r.mTransitionController.isShellTransitionsEnabled()
                         && !r.mTransitionController.isCollecting()
                         ? r.mTransitionController.createTransition(TRANSIT_TO_FRONT) : null;
                 final boolean changed = r.setOccludesParent(false);
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index f478e9b..8bfa426 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -2267,6 +2267,12 @@
         if (cutout == null || cutout == DisplayCutout.NO_CUTOUT) {
             return WmDisplayCutout.NO_CUTOUT;
         }
+        if (displayWidth == displayHeight) {
+            Slog.w(TAG, "Ignore cutout because display size is square: " + displayWidth);
+            // Avoid UnsupportedOperationException because DisplayCutout#computeSafeInsets doesn't
+            // support square size.
+            return WmDisplayCutout.NO_CUTOUT;
+        }
         if (rotation == ROTATION_0) {
             return WmDisplayCutout.computeSafeInsets(
                     cutout, displayWidth, displayHeight);
@@ -3087,13 +3093,9 @@
 
         mIsSizeForced = mInitialDisplayWidth != width || mInitialDisplayHeight != height;
         if (mIsSizeForced) {
-            // Set some sort of reasonable bounds on the size of the display that we will try
-            // to emulate.
-            final int minSize = 200;
-            final int maxScale = 3;
-            final int maxSize = Math.max(mInitialDisplayWidth, mInitialDisplayHeight) * maxScale;
-            width = Math.min(Math.max(width, minSize), maxSize);
-            height = Math.min(Math.max(height, minSize), maxSize);
+            final Point size = getValidForcedSize(width, height);
+            width = size.x;
+            height = size.y;
         }
 
         Slog.i(TAG_WM, "Using new display size: " + width + "x" + height);
@@ -3108,6 +3110,16 @@
         mWmService.mDisplayWindowSettings.setForcedSize(this, width, height);
     }
 
+    /** Returns a reasonable size for setting forced display size. */
+    Point getValidForcedSize(int w, int h) {
+        final int minSize = 200;
+        final int maxScale = 3;
+        final int maxSize = Math.max(mInitialDisplayWidth, mInitialDisplayHeight) * maxScale;
+        w = Math.min(Math.max(w, minSize), maxSize);
+        h = Math.min(Math.max(h, minSize), maxSize);
+        return new Point(w, h);
+    }
+
     DisplayCutout loadDisplayCutout(int displayWidth, int displayHeight) {
         if (mDisplayPolicy == null || mInitialDisplayCutout == null) {
             return null;
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 8822193..40b8274 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -5780,10 +5780,12 @@
         if (sizeStr != null && sizeStr.length() > 0) {
             final int pos = sizeStr.indexOf(',');
             if (pos > 0 && sizeStr.lastIndexOf(',') == pos) {
-                int width, height;
                 try {
-                    width = Integer.parseInt(sizeStr.substring(0, pos));
-                    height = Integer.parseInt(sizeStr.substring(pos + 1));
+                    final Point size = displayContent.getValidForcedSize(
+                            Integer.parseInt(sizeStr.substring(0, pos)),
+                            Integer.parseInt(sizeStr.substring(pos + 1)));
+                    final int width = size.x;
+                    final int height = size.y;
                     if (displayContent.mBaseDisplayWidth != width
                             || displayContent.mBaseDisplayHeight != height) {
                         ProtoLog.i(WM_ERROR, "FORCED DISPLAY SIZE: %dx%d", width, height);
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index f6bc93a..23dc260 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -3575,7 +3575,9 @@
     void handleStartUser(int userId) {
         synchronized (getLockObject()) {
             pushScreenCapturePolicy(userId);
-            pushUserControlDisabledPackagesLocked(userId);
+            if (!isPolicyEngineForFinanceFlagEnabled()) {
+                pushUserControlDisabledPackagesLocked(userId);
+            }
         }
         pushUserRestrictions(userId);
         // When system user is started (device boot), load cache for all users.
@@ -6038,7 +6040,7 @@
     @Override
     public void lockNow(int flags, String callerPackageName, boolean parent) {
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(callerPackageName);
         } else {
             caller = getCallerIdentity();
@@ -6050,7 +6052,7 @@
             ActiveAdmin admin;
             // Make sure the caller has any active admin with the right policy or
             // the required permission.
-            if (isPermissionCheckFlagEnabled()) {
+            if (isPolicyEngineForFinanceFlagEnabled()) {
                 admin = enforcePermissionAndGetEnforcingAdmin(
                         /* admin= */ null,
                         /* permission= */ MANAGE_DEVICE_POLICY_LOCK,
@@ -8901,13 +8903,13 @@
         }
 
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             // The effect of this policy is device-wide.
             enforcePermission(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
         } else {
@@ -8935,13 +8937,13 @@
             return false;
         }
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             enforceCanQuery(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
         } else {
             Objects.requireNonNull(who, "ComponentName is null");
@@ -8970,7 +8972,7 @@
             caller = getCallerIdentity(who);
         }
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             // The effect of this policy is device-wide.
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     who,
@@ -9010,13 +9012,13 @@
         }
 
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             // The effect of this policy is device-wide.
             enforceCanQuery(SET_TIME_ZONE, caller.getPackageName(), UserHandle.USER_ALL);
         } else {
@@ -9319,7 +9321,7 @@
         }
 
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
@@ -9329,7 +9331,7 @@
         final int userHandle = caller.getUserId();
         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
         synchronized (getLockObject()) {
-            if (isPermissionCheckFlagEnabled()) {
+            if (isPolicyEngineForFinanceFlagEnabled()) {
                 // SUPPORT USES_POLICY_DISABLE_KEYGUARD_FEATURES
                 EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
                         who, MANAGE_DEVICE_POLICY_KEYGUARD, caller.getPackageName(),
@@ -9408,7 +9410,7 @@
 
         synchronized (getLockObject()) {
             if (who != null) {
-                if (isPermissionCheckFlagEnabled()) {
+                if (isPolicyEngineForFinanceFlagEnabled()) {
                     EnforcingAdmin admin = getEnforcingAdminForCaller(
                             who, who.getPackageName());
                     Integer features = mDevicePolicyEngine.getLocalPolicySetByAdmin(
@@ -9422,7 +9424,7 @@
                 }
             }
 
-            if (isPermissionCheckFlagEnabled()) {
+            if (isPolicyEngineForFinanceFlagEnabled()) {
                 Integer features = mDevicePolicyEngine.getResolvedPolicy(
                         PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
                         affectedUserId);
@@ -10062,7 +10064,9 @@
         setNetworkLoggingActiveInternal(false);
         deleteTransferOwnershipBundleLocked(userId);
         toggleBackupServiceActive(UserHandle.USER_SYSTEM, true);
-        pushUserControlDisabledPackagesLocked(userId);
+        if (!isPolicyEngineForFinanceFlagEnabled()) {
+            pushUserControlDisabledPackagesLocked(userId);
+        }
         setGlobalSettingDeviceOwnerType(DEVICE_OWNER_TYPE_DEFAULT);
 
         if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
@@ -11617,7 +11621,7 @@
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS);
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     who,
                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
@@ -12993,7 +12997,7 @@
             String packageName) {
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
                     who,
                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
@@ -13063,7 +13067,7 @@
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
         ActiveAdmin admin;
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     who,
                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
@@ -13160,7 +13164,7 @@
     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             enforcePermission(
                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
                     caller.getPackageName(),
@@ -13766,7 +13770,7 @@
             boolean hidden, boolean parent) {
         CallerIdentity caller = getCallerIdentity(who, callerPackage);
         final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             // TODO: We need to ensure the delegate with DELEGATION_PACKAGE_ACCESS can do this
             enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
         } else {
@@ -13785,7 +13789,7 @@
         boolean result;
         synchronized (getLockObject()) {
             if (parent) {
-                if (!isPermissionCheckFlagEnabled()) {
+                if (!isPolicyEngineForFinanceFlagEnabled()) {
                     Preconditions.checkCallAuthorization(
                             isProfileOwnerOfOrganizationOwnedDevice(
                                     caller.getUserId()) && isManagedProfile(caller.getUserId()));
@@ -13802,7 +13806,7 @@
                 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)",
                         packageName, hidden, userId);
             }
-            if (isPermissionCheckFlagEnabled()) {
+            if (isPolicyEngineForFinanceFlagEnabled()) {
                 EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
                 mDevicePolicyEngine.setLocalPolicy(
                         PolicyDefinition.APPLICATION_HIDDEN(packageName),
@@ -13841,7 +13845,7 @@
             String packageName, boolean parent) {
         CallerIdentity caller = getCallerIdentity(who, callerPackage);
         int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             // TODO: Also support DELEGATION_PACKAGE_ACCESS
             enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
         } else {
@@ -13853,7 +13857,7 @@
 
         synchronized (getLockObject()) {
             if (parent) {
-                if (!isPermissionCheckFlagEnabled()) {
+                if (!isPolicyEngineForFinanceFlagEnabled()) {
                     Preconditions.checkCallAuthorization(
                             isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId())
                                     && isManagedProfile(caller.getUserId()));
@@ -14042,13 +14046,13 @@
             return;
         }
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
         synchronized (getLockObject()) {
-            if (isPermissionCheckFlagEnabled()) {
+            if (isPolicyEngineForFinanceFlagEnabled()) {
                 int affectedUser = getAffectedUser(parent);
                 EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                         who,
@@ -14111,7 +14115,7 @@
         CallerIdentity caller;
         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
         final ArraySet<String> resultSet = new ArraySet<>();
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             int affectedUser = parent ? getProfileParentId(userId) : userId;
             caller = getCallerIdentity(callerPackageName);
             if (!hasPermission(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
@@ -14744,24 +14748,24 @@
             synchronized (getLockObject()) {
                 enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
             }
-            if (packages.length == 0) {
+            LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
+                    PolicyDefinition.LOCK_TASK,
+                    enforcingAdmin,
+                    caller.getUserId());
+            LockTaskPolicy policy;
+            if (currentPolicy == null) {
+                policy = new LockTaskPolicy(Set.of(packages));
+            } else {
+                policy = new LockTaskPolicy(currentPolicy);
+                policy.setPackages(Set.of(packages));
+            }
+            if (policy.getPackages().isEmpty()
+                    && policy.getFlags() == DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
                 mDevicePolicyEngine.removeLocalPolicy(
                         PolicyDefinition.LOCK_TASK,
                         enforcingAdmin,
                         caller.getUserId());
             } else {
-                LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
-                        PolicyDefinition.LOCK_TASK,
-                        enforcingAdmin,
-                        caller.getUserId());
-                LockTaskPolicy policy;
-                if (currentPolicy == null) {
-                    policy = new LockTaskPolicy(Set.of(packages));
-                } else {
-                    policy = new LockTaskPolicy(currentPolicy);
-                    policy.setPackages(Set.of(packages));
-                }
-
                 mDevicePolicyEngine.setLocalPolicy(
                         PolicyDefinition.LOCK_TASK,
                         enforcingAdmin,
@@ -14876,18 +14880,26 @@
                     PolicyDefinition.LOCK_TASK,
                     enforcingAdmin,
                     caller.getUserId());
+            LockTaskPolicy policy;
             if (currentPolicy == null) {
-                throw new IllegalArgumentException("Can't set a lock task flags without setting "
-                        + "lock task packages first.");
+                policy = new LockTaskPolicy(flags);
+            } else {
+                policy = new LockTaskPolicy(currentPolicy);
+                policy.setFlags(flags);
             }
-            LockTaskPolicy policy = new LockTaskPolicy(currentPolicy);
-            policy.setFlags(flags);
-
-            mDevicePolicyEngine.setLocalPolicy(
-                    PolicyDefinition.LOCK_TASK,
-                    enforcingAdmin,
-                    policy,
-                    caller.getUserId());
+            if (policy.getPackages().isEmpty()
+                    && policy.getFlags() == DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
+                mDevicePolicyEngine.removeLocalPolicy(
+                        PolicyDefinition.LOCK_TASK,
+                        enforcingAdmin,
+                        caller.getUserId());
+            } else {
+                mDevicePolicyEngine.setLocalPolicy(
+                        PolicyDefinition.LOCK_TASK,
+                        enforcingAdmin,
+                        policy,
+                        caller.getUserId());
+            }
         } else {
             Objects.requireNonNull(who, "ComponentName is null");
             synchronized (getLockObject()) {
@@ -14945,18 +14957,34 @@
                     continue;
                 }
 
-                final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
-                // TODO(b/278438525): handle in the policy engine
-                if (!lockTaskPackages.isEmpty()) {
-                    Slogf.d(LOG_TAG,
-                            "User id " + userId + " not affiliated. Clearing lock task packages");
-                    setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
-                }
-                final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
-                if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){
-                    Slogf.d(LOG_TAG,
-                            "User id " + userId + " not affiliated. Clearing lock task features");
-                    setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
+                if (isPolicyEngineForFinanceFlagEnabled()) {
+                    Map<EnforcingAdmin, PolicyValue<LockTaskPolicy>> policies =
+                            mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
+                                    PolicyDefinition.LOCK_TASK, userId);
+                    Set<EnforcingAdmin> admins = new HashSet<>(policies.keySet());
+                    for (EnforcingAdmin admin : admins) {
+                        if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
+                            mDevicePolicyEngine.removeLocalPolicy(
+                                    PolicyDefinition.LOCK_TASK, admin, userId);
+                        }
+                    }
+                } else {
+                    final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
+                    // TODO(b/278438525): handle in the policy engine
+                    if (!lockTaskPackages.isEmpty()) {
+                        Slogf.d(LOG_TAG,
+                                "User id " + userId
+                                        + " not affiliated. Clearing lock task packages");
+                        setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
+                    }
+                    final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
+                    if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
+                        Slogf.d(LOG_TAG,
+                                "User id " + userId
+                                        + " not affiliated. Clearing lock task features");
+                        setLockTaskFeaturesLocked(userId,
+                                DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
+                    }
                 }
             }
         });
@@ -15454,12 +15482,12 @@
     public boolean setStatusBarDisabled(ComponentName who, String callerPackageName,
             boolean disabled) {
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(who, callerPackageName);
         } else {
             caller = getCallerIdentity(who);
         }
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             enforcePermission(MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(),
                     UserHandle.USER_ALL);
         } else {
@@ -15470,7 +15498,7 @@
 
         int userId = caller.getUserId();
         synchronized (getLockObject()) {
-            if (!isPermissionCheckFlagEnabled()) {
+            if (!isPolicyEngineForFinanceFlagEnabled()) {
                 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
                         "Admin " + who + " is neither the device owner or affiliated "
                                 + "user's profile owner.");
@@ -15529,7 +15557,7 @@
     @Override
     public boolean isStatusBarDisabled(String callerPackage) {
         final CallerIdentity caller = getCallerIdentity(callerPackage);
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             enforceCanQuery(
                     MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(), caller.getUserId());
         } else {
@@ -15539,7 +15567,7 @@
 
         int userId = caller.getUserId();
         synchronized (getLockObject()) {
-            if (!isPermissionCheckFlagEnabled()) {
+            if (!isPolicyEngineForFinanceFlagEnabled()) {
                 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
                         "Admin " + callerPackage
                                 + " is neither the device owner or affiliated user's profile owner.");
@@ -16191,17 +16219,13 @@
                         deviceOwner.second);
                 return result;
             }
-        } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)
-                || DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
+        } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
             synchronized (getLockObject()) {
                 final DevicePolicyData policy = getUserData(userId);
                 final int N = policy.mAdminList.size();
                 for (int i = 0; i < N; i++) {
                     final ActiveAdmin admin = policy.mAdminList.get(i);
-                    if ((admin.disableCamera &&
-                            DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction))
-                            || (admin.disableScreenCapture && DevicePolicyManager
-                            .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
+                    if (admin.disableScreenCapture) {
                         result = new Bundle();
                         result.putInt(Intent.EXTRA_USER_ID, userId);
                         result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
@@ -16209,17 +16233,44 @@
                         return result;
                     }
                 }
-                // For the camera, a device owner on a different user can disable it globally,
-                // so we need an additional check.
-                if (result == null
-                        && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
-                    final ActiveAdmin admin = getDeviceOwnerAdminLocked();
-                    if (admin != null && admin.disableCamera) {
-                        result = new Bundle();
-                        result.putInt(Intent.EXTRA_USER_ID, mOwners.getDeviceOwnerUserId());
-                        result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
-                                admin.info.getComponent());
-                        return result;
+            }
+        } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
+            if (isPolicyEngineForFinanceFlagEnabled()) {
+                PolicyDefinition<Boolean> policyDefinition =
+                        PolicyDefinition.getPolicyDefinitionForUserRestriction(
+                                UserManager.DISALLOW_CAMERA);
+                Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
+                if (value != null && value) {
+                    result = new Bundle();
+                    result.putInt(Intent.EXTRA_USER_ID, userId);
+                    return result;
+                }
+            } else {
+                synchronized (getLockObject()) {
+                    final DevicePolicyData policy = getUserData(userId);
+                    final int N = policy.mAdminList.size();
+                    for (int i = 0; i < N; i++) {
+                        final ActiveAdmin admin = policy.mAdminList.get(i);
+                        if (admin.disableCamera) {
+                            result = new Bundle();
+                            result.putInt(Intent.EXTRA_USER_ID, userId);
+                            result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
+                                    admin.info.getComponent());
+                            return result;
+                        }
+                    }
+                    // For the camera, a device owner on a different user can disable it globally,
+                    // so we need an additional check.
+                    if (result == null
+                            && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
+                        final ActiveAdmin admin = getDeviceOwnerAdminLocked();
+                        if (admin != null && admin.disableCamera) {
+                            result = new Bundle();
+                            result.putInt(Intent.EXTRA_USER_ID, mOwners.getDeviceOwnerUserId());
+                            result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
+                                    admin.info.getComponent());
+                            return result;
+                        }
                     }
                 }
             }
@@ -16676,7 +16727,7 @@
             }
         }
         EnforcingAdmin enforcingAdmin;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
@@ -16847,7 +16898,7 @@
     public int getPermissionGrantState(ComponentName admin, String callerPackage,
             String packageName, String permission) throws RemoteException {
         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             enforceCanQuery(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, caller.getPackageName(),
                     caller.getUserId());
         } else {
@@ -18978,14 +19029,14 @@
             throw new IllegalArgumentException("token must be at least 32-byte long");
         }
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(admin, callerPackageName);
         } else {
             caller = getCallerIdentity(admin);
         }
         final int userId = caller.getUserId();
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
@@ -19041,7 +19092,7 @@
             return false;
         }
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(admin, callerPackageName);
         } else {
             caller = getCallerIdentity(admin);
@@ -19049,7 +19100,7 @@
         final int userId = caller.getUserId();
         boolean result = false;
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
@@ -19088,14 +19139,14 @@
             return false;
         }
         CallerIdentity caller;
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             caller = getCallerIdentity(admin, callerPackageName);
         } else {
             caller = getCallerIdentity(admin);
         }
         int userId = caller.getUserId();
 
-        if (isPermissionCheckFlagEnabled()) {
+        if (isPolicyEngineForFinanceFlagEnabled()) {
             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                     admin,
                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/LockTaskPolicySerializer.java b/services/devicepolicy/java/com/android/server/devicepolicy/LockTaskPolicySerializer.java
index 0f6f3c5..20bd2d7 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/LockTaskPolicySerializer.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/LockTaskPolicySerializer.java
@@ -42,10 +42,6 @@
     void saveToXml(PolicyKey policyKey, TypedXmlSerializer serializer,
             @NonNull LockTaskPolicy value) throws IOException {
         Objects.requireNonNull(value);
-        if (value.getPackages() == null || value.getPackages().isEmpty()) {
-            throw new IllegalArgumentException("Error saving LockTaskPolicy to file, lock task "
-                    + "packages must be present");
-        }
         serializer.attribute(
                 /* namespace= */ null,
                 ATTR_PACKAGES,
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java
index 12a8a75..289098e 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyEnforcerCallbacks.java
@@ -26,6 +26,7 @@
 import android.app.admin.PackagePolicyKey;
 import android.app.admin.PolicyKey;
 import android.app.admin.UserRestrictionPolicyKey;
+import android.app.usage.UsageStatsManagerInternal;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.IntentFilter;
@@ -38,6 +39,7 @@
 import android.permission.AdminPermissionControlParams;
 import android.permission.PermissionControllerManager;
 import android.provider.Settings;
+import android.util.ArraySet;
 import android.util.Slog;
 
 import com.android.server.LocalServices;
@@ -151,11 +153,15 @@
 
     static boolean setUserControlDisabledPackages(
             @Nullable Set<String> packages, int userId) {
-        Binder.withCleanCallingIdentity(() ->
-                LocalServices.getService(PackageManagerInternal.class)
-                        .setOwnerProtectedPackages(
-                                userId,
-                                packages == null ? null : packages.stream().toList()));
+        Binder.withCleanCallingIdentity(() -> {
+            LocalServices.getService(PackageManagerInternal.class)
+                    .setOwnerProtectedPackages(
+                            userId,
+                            packages == null ? null : packages.stream().toList());
+            LocalServices.getService(UsageStatsManagerInternal.class)
+                            .setAdminProtectedPackages(
+                            packages == null ? null : new ArraySet(packages), userId);
+        });
         return true;
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index d85db64b..34b88b0 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -1511,6 +1511,7 @@
      * Validates that when the device owner is removed, the reset password token is cleared
      */
     @Test
+    @Ignore("b/277916462")
     public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
         mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
         mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
@@ -2601,6 +2602,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetApplicationHiddenWithDO() throws Exception {
         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
         setupDeviceOwner();
@@ -2626,6 +2628,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetApplicationHiddenWithPOOfOrganizationOwnedDevice() throws Exception {
         final int MANAGED_PROFILE_USER_ID = CALLER_USER_HANDLE;
         final int MANAGED_PROFILE_ADMIN_UID =
@@ -4372,6 +4375,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetAutoTimeZoneEnabledModifiesSetting() throws Exception {
         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
         setupDeviceOwner();
@@ -4383,6 +4387,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetAutoTimeZoneEnabledWithPOOnUser0() throws Exception {
         mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
         setupProfileOwnerOnUser0();
@@ -4394,6 +4399,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetAutoTimeZoneEnabledFailWithPONotOnUser0() throws Exception {
         setupProfileOwner();
         assertExpectException(SecurityException.class, null,
@@ -4403,6 +4409,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetAutoTimeZoneEnabledWithPOOfOrganizationOwnedDevice() throws Exception {
         setupProfileOwner();
         configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE);
@@ -5376,6 +5383,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testResetPasswordWithToken() throws Exception {
         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
         setupDeviceOwner();
@@ -5410,6 +5418,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void resetPasswordWithToken_NumericPin() throws Exception {
         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
         setupDeviceOwner();
@@ -5430,6 +5439,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void resetPasswordWithToken_EmptyPassword() throws Exception {
         mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
         setupDeviceOwner();
@@ -7250,6 +7260,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testCanProfileOwnerResetPasswordWhenLocked() throws Exception {
         setDeviceEncryptionPerUser();
         setupProfileOwner();
@@ -7313,6 +7324,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetAccountTypesWithManagementDisabledOnManagedProfile() throws Exception {
         setupProfileOwner();
 
@@ -7332,6 +7344,7 @@
     }
 
     @Test
+    @Ignore("b/277916462")
     public void testSetAccountTypesWithManagementDisabledOnOrgOwnedManagedProfile()
             throws Exception {
         mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS);
diff --git a/services/tests/servicestests/src/com/android/server/display/LogicalDisplayTest.java b/services/tests/servicestests/src/com/android/server/display/LogicalDisplayTest.java
index ff89be7..5ea3029 100644
--- a/services/tests/servicestests/src/com/android/server/display/LogicalDisplayTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/LogicalDisplayTest.java
@@ -17,6 +17,8 @@
 package com.android.server.display;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.mock;
@@ -26,6 +28,7 @@
 
 import android.app.PropertyInvalidatedCache;
 import android.graphics.Point;
+import android.util.SparseArray;
 import android.view.Display;
 import android.view.DisplayInfo;
 import android.view.Surface;
@@ -47,6 +50,7 @@
     private static final int LAYER_STACK = 0;
     private static final int DISPLAY_WIDTH = 100;
     private static final int DISPLAY_HEIGHT = 200;
+    private static final int MODE_ID = 1;
 
     private LogicalDisplay mLogicalDisplay;
     private DisplayDevice mDisplayDevice;
@@ -65,6 +69,9 @@
         mDisplayDeviceInfo.height = DISPLAY_HEIGHT;
         mDisplayDeviceInfo.flags = DisplayDeviceInfo.FLAG_ROTATES_WITH_CONTENT;
         mDisplayDeviceInfo.touch = DisplayDeviceInfo.TOUCH_INTERNAL;
+        mDisplayDeviceInfo.modeId = MODE_ID;
+        mDisplayDeviceInfo.supportedModes = new Display.Mode[] {new Display.Mode(MODE_ID,
+                DISPLAY_WIDTH, DISPLAY_HEIGHT, /* refreshRate= */ 60)};
         when(mDisplayDevice.getDisplayDeviceInfoLocked()).thenReturn(mDisplayDeviceInfo);
 
         // Disable binder caches in this process.
@@ -168,14 +175,34 @@
     }
 
     @Test
-    public void testLayoutLimitedRefreshRateNotClearedAfterUpdate() {
-        SurfaceControl.RefreshRateRange refreshRateRange = new SurfaceControl.RefreshRateRange(1,
-                2);
-        mLogicalDisplay.updateLayoutLimitedRefreshRateLocked(refreshRateRange);
-        mLogicalDisplay.updateDisplayGroupIdLocked(1);
+    public void testUpdateLayoutLimitedRefreshRate() {
+        SurfaceControl.RefreshRateRange layoutLimitedRefreshRate =
+                new SurfaceControl.RefreshRateRange(0, 120);
+        DisplayInfo info1 = mLogicalDisplay.getDisplayInfoLocked();
+        mLogicalDisplay.updateLayoutLimitedRefreshRateLocked(layoutLimitedRefreshRate);
+        DisplayInfo info2 = mLogicalDisplay.getDisplayInfoLocked();
+        // Display info should only be updated when updateLocked is called
+        assertEquals(info2, info1);
 
-        DisplayInfo result = mLogicalDisplay.getDisplayInfoLocked();
+        mLogicalDisplay.updateLocked(mDeviceRepo);
+        DisplayInfo info3 = mLogicalDisplay.getDisplayInfoLocked();
+        assertNotEquals(info3, info2);
+        assertEquals(layoutLimitedRefreshRate, info3.layoutLimitedRefreshRate);
+    }
 
-        assertEquals(refreshRateRange, result.layoutLimitedRefreshRate);
+    @Test
+    public void testUpdateRefreshRateThermalThrottling() {
+        SparseArray<SurfaceControl.RefreshRateRange> refreshRanges = new SparseArray<>();
+        refreshRanges.put(0, new SurfaceControl.RefreshRateRange(0, 120));
+        DisplayInfo info1 = mLogicalDisplay.getDisplayInfoLocked();
+        mLogicalDisplay.updateThermalRefreshRateThrottling(refreshRanges);
+        DisplayInfo info2 = mLogicalDisplay.getDisplayInfoLocked();
+        // Display info should only be updated when updateLocked is called
+        assertEquals(info2, info1);
+
+        mLogicalDisplay.updateLocked(mDeviceRepo);
+        DisplayInfo info3 = mLogicalDisplay.getDisplayInfoLocked();
+        assertNotEquals(info3, info2);
+        assertTrue(refreshRanges.contentEquals(info3.thermalRefreshRateThrottling));
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/display/mode/DisplayModeDirectorTest.java b/services/tests/servicestests/src/com/android/server/display/mode/DisplayModeDirectorTest.java
index 42c1fd9..e492252 100644
--- a/services/tests/servicestests/src/com/android/server/display/mode/DisplayModeDirectorTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/mode/DisplayModeDirectorTest.java
@@ -27,7 +27,7 @@
 import static android.hardware.display.DisplayManager.DeviceConfig.KEY_REFRESH_RATE_IN_HIGH_ZONE;
 import static android.hardware.display.DisplayManager.DeviceConfig.KEY_REFRESH_RATE_IN_LOW_ZONE;
 
-import static com.android.server.display.mode.DisplayModeDirector.Vote.INVALID_SIZE;
+import static com.android.server.display.mode.Vote.INVALID_SIZE;
 
 import static com.google.common.truth.Truth.assertThat;
 
@@ -94,7 +94,6 @@
 import com.android.server.display.TestUtils;
 import com.android.server.display.mode.DisplayModeDirector.BrightnessObserver;
 import com.android.server.display.mode.DisplayModeDirector.DesiredDisplayModeSpecs;
-import com.android.server.display.mode.DisplayModeDirector.Vote;
 import com.android.server.sensors.SensorManagerInternal;
 import com.android.server.sensors.SensorManagerInternal.ProximityActiveListener;
 import com.android.server.statusbar.StatusBarManagerInternal;
@@ -127,7 +126,8 @@
     private static final String TAG = "DisplayModeDirectorTest";
     private static final boolean DEBUG = false;
     private static final float FLOAT_TOLERANCE = 0.01f;
-    private static final int DISPLAY_ID = 0;
+    private static final int DISPLAY_ID = Display.DEFAULT_DISPLAY;
+    private static final int MODE_ID = 1;
     private static final float TRANSITION_POINT = 0.763f;
 
     private static final float HBM_TRANSITION_POINT_INVALID = Float.POSITIVE_INFINITY;
@@ -223,8 +223,7 @@
         assertThat(modeSpecs.appRequest.render.min).isEqualTo(0f);
         assertThat(modeSpecs.appRequest.render.max).isEqualTo(Float.POSITIVE_INFINITY);
 
-        int numPriorities =
-                DisplayModeDirector.Vote.MAX_PRIORITY - DisplayModeDirector.Vote.MIN_PRIORITY + 1;
+        int numPriorities =  Vote.MAX_PRIORITY - Vote.MIN_PRIORITY + 1;
 
         // Ensure vote priority works as expected. As we add new votes with higher priority, they
         // should take precedence over lower priority votes.
@@ -2644,6 +2643,53 @@
         assertNull(vote);
     }
 
+    @Test
+    public void testUpdateLayoutLimitedRefreshRate_validDisplayInfo() {
+        DisplayModeDirector director =
+                createDirectorFromRefreshRateArray(new float[]{60.0f, 90.0f}, 0);
+        director.start(createMockSensorManager());
+
+        ArgumentCaptor<DisplayListener> displayListenerCaptor =
+                ArgumentCaptor.forClass(DisplayListener.class);
+        verify(mInjector).registerDisplayListener(displayListenerCaptor.capture(),
+                any(Handler.class));
+        DisplayListener displayListener = displayListenerCaptor.getValue();
+
+        float refreshRate = 60;
+        mInjector.mDisplayInfo.layoutLimitedRefreshRate =
+                new RefreshRateRange(refreshRate, refreshRate);
+        displayListener.onDisplayChanged(DISPLAY_ID);
+
+        Vote vote = director.getVote(DISPLAY_ID, Vote.PRIORITY_LAYOUT_LIMITED_FRAME_RATE);
+        assertVoteForPhysicalRefreshRate(vote, /* refreshRate= */ refreshRate);
+
+        mInjector.mDisplayInfo.layoutLimitedRefreshRate = null;
+        displayListener.onDisplayChanged(DISPLAY_ID);
+
+        vote = director.getVote(DISPLAY_ID, Vote.PRIORITY_LAYOUT_LIMITED_FRAME_RATE);
+        assertNull(vote);
+    }
+
+    @Test
+    public void testUpdateLayoutLimitedRefreshRate_invalidDisplayInfo() {
+        DisplayModeDirector director =
+                createDirectorFromRefreshRateArray(new float[]{60.0f, 90.0f}, 0);
+        director.start(createMockSensorManager());
+
+        ArgumentCaptor<DisplayListener> displayListenerCaptor =
+                ArgumentCaptor.forClass(DisplayListener.class);
+        verify(mInjector).registerDisplayListener(displayListenerCaptor.capture(),
+                any(Handler.class));
+        DisplayListener displayListener = displayListenerCaptor.getValue();
+
+        mInjector.mDisplayInfo.layoutLimitedRefreshRate = new RefreshRateRange(10, 10);
+        mInjector.mDisplayInfoValid = false;
+        displayListener.onDisplayChanged(DISPLAY_ID);
+
+        Vote vote = director.getVote(DISPLAY_ID, Vote.PRIORITY_LAYOUT_LIMITED_FRAME_RATE);
+        assertNull(vote);
+    }
+
     private Temperature getSkinTemp(@Temperature.ThrottlingStatus int status) {
         return new Temperature(30.0f, Temperature.TYPE_SKIN, "test_skin_temp", status);
     }
@@ -2850,12 +2896,20 @@
 
     public static class FakesInjector implements DisplayModeDirector.Injector {
         private final FakeDeviceConfig mDeviceConfig;
+        private final DisplayInfo mDisplayInfo;
+        private final Display mDisplay;
+        private boolean mDisplayInfoValid = true;
         private ContentObserver mBrightnessObserver;
         private ContentObserver mSmoothDisplaySettingObserver;
         private ContentObserver mForcePeakRefreshRateSettingObserver;
 
         FakesInjector() {
             mDeviceConfig = new FakeDeviceConfig();
+            mDisplayInfo = new DisplayInfo();
+            mDisplayInfo.defaultModeId = MODE_ID;
+            mDisplayInfo.supportedModes = new Display.Mode[] {new Display.Mode(MODE_ID,
+                    800, 600, /* refreshRate= */ 60)};
+            mDisplay = createDisplay(DISPLAY_ID);
         }
 
         @NonNull
@@ -2876,16 +2930,25 @@
         }
 
         @Override
+        public void registerDisplayListener(DisplayListener listener, Handler handler) {}
+
+        @Override
         public void registerDisplayListener(DisplayListener listener, Handler handler, long flag) {}
 
         @Override
+        public Display getDisplay(int displayId) {
+            return mDisplay;
+        }
+
+        @Override
         public Display[] getDisplays() {
-            return new Display[] { createDisplay(DISPLAY_ID) };
+            return new Display[] { mDisplay };
         }
 
         @Override
         public boolean getDisplayInfo(int displayId, DisplayInfo displayInfo) {
-            return false;
+            displayInfo.copyFrom(mDisplayInfo);
+            return mDisplayInfoValid;
         }
 
         @Override
@@ -2909,7 +2972,7 @@
         }
 
         protected Display createDisplay(int id) {
-            return new Display(DisplayManagerGlobal.getInstance(), id, new DisplayInfo(),
+            return new Display(DisplayManagerGlobal.getInstance(), id, mDisplayInfo,
                     ApplicationProvider.getApplicationContext().getResources());
         }
 
diff --git a/services/tests/servicestests/src/com/android/server/display/mode/SkinThermalStatusObserverTest.java b/services/tests/servicestests/src/com/android/server/display/mode/SkinThermalStatusObserverTest.java
index fd1889c..9ab6ee5 100644
--- a/services/tests/servicestests/src/com/android/server/display/mode/SkinThermalStatusObserverTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/mode/SkinThermalStatusObserverTest.java
@@ -18,7 +18,6 @@
 
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 
 import android.hardware.display.DisplayManager;
@@ -57,7 +56,7 @@
     private RegisteringFakesInjector mInjector = new RegisteringFakesInjector();
 
     private final TestHandler mHandler = new TestHandler(null);
-    private final FakeVoteStorage mStorage = new FakeVoteStorage();
+    private final VotesStorage mStorage = new VotesStorage(() -> {});
 
     @Before
     public void setUp() {
@@ -92,28 +91,26 @@
     public void testNotifyWithDefaultVotesForCritical() {
         // GIVEN 2 displays with no thermalThrottling config
         mObserver.observe();
-        assertEquals(0, mStorage.mVoteRegistry.size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
 
         // WHEN thermal sensor notifies CRITICAL
         mObserver.notifyThrottling(createTemperature(Temperature.THROTTLING_CRITICAL));
         mHandler.flush();
 
         // THEN 2 votes are added to storage with (0,60) render refresh rate(default behaviour)
-        assertEquals(2, mStorage.mVoteRegistry.size());
-
-        SparseArray<DisplayModeDirector.Vote> displayVotes = mStorage.mVoteRegistry.get(DISPLAY_ID);
+        SparseArray<Vote> displayVotes = mStorage.getVotes(DISPLAY_ID);
         assertEquals(1, displayVotes.size());
 
-        DisplayModeDirector.Vote vote = displayVotes.get(
-                DisplayModeDirector.Vote.PRIORITY_SKIN_TEMPERATURE);
+        Vote vote = displayVotes.get(
+                Vote.PRIORITY_SKIN_TEMPERATURE);
         assertEquals(0, vote.refreshRateRanges.render.min, FLOAT_TOLERANCE);
         assertEquals(60, vote.refreshRateRanges.render.max, FLOAT_TOLERANCE);
 
-        SparseArray<DisplayModeDirector.Vote> otherDisplayVotes = mStorage.mVoteRegistry.get(
-                DISPLAY_ID_OTHER);
+        SparseArray<Vote> otherDisplayVotes = mStorage.getVotes(DISPLAY_ID_OTHER);
         assertEquals(1, otherDisplayVotes.size());
 
-        vote = otherDisplayVotes.get(DisplayModeDirector.Vote.PRIORITY_SKIN_TEMPERATURE);
+        vote = otherDisplayVotes.get(Vote.PRIORITY_SKIN_TEMPERATURE);
         assertEquals(0, vote.refreshRateRanges.render.min, FLOAT_TOLERANCE);
         assertEquals(60, vote.refreshRateRanges.render.max, FLOAT_TOLERANCE);
     }
@@ -122,25 +119,29 @@
     public void testNotifyWithDefaultVotesChangeFromCriticalToSevere() {
         // GIVEN 2 displays with no thermalThrottling config AND temperature level CRITICAL
         mObserver.observe();
-        assertEquals(0, mStorage.mVoteRegistry.size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
         mObserver.notifyThrottling(createTemperature(Temperature.THROTTLING_CRITICAL));
         // WHEN thermal sensor notifies SEVERE
         mObserver.notifyThrottling(createTemperature(Temperature.THROTTLING_SEVERE));
         mHandler.flush();
         // THEN all votes with PRIORITY_SKIN_TEMPERATURE are removed from the storage
-        assertEquals(0, mStorage.mVoteRegistry.size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
     }
 
     @Test
     public void testNotifyWithDefaultVotesForSevere() {
         // GIVEN 2 displays with no thermalThrottling config
         mObserver.observe();
-        assertEquals(0, mStorage.mVoteRegistry.size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
         // WHEN thermal sensor notifies CRITICAL
         mObserver.notifyThrottling(createTemperature(Temperature.THROTTLING_SEVERE));
         mHandler.flush();
         // THEN nothing is added to the storage
-        assertEquals(0, mStorage.mVoteRegistry.size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
     }
 
     @Test
@@ -155,18 +156,20 @@
         mObserver = new SkinThermalStatusObserver(mInjector, mStorage, mHandler);
         mObserver.observe();
         mObserver.onDisplayChanged(DISPLAY_ID);
-        assertEquals(0, mStorage.mVoteRegistry.size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
         // WHEN thermal sensor notifies temperature above configured
         mObserver.notifyThrottling(createTemperature(Temperature.THROTTLING_SEVERE));
         mHandler.flush();
         // THEN vote with refreshRate from config is added to the storage
-        assertEquals(1, mStorage.mVoteRegistry.size());
-        SparseArray<DisplayModeDirector.Vote> displayVotes = mStorage.mVoteRegistry.get(DISPLAY_ID);
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
+
+        SparseArray<Vote> displayVotes = mStorage.getVotes(DISPLAY_ID);
         assertEquals(1, displayVotes.size());
-        DisplayModeDirector.Vote vote = displayVotes.get(
-                DisplayModeDirector.Vote.PRIORITY_SKIN_TEMPERATURE);
+        Vote vote = displayVotes.get(Vote.PRIORITY_SKIN_TEMPERATURE);
         assertEquals(90, vote.refreshRateRanges.render.min, FLOAT_TOLERANCE);
         assertEquals(120, vote.refreshRateRanges.render.max, FLOAT_TOLERANCE);
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_OTHER).size());
     }
 
     @Test
@@ -178,14 +181,13 @@
         mObserver.onDisplayAdded(DISPLAY_ID_ADDED);
         mHandler.flush();
         // THEN 3rd vote is added to storage with (0,60) render refresh rate(default behaviour)
-        assertEquals(3, mStorage.mVoteRegistry.size());
+        assertEquals(1, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(1, mStorage.getVotes(DISPLAY_ID_OTHER).size());
+        assertEquals(1, mStorage.getVotes(DISPLAY_ID_ADDED).size());
 
-        SparseArray<DisplayModeDirector.Vote> displayVotes = mStorage.mVoteRegistry.get(
-                DISPLAY_ID_ADDED);
-        assertEquals(1, displayVotes.size());
+        SparseArray<Vote> displayVotes = mStorage.getVotes(DISPLAY_ID_ADDED);
 
-        DisplayModeDirector.Vote vote = displayVotes.get(
-                DisplayModeDirector.Vote.PRIORITY_SKIN_TEMPERATURE);
+        Vote vote = displayVotes.get(Vote.PRIORITY_SKIN_TEMPERATURE);
         assertEquals(0, vote.refreshRateRanges.render.min, FLOAT_TOLERANCE);
         assertEquals(60, vote.refreshRateRanges.render.max, FLOAT_TOLERANCE);
     }
@@ -200,9 +202,9 @@
         mObserver.onDisplayRemoved(DISPLAY_ID_ADDED);
         mHandler.flush();
         // THEN there are 2 votes in registry
-        assertEquals(2, mStorage.mVoteRegistry.size());
-        assertNotNull(mStorage.mVoteRegistry.get(DISPLAY_ID));
-        assertNotNull(mStorage.mVoteRegistry.get(DISPLAY_ID_OTHER));
+        assertEquals(1, mStorage.getVotes(DISPLAY_ID).size());
+        assertEquals(1, mStorage.getVotes(DISPLAY_ID_OTHER).size());
+        assertEquals(0, mStorage.getVotes(DISPLAY_ID_ADDED).size());
     }
 
     private static Temperature createTemperature(@Temperature.ThrottlingStatus int status) {
@@ -253,33 +255,10 @@
         public boolean getDisplayInfo(int displayId, DisplayInfo displayInfo) {
             SparseArray<SurfaceControl.RefreshRateRange> config = mOverriddenConfig.get(displayId);
             if (config != null) {
-                displayInfo.refreshRateThermalThrottling = config;
+                displayInfo.thermalRefreshRateThrottling = config;
                 return true;
             }
             return false;
         }
     }
-
-
-    private static class FakeVoteStorage implements DisplayModeDirector.BallotBox {
-        private final SparseArray<SparseArray<DisplayModeDirector.Vote>> mVoteRegistry =
-                new SparseArray<>();
-
-        @Override
-        public void vote(int displayId, int priority, DisplayModeDirector.Vote vote) {
-            SparseArray<DisplayModeDirector.Vote> votesPerDisplay = mVoteRegistry.get(displayId);
-            if (votesPerDisplay == null) {
-                votesPerDisplay = new SparseArray<>();
-                mVoteRegistry.put(displayId, votesPerDisplay);
-            }
-            if (vote == null) {
-                votesPerDisplay.remove(priority);
-            } else {
-                votesPerDisplay.put(priority, vote);
-            }
-            if (votesPerDisplay.size() == 0) {
-                mVoteRegistry.remove(displayId);
-            }
-        }
-    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/display/mode/VotesStorageTest.java b/services/tests/servicestests/src/com/android/server/display/mode/VotesStorageTest.java
new file mode 100644
index 0000000..287fdd5
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/display/mode/VotesStorageTest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2023 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.mode;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import android.util.SparseArray;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class VotesStorageTest {
+    private static final int DISPLAY_ID = 100;
+    private static final int PRIORITY = Vote.PRIORITY_APP_REQUEST_SIZE;
+    private static final Vote VOTE = Vote.forDisableRefreshRateSwitching();
+    private static final int DISPLAY_ID_OTHER = 101;
+    private static final int PRIORITY_OTHER = Vote.PRIORITY_FLICKER_REFRESH_RATE;
+    private static final Vote VOTE_OTHER = Vote.forBaseModeRefreshRate(10f);
+
+    @Mock
+    public VotesStorage.Listener mVotesListener;
+
+    private VotesStorage mVotesStorage;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mVotesStorage = new VotesStorage(mVotesListener);
+    }
+
+    @Test
+    public void addsVoteToStorage() {
+        // WHEN updateVote is called
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY, VOTE);
+        // THEN vote is added to the storage
+        SparseArray<Vote> votes = mVotesStorage.getVotes(DISPLAY_ID);
+        assertThat(votes.size()).isEqualTo(1);
+        assertThat(votes.get(PRIORITY)).isEqualTo(VOTE);
+        assertThat(mVotesStorage.getVotes(DISPLAY_ID_OTHER).size()).isEqualTo(0);
+    }
+
+    @Test
+    public void notifiesVoteListenerIfVoteAdded() {
+        // WHEN updateVote is called
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY, VOTE);
+        // THEN listener is notified
+        verify(mVotesListener).onChanged();
+    }
+
+    @Test
+    public void addsAnotherVoteToStorageWithDifferentPriority() {
+        // GIVEN vote storage with one vote
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY, VOTE);
+        // WHEN updateVote is called with other priority
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY_OTHER, VOTE_OTHER);
+        // THEN another vote is added to storage
+        SparseArray<Vote> votes = mVotesStorage.getVotes(DISPLAY_ID);
+        assertThat(votes.size()).isEqualTo(2);
+        assertThat(votes.get(PRIORITY)).isEqualTo(VOTE);
+        assertThat(votes.get(PRIORITY_OTHER)).isEqualTo(VOTE_OTHER);
+        assertThat(mVotesStorage.getVotes(DISPLAY_ID_OTHER).size()).isEqualTo(0);
+    }
+
+    @Test
+    public void replacesVoteInStorageForSamePriority() {
+        // GIVEN vote storage with one vote
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY, VOTE);
+        // WHEN updateVote is called with same priority
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY, VOTE_OTHER);
+        // THEN vote is replaced by other vote
+        SparseArray<Vote> votes = mVotesStorage.getVotes(DISPLAY_ID);
+        assertThat(votes.size()).isEqualTo(1);
+        assertThat(votes.get(PRIORITY)).isEqualTo(VOTE_OTHER);
+        assertThat(mVotesStorage.getVotes(DISPLAY_ID_OTHER).size()).isEqualTo(0);
+    }
+
+    @Test
+    public void removesVoteInStorageForSamePriority() {
+        // GIVEN vote storage with one vote
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY, VOTE);
+        // WHEN update is called with same priority and null vote
+        mVotesStorage.updateVote(DISPLAY_ID, PRIORITY, null);
+        // THEN vote removed from the storage
+        assertThat(mVotesStorage.getVotes(DISPLAY_ID).size()).isEqualTo(0);
+        assertThat(mVotesStorage.getVotes(DISPLAY_ID_OTHER).size()).isEqualTo(0);
+    }
+
+    @Test
+    public void addsGlobalDisplayVoteToStorage() {
+        // WHEN updateGlobalVote is called
+        mVotesStorage.updateGlobalVote(PRIORITY, VOTE);
+        // THEN it is added to the storage for every display
+        SparseArray<Vote> votes = mVotesStorage.getVotes(DISPLAY_ID);
+        assertThat(votes.size()).isEqualTo(1);
+        assertThat(votes.get(PRIORITY)).isEqualTo(VOTE);
+        votes = mVotesStorage.getVotes(DISPLAY_ID_OTHER);
+        assertThat(votes.size()).isEqualTo(1);
+        assertThat(votes.get(PRIORITY)).isEqualTo(VOTE);
+    }
+
+    @Test
+    public void ignoresVotesWithLowerThanMinPriority() {
+        // WHEN updateVote is called with invalid (lower than min) priority
+        mVotesStorage.updateVote(DISPLAY_ID, Vote.MIN_PRIORITY - 1, VOTE);
+        // THEN vote is not added to the storage AND listener not notified
+        assertThat(mVotesStorage.getVotes(DISPLAY_ID).size()).isEqualTo(0);
+        verify(mVotesListener, never()).onChanged();
+    }
+
+    @Test
+    public void ignoresVotesWithGreaterThanMaxPriority() {
+        // WHEN updateVote is called with invalid (greater than max) priority
+        mVotesStorage.updateVote(DISPLAY_ID, Vote.MAX_PRIORITY + 1, VOTE);
+        // THEN vote is not added to the storage AND listener not notified
+        assertThat(mVotesStorage.getVotes(DISPLAY_ID).size()).isEqualTo(0);
+        verify(mVotesListener, never()).onChanged();
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/input/KeyboardBacklightControllerTests.kt b/services/tests/servicestests/src/com/android/server/input/KeyboardBacklightControllerTests.kt
index 0f4d4e8..64c05dc 100644
--- a/services/tests/servicestests/src/com/android/server/input/KeyboardBacklightControllerTests.kt
+++ b/services/tests/servicestests/src/com/android/server/input/KeyboardBacklightControllerTests.kt
@@ -250,20 +250,24 @@
         `when`(iInputManager.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight)
         `when`(iInputManager.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight))
 
-        dataStore.setKeyboardBacklightBrightness(
-            keyboardWithBacklight.descriptor,
-            LIGHT_ID,
-            MAX_BRIGHTNESS
-        )
+        for (level in 1 until BRIGHTNESS_VALUE_FOR_LEVEL.size) {
+            dataStore.setKeyboardBacklightBrightness(
+                    keyboardWithBacklight.descriptor,
+                    LIGHT_ID,
+                    BRIGHTNESS_VALUE_FOR_LEVEL[level] - 1
+            )
 
-        keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
-        keyboardBacklightController.notifyUserActivity()
-        testLooper.dispatchNext()
-        assertEquals(
-            "Keyboard backlight level should be restored to the level saved in the data store",
-            Color.argb(MAX_BRIGHTNESS, 0, 0, 0),
-            lightColorMap[LIGHT_ID]
-        )
+            keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
+            keyboardBacklightController.notifyUserActivity()
+            testLooper.dispatchNext()
+            assertEquals(
+                    "Keyboard backlight level should be restored to the level saved in the data " +
+                            "store",
+                    Color.argb(BRIGHTNESS_VALUE_FOR_LEVEL[level], 0, 0, 0),
+                    lightColorMap[LIGHT_ID]
+            )
+            keyboardBacklightController.onInputDeviceRemoved(DEVICE_ID)
+        }
     }
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/input/KeyboardLayoutManagerTests.kt b/services/tests/servicestests/src/com/android/server/input/KeyboardLayoutManagerTests.kt
index ea3f3bc..d0d28c3 100644
--- a/services/tests/servicestests/src/com/android/server/input/KeyboardLayoutManagerTests.kt
+++ b/services/tests/servicestests/src/com/android/server/input/KeyboardLayoutManagerTests.kt
@@ -633,6 +633,30 @@
                 0,
                 keyboardLayouts.size
             )
+
+            // If IME doesn't have a corresponding language tag, then should show all available
+            // layouts no matter the script code.
+            keyboardLayouts =
+                keyboardLayoutManager.getKeyboardLayoutListForInputDevice(
+                    keyboardDevice.identifier, USER_ID, imeInfo, null
+                )
+            assertNotEquals(
+                "New UI: getKeyboardLayoutListForInputDevice API should return all layouts if" +
+                    "language tag or subtype not provided",
+                0,
+                keyboardLayouts.size
+            )
+            assertTrue("New UI: getKeyboardLayoutListForInputDevice API should contain Latin " +
+                "layouts if language tag or subtype not provided",
+                containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR)
+            )
+            assertTrue("New UI: getKeyboardLayoutListForInputDevice API should contain Cyrillic " +
+                "layouts if language tag or subtype not provided",
+                containsLayout(
+                    keyboardLayouts,
+                    createLayoutDescriptor("keyboard_layout_russian")
+                )
+            )
         }
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java b/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java
index 8f0a5e6..bf6901e 100644
--- a/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java
+++ b/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java
@@ -21,6 +21,8 @@
 import static android.view.KeyEvent.KEYCODE_C;
 import static android.view.KeyEvent.KEYCODE_CTRL_LEFT;
 import static android.view.KeyEvent.KEYCODE_E;
+import static android.view.KeyEvent.KEYCODE_ENTER;
+import static android.view.KeyEvent.KEYCODE_H;
 import static android.view.KeyEvent.KEYCODE_K;
 import static android.view.KeyEvent.KEYCODE_M;
 import static android.view.KeyEvent.KEYCODE_META_LEFT;
@@ -164,4 +166,24 @@
         sendKeyCombination(new int[]{KEYCODE_META_LEFT, KEYCODE_ALT_LEFT}, 0);
         mPhoneWindowManager.assertToggleCapsLock();
     }
+
+    /**
+     * META + H to go to homescreen
+     */
+    @Test
+    public void testMetaH() {
+        mPhoneWindowManager.overrideLaunchHome();
+        sendKeyCombination(new int[]{KEYCODE_META_LEFT, KEYCODE_H}, 0);
+        mPhoneWindowManager.assertGoToHomescreen();
+    }
+
+    /**
+     * META + ENTER to go to homescreen
+     */
+    @Test
+    public void testMetaEnter() {
+        mPhoneWindowManager.overrideLaunchHome();
+        sendKeyCombination(new int[]{KEYCODE_META_LEFT, KEYCODE_ENTER}, 0);
+        mPhoneWindowManager.assertGoToHomescreen();
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/policy/ShortcutKeyTestBase.java b/services/tests/wmtests/src/com/android/server/policy/ShortcutKeyTestBase.java
index 6368f47..676bfb0 100644
--- a/services/tests/wmtests/src/com/android/server/policy/ShortcutKeyTestBase.java
+++ b/services/tests/wmtests/src/com/android/server/policy/ShortcutKeyTestBase.java
@@ -117,9 +117,9 @@
             throw new RuntimeException(e);
         }
 
-        for (KeyEvent event: events) {
+        for (int i = count - 1; i >= 0; i--) {
             final long eventTime = SystemClock.uptimeMillis();
-            final int keyCode = event.getKeyCode();
+            final int keyCode = keyCodes[i];
             final KeyEvent upEvent = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_UP, keyCode,
                     0, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0 /*scancode*/, 0 /*flags*/,
                     InputDevice.SOURCE_KEYBOARD);
diff --git a/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java b/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
index a2ee8a4..2665e19 100644
--- a/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
+++ b/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
@@ -353,6 +353,10 @@
                 () -> LocalServices.getService(eq(StatusBarManagerInternal.class)));
     }
 
+    void overrideLaunchHome() {
+        doNothing().when(mPhoneWindowManager).launchHomeFromHotKey(anyInt());
+    }
+
     /**
      * Below functions will check the policy behavior could be invoked.
      */
@@ -480,4 +484,9 @@
         transitionCaptor.getValue().onAppTransitionFinishedLocked(any());
         verify(mPhoneWindowManager).lockNow(null);
     }
+
+    void assertGoToHomescreen() {
+        waitForIdle();
+        verify(mPhoneWindowManager).launchHomeFromHotKey(anyInt());
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayWindowSettingsTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayWindowSettingsTests.java
index fb4f2ee..1cec0ef 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayWindowSettingsTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayWindowSettingsTests.java
@@ -41,8 +41,9 @@
 
 import android.annotation.NonNull;
 import android.app.WindowConfiguration;
-import android.content.res.Configuration;
+import android.content.ContentResolver;
 import android.platform.test.annotations.Presubmit;
+import android.provider.Settings;
 import android.view.Display;
 import android.view.DisplayInfo;
 import android.view.Surface;
@@ -439,6 +440,7 @@
     public void testDisplayWindowSettingsAppliedOnDisplayReady() {
         // Set forced densities for two displays in DisplayWindowSettings
         final DisplayContent dc = createMockSimulatedDisplay();
+        final ContentResolver contentResolver = useFakeSettingsProvider();
         mDisplayWindowSettings.setForcedDensity(mPrimaryDisplay.getDisplayInfo(), 123,
                 0 /* userId */);
         mDisplayWindowSettings.setForcedDensity(dc.getDisplayInfo(), 456, 0 /* userId */);
@@ -450,15 +452,21 @@
         assertFalse(mPrimaryDisplay.mWaitingForConfig);
         assertFalse(dc.mWaitingForConfig);
 
+        final int invalidW = Integer.MAX_VALUE;
+        final int invalidH = Integer.MAX_VALUE;
+        // Verify that applyForcedPropertiesForDefaultDisplay() handles invalid size request.
+        Settings.Global.putString(contentResolver, Settings.Global.DISPLAY_SIZE_FORCED,
+                invalidW + "," + invalidH);
         // Notify WM that the displays are ready and check that they are reconfigured.
         mWm.displayReady();
         waitUntilHandlersIdle();
 
-        final Configuration config = new Configuration();
-        mPrimaryDisplay.computeScreenConfiguration(config);
-        assertEquals(123, config.densityDpi);
-        dc.computeScreenConfiguration(config);
-        assertEquals(456, config.densityDpi);
+        // Density is set successfully.
+        assertEquals(123, mPrimaryDisplay.getConfiguration().densityDpi);
+        assertEquals(456, dc.getConfiguration().densityDpi);
+        // Invalid size won't be applied.
+        assertNotEquals(invalidW, mPrimaryDisplay.mBaseDisplayWidth);
+        assertNotEquals(invalidH, mPrimaryDisplay.mBaseDisplayHeight);
     }
 
     @Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
index f85cdf0..07244a4 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -66,6 +66,7 @@
 import android.annotation.Nullable;
 import android.app.ActivityOptions;
 import android.content.ComponentName;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
@@ -81,6 +82,7 @@
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.os.UserHandle;
+import android.provider.Settings;
 import android.service.voice.IVoiceInteractionSession;
 import android.util.SparseArray;
 import android.view.Display;
@@ -109,6 +111,7 @@
 
 import com.android.internal.policy.AttributeCache;
 import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.test.FakeSettingsProvider;
 import com.android.server.wm.DisplayWindowSettings.SettingsProvider.SettingsEntry;
 
 import org.junit.After;
@@ -146,6 +149,7 @@
     WindowManagerService mWm;
     private final IWindow mIWindow = new TestIWindow();
     private Session mMockSession;
+    private boolean mUseFakeSettingsProvider;
 
     DisplayInfo mDisplayInfo = new DisplayInfo();
     DisplayContent mDefaultDisplay;
@@ -272,16 +276,9 @@
 
     @After
     public void tearDown() throws Exception {
-        // Revert back to device overrides.
-        mAtm.mWindowManager.mLetterboxConfiguration.resetFixedOrientationLetterboxAspectRatio();
-        mAtm.mWindowManager.mLetterboxConfiguration.resetLetterboxHorizontalPositionMultiplier();
-        mAtm.mWindowManager.mLetterboxConfiguration.resetLetterboxVerticalPositionMultiplier();
-        mAtm.mWindowManager.mLetterboxConfiguration.resetIsHorizontalReachabilityEnabled();
-        mAtm.mWindowManager.mLetterboxConfiguration.resetIsVerticalReachabilityEnabled();
-        mAtm.mWindowManager.mLetterboxConfiguration
-                .resetIsSplitScreenAspectRatioForUnresizableAppsEnabled();
-        mAtm.mWindowManager.mLetterboxConfiguration
-                .resetIsDisplayAspectRatioEnabledForFixedOrientationLetterbox();
+        if (mUseFakeSettingsProvider) {
+            FakeSettingsProvider.clearSettingsProvider();
+        }
     }
 
     /**
@@ -428,6 +425,17 @@
         // Called before display is created.
     }
 
+    /** Avoid writing values to real Settings. */
+    ContentResolver useFakeSettingsProvider() {
+        mUseFakeSettingsProvider = true;
+        FakeSettingsProvider.clearSettingsProvider();
+        final FakeSettingsProvider provider = new FakeSettingsProvider();
+        // SystemServicesTestRule#setUpSystemCore has called spyOn for the ContentResolver.
+        final ContentResolver resolver = mContext.getContentResolver();
+        doReturn(provider.getIContentProvider()).when(resolver).acquireProvider(Settings.AUTHORITY);
+        return resolver;
+    }
+
     private WindowState createCommonWindow(WindowState parent, int type, String name) {
         final WindowState win = createWindow(parent, type, name);
         // Prevent common windows from been IME targets.