diff options
43 files changed, 1962 insertions, 1094 deletions
diff --git a/apct-tests/perftests/core/Android.bp b/apct-tests/perftests/core/Android.bp index ab20fdbde1e5..23464f879518 100644 --- a/apct-tests/perftests/core/Android.bp +++ b/apct-tests/perftests/core/Android.bp @@ -43,7 +43,6 @@ android_test { "apct-perftests-resources-manager-apps", "apct-perftests-utils", "collector-device-lib", - "compatibility-device-util-axt", "core-tests-support", "guava", ], diff --git a/apct-tests/perftests/core/AndroidManifest.xml b/apct-tests/perftests/core/AndroidManifest.xml index c153201cd475..bb57161b4f6b 100644 --- a/apct-tests/perftests/core/AndroidManifest.xml +++ b/apct-tests/perftests/core/AndroidManifest.xml @@ -55,16 +55,6 @@ </intent-filter> </service> - <service android:name="android.view.HandwritingImeService" - android:label="Handwriting IME" - android:permission="android.permission.BIND_INPUT_METHOD" - android:exported="true"> - <intent-filter> - <action android:name="android.view.InputMethod"/> - </intent-filter> - <meta-data android:name="android.view.im" - android:resource="@xml/ime_meta_handwriting"/> - </service> </application> <instrumentation android:name="androidx.benchmark.junit4.AndroidBenchmarkRunner" diff --git a/apct-tests/perftests/core/res/xml/ime_meta_handwriting.xml b/apct-tests/perftests/core/res/xml/ime_meta_handwriting.xml deleted file mode 100644 index 24c0c255c2f3..000000000000 --- a/apct-tests/perftests/core/res/xml/ime_meta_handwriting.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - ~ Copyright (C) 2022 The Android Open Source Project - ~ - ~ Licensed under the Apache License, Version 2.0 (the "License"); - ~ you may not use this file except in compliance with the License. - ~ You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - -<input-method - xmlns:android="http://schemas.android.com/apk/res/android" - android:settingsActivity="com.android.inputmethod.latin.settings.SettingsActivity" - android:supportsStylusHandwriting="true"/> diff --git a/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java b/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java index cf76334ceb10..123b2eeba5dd 100644 --- a/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java +++ b/apct-tests/perftests/core/src/android/view/HandwritingInitiatorPerfTest.java @@ -22,6 +22,7 @@ import static android.view.MotionEvent.ACTION_UP; import static android.view.MotionEvent.TOOL_TYPE_FINGER; import static android.view.MotionEvent.TOOL_TYPE_STYLUS; + import android.app.Instrumentation; import android.content.Context; import android.perftests.utils.BenchmarkState; @@ -33,15 +34,11 @@ import androidx.test.filters.LargeTest; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.runner.AndroidJUnit4; -import com.android.compatibility.common.util.PollingCheck; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import java.util.concurrent.TimeUnit; - /** * Benchmark tests for {@link HandwritingInitiator} * @@ -59,21 +56,11 @@ public class HandwritingInitiatorPerfTest { public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @Before - public void setup() throws Exception { - final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); - mContext = instrumentation.getTargetContext(); - - String imeId = HandwritingImeService.getImeId(); - instrumentation.getUiAutomation().executeShellCommand("ime enable " + imeId); - instrumentation.getUiAutomation().executeShellCommand("ime set " + imeId); - PollingCheck.check("Check that stylus handwriting is available", - TimeUnit.SECONDS.toMillis(10), - () -> mContext.getSystemService(InputMethodManager.class) - .isStylusHandwritingAvailable()); - + public void setup() { + final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation(); + mContext = mInstrumentation.getTargetContext(); final ViewConfiguration viewConfiguration = ViewConfiguration.get(mContext); mTouchSlop = viewConfiguration.getScaledTouchSlop(); - final InputMethodManager inputMethodManager = mContext.getSystemService(InputMethodManager.class); mHandwritingInitiator = new HandwritingInitiator(viewConfiguration, inputMethodManager); diff --git a/core/java/android/app/NotificationChannelGroup.java b/core/java/android/app/NotificationChannelGroup.java index 1769993e0e07..f97415ca20c8 100644 --- a/core/java/android/app/NotificationChannelGroup.java +++ b/core/java/android/app/NotificationChannelGroup.java @@ -20,7 +20,6 @@ import android.annotation.SystemApi; import android.annotation.TestApi; import android.compat.annotation.UnsupportedAppUsage; import android.content.Intent; -import android.content.pm.ParceledListSlice; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; @@ -67,7 +66,7 @@ public final class NotificationChannelGroup implements Parcelable { private CharSequence mName; private String mDescription; private boolean mBlocked; - private ParceledListSlice<NotificationChannel> mChannels; + private List<NotificationChannel> mChannels = new ArrayList<>(); // Bitwise representation of fields that have been changed by the user private int mUserLockedFields; @@ -101,8 +100,7 @@ public final class NotificationChannelGroup implements Parcelable { } else { mDescription = null; } - mChannels = in.readParcelable( - NotificationChannelGroup.class.getClassLoader(), ParceledListSlice.class); + in.readParcelableList(mChannels, NotificationChannel.class.getClassLoader(), android.app.NotificationChannel.class); mBlocked = in.readBoolean(); mUserLockedFields = in.readInt(); } @@ -129,7 +127,7 @@ public final class NotificationChannelGroup implements Parcelable { } else { dest.writeByte((byte) 0); } - dest.writeParcelable(mChannels, flags); + dest.writeParcelableList(mChannels, flags); dest.writeBoolean(mBlocked); dest.writeInt(mUserLockedFields); } @@ -159,7 +157,7 @@ public final class NotificationChannelGroup implements Parcelable { * Returns the list of channels that belong to this group */ public List<NotificationChannel> getChannels() { - return mChannels == null ? new ArrayList<>() : mChannels.getList(); + return mChannels; } /** @@ -193,8 +191,15 @@ public final class NotificationChannelGroup implements Parcelable { /** * @hide */ + public void addChannel(NotificationChannel channel) { + mChannels.add(channel); + } + + /** + * @hide + */ public void setChannels(List<NotificationChannel> channels) { - mChannels = new ParceledListSlice<>(channels); + mChannels = channels; } /** @@ -329,7 +334,7 @@ public final class NotificationChannelGroup implements Parcelable { proto.write(NotificationChannelGroupProto.NAME, mName.toString()); proto.write(NotificationChannelGroupProto.DESCRIPTION, mDescription); proto.write(NotificationChannelGroupProto.IS_BLOCKED, mBlocked); - for (NotificationChannel channel : mChannels.getList()) { + for (NotificationChannel channel : mChannels) { channel.dumpDebug(proto, NotificationChannelGroupProto.CHANNELS); } proto.end(token); diff --git a/core/java/android/content/pm/VerifierDeviceIdentity.java b/core/java/android/content/pm/VerifierDeviceIdentity.java index 3ce0b65e9f95..7e82edf8ec8f 100644 --- a/core/java/android/content/pm/VerifierDeviceIdentity.java +++ b/core/java/android/content/pm/VerifierDeviceIdentity.java @@ -89,8 +89,8 @@ public class VerifierDeviceIdentity implements Parcelable { * @return verifier device identity based on the input from the provided * random number generator */ - @VisibleForTesting - static VerifierDeviceIdentity generate(Random rng) { + @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE) + public static VerifierDeviceIdentity generate(Random rng) { long identity = rng.nextLong(); return new VerifierDeviceIdentity(identity); } diff --git a/core/java/android/view/AttachedSurfaceControl.java b/core/java/android/view/AttachedSurfaceControl.java index bd468d95858a..5dae31373e82 100644 --- a/core/java/android/view/AttachedSurfaceControl.java +++ b/core/java/android/view/AttachedSurfaceControl.java @@ -17,10 +17,10 @@ package android.view; import android.annotation.NonNull; import android.annotation.Nullable; -import android.annotation.SystemApi; import android.annotation.UiThread; import android.graphics.Region; import android.hardware.HardwareBuffer; +import android.window.SurfaceSyncGroup; /** * Provides an interface to the root-Surface of a View Hierarchy or Window. This @@ -138,4 +138,12 @@ public interface AttachedSurfaceControl { */ default void setTouchableRegion(@Nullable Region r) { } + + /** + * Returns a SyncTarget that can be used to sync {@link AttachedSurfaceControl} in a + * {@link SurfaceSyncGroup} + * + * @hide + */ + SurfaceSyncGroup.SyncTarget getSyncTarget(); } diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java index c7dbc07ef7c6..70a5eda1d03e 100644 --- a/core/java/android/view/SurfaceView.java +++ b/core/java/android/view/SurfaceView.java @@ -47,7 +47,7 @@ import android.util.Log; import android.view.SurfaceControl.Transaction; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.IAccessibilityEmbeddedConnection; -import android.window.SurfaceSyncer; +import android.window.SurfaceSyncGroup; import com.android.internal.view.SurfaceCallbackHelper; @@ -210,8 +210,7 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall private int mSurfaceFlags = SurfaceControl.HIDDEN; - private final SurfaceSyncer mSurfaceSyncer = new SurfaceSyncer(); - private final ArraySet<Integer> mSyncIds = new ArraySet<>(); + private final ArraySet<SurfaceSyncGroup> mSyncGroups = new ArraySet<>(); /** * Transaction that should be used from the render thread. This transaction is only thread safe @@ -1077,20 +1076,21 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall } private void handleSyncNoBuffer(SurfaceHolder.Callback[] callbacks) { - final int syncId = mSurfaceSyncer.setupSync(this::onDrawFinished); + final SurfaceSyncGroup syncGroup = new SurfaceSyncGroup(); + synchronized (mSyncGroups) { + mSyncGroups.add(syncGroup); + } - mSurfaceSyncer.addToSync(syncId, syncBufferCallback -> redrawNeededAsync(callbacks, + syncGroup.addToSync(syncBufferCallback -> redrawNeededAsync(callbacks, () -> { syncBufferCallback.onBufferReady(null); - synchronized (mSyncIds) { - mSyncIds.remove(syncId); + onDrawFinished(); + synchronized (mSyncGroups) { + mSyncGroups.remove(syncGroup); } })); - mSurfaceSyncer.markSyncReady(syncId); - synchronized (mSyncIds) { - mSyncIds.add(syncId); - } + syncGroup.markSyncReady(); } private void redrawNeededAsync(SurfaceHolder.Callback[] callbacks, @@ -1106,9 +1106,9 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall public void surfaceSyncStarted() { ViewRootImpl viewRoot = getViewRootImpl(); if (viewRoot != null) { - synchronized (mSyncIds) { - for (int syncId : mSyncIds) { - viewRoot.mergeSync(syncId, mSurfaceSyncer); + synchronized (mSyncGroups) { + for (SurfaceSyncGroup syncGroup : mSyncGroups) { + viewRoot.mergeSync(syncGroup); } } } diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java index fbfeac71e655..c1a5a3a25680 100644 --- a/core/java/android/view/ViewRootImpl.java +++ b/core/java/android/view/ViewRootImpl.java @@ -197,7 +197,7 @@ import android.window.ClientWindowFrames; import android.window.CompatOnBackInvokedCallback; import android.window.OnBackInvokedCallback; import android.window.OnBackInvokedDispatcher; -import android.window.SurfaceSyncer; +import android.window.SurfaceSyncGroup; import android.window.WindowOnBackInvokedDispatcher; import com.android.internal.R; @@ -829,9 +829,8 @@ public final class ViewRootImpl implements ViewParent, return mHandwritingInitiator; } - private final SurfaceSyncer mSurfaceSyncer = new SurfaceSyncer(); - private int mSyncId = UNSET_SYNC_ID; - private SurfaceSyncer.SyncBufferCallback mSyncBufferCallback; + private SurfaceSyncGroup mSyncGroup; + private SurfaceSyncGroup.SyncBufferCallback mSyncBufferCallback; private int mNumSyncsInProgress = 0; private HashSet<ScrollCaptureCallback> mRootScrollCaptureCallbacks; @@ -3594,8 +3593,8 @@ public final class ViewRootImpl implements ViewParent, mSyncBufferCallback = null; mSyncBuffer = false; if (isInLocalSync()) { - mSurfaceSyncer.markSyncReady(mSyncId); - mSyncId = UNSET_SYNC_ID; + mSyncGroup.markSyncReady(); + mSyncGroup = null; } } } @@ -3607,17 +3606,19 @@ public final class ViewRootImpl implements ViewParent, } final int seqId = mSyncSeqId; - mSyncId = mSurfaceSyncer.setupSync(transaction -> { + mSyncGroup = new SurfaceSyncGroup(transaction -> { // Callback will be invoked on executor thread so post to main thread. mHandler.postAtFrontOfQueue(() -> { - mSurfaceChangedTransaction.merge(transaction); + if (transaction != null) { + mSurfaceChangedTransaction.merge(transaction); + } reportDrawFinished(seqId); }); }); if (DEBUG_BLAST) { - Log.d(mTag, "Setup new sync id=" + mSyncId); + Log.d(mTag, "Setup new sync id=" + mSyncGroup); } - mSurfaceSyncer.addToSync(mSyncId, mSyncTarget); + mSyncGroup.addToSync(mSyncTarget); notifySurfaceSyncStarted(); } @@ -4255,11 +4256,11 @@ public final class ViewRootImpl implements ViewParent, return mAttachInfo.mThreadedRenderer != null && mAttachInfo.mThreadedRenderer.isEnabled(); } - void addToSync(SurfaceSyncer.SyncTarget syncable) { + void addToSync(SurfaceSyncGroup.SyncTarget syncable) { if (!isInLocalSync()) { return; } - mSurfaceSyncer.addToSync(mSyncId, syncable); + mSyncGroup.addToSync(syncable); } /** @@ -4267,7 +4268,7 @@ public final class ViewRootImpl implements ViewParent, * within VRI. */ public boolean isInLocalSync() { - return mSyncId != UNSET_SYNC_ID; + return mSyncGroup != null; } private void addFrameCommitCallbackIfNeeded() { @@ -4392,7 +4393,7 @@ public final class ViewRootImpl implements ViewParent, } if (mSurfaceHolder != null && mSurface.isValid()) { - final SurfaceSyncer.SyncBufferCallback syncBufferCallback = mSyncBufferCallback; + final SurfaceSyncGroup.SyncBufferCallback syncBufferCallback = mSyncBufferCallback; SurfaceCallbackHelper sch = new SurfaceCallbackHelper(() -> mHandler.post(() -> syncBufferCallback.onBufferReady(null))); mSyncBufferCallback = null; @@ -10929,7 +10930,7 @@ public final class ViewRootImpl implements ViewParent, } private void registerCallbacksForSync(boolean syncBuffer, - final SurfaceSyncer.SyncBufferCallback syncBufferCallback) { + final SurfaceSyncGroup.SyncBufferCallback syncBufferCallback) { if (!isHardwareEnabled()) { return; } @@ -11002,9 +11003,9 @@ public final class ViewRootImpl implements ViewParent, }); } - public final SurfaceSyncer.SyncTarget mSyncTarget = new SurfaceSyncer.SyncTarget() { + public final SurfaceSyncGroup.SyncTarget mSyncTarget = new SurfaceSyncGroup.SyncTarget() { @Override - public void onReadyToSync(SurfaceSyncer.SyncBufferCallback syncBufferCallback) { + public void onReadyToSync(SurfaceSyncGroup.SyncBufferCallback syncBufferCallback) { readyToSync(syncBufferCallback); } @@ -11018,7 +11019,12 @@ public final class ViewRootImpl implements ViewParent, } }; - private void readyToSync(SurfaceSyncer.SyncBufferCallback syncBufferCallback) { + @Override + public SurfaceSyncGroup.SyncTarget getSyncTarget() { + return mSyncTarget; + } + + private void readyToSync(SurfaceSyncGroup.SyncBufferCallback syncBufferCallback) { mNumSyncsInProgress++; if (!isInLocalSync()) { // Always sync the buffer if the sync request did not come from VRI. @@ -11041,10 +11047,10 @@ public final class ViewRootImpl implements ViewParent, } } - void mergeSync(int syncId, SurfaceSyncer otherSyncer) { + void mergeSync(SurfaceSyncGroup otherSyncGroup) { if (!isInLocalSync()) { return; } - mSurfaceSyncer.merge(mSyncId, syncId, otherSyncer); + mSyncGroup.merge(otherSyncGroup); } } diff --git a/core/java/android/window/SurfaceSyncGroup.java b/core/java/android/window/SurfaceSyncGroup.java new file mode 100644 index 000000000000..5672697f665e --- /dev/null +++ b/core/java/android/window/SurfaceSyncGroup.java @@ -0,0 +1,388 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.window; + +import android.annotation.Nullable; +import android.annotation.UiThread; +import android.util.ArraySet; +import android.util.Log; +import android.util.Pair; +import android.view.AttachedSurfaceControl; +import android.view.SurfaceControl.Transaction; +import android.view.SurfaceView; + +import com.android.internal.annotations.GuardedBy; + +import java.util.Set; +import java.util.concurrent.Executor; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Used to organize syncs for surfaces. + * + * The SurfaceSyncGroup allows callers to add desired syncs into a set and wait for them to all + * complete before getting a callback. The purpose of the SurfaceSyncGroup is to be an accounting + * mechanism so each sync implementation doesn't need to handle it themselves. The SurfaceSyncGroup + * class is used the following way. + * + * 1. {@link #SurfaceSyncGroup()} constructor is called + * 2. {@link #addToSync(SyncTarget)} is called for every SyncTarget object that wants to be + * included in the sync. If the addSync is called for an {@link AttachedSurfaceControl} or + * {@link SurfaceView} it needs to be called on the UI thread. When addToSync is called, it's + * guaranteed that any UI updates that were requested before addToSync but after the last frame + * drew, will be included in the sync. + * 3. {@link #markSyncReady()} should be called when all the {@link SyncTarget}s have been added + * to the SurfaceSyncGroup. At this point, the SurfaceSyncGroup is closed and no more SyncTargets + * can be added to it. + * 4. The SurfaceSyncGroup will gather the data for each SyncTarget using the steps described below. + * When all the SyncTargets have finished, the syncRequestComplete will be invoked and the + * transaction will either be applied or sent to the caller. In most cases, only the + * SurfaceSyncGroup should be handling the Transaction object directly. However, there are some + * cases where the framework needs to send the Transaction elsewhere, like in ViewRootImpl, so that + * option is provided. + * + * The following is what happens within the {@link SurfaceSyncGroup} + * 1. Each SyncTarget will get a {@link SyncTarget#onReadyToSync} callback that contains a + * {@link SyncBufferCallback}. + * 2. Each {@link SyncTarget} needs to invoke {@link SyncBufferCallback#onBufferReady(Transaction)}. + * This makes sure the SurfaceSyncGroup knows when the SyncTarget is complete, allowing the + * SurfaceSyncGroup to get the Transaction that contains the buffer. + * 3. When the final SyncBufferCallback finishes for the SurfaceSyncGroup, in most cases the + * transaction is applied and then the sync complete callbacks are invoked, letting the callers know + * the sync is now complete. + * + * @hide + */ +public final class SurfaceSyncGroup { + private static final String TAG = "SurfaceSyncGroup"; + private static final boolean DEBUG = false; + + private static Supplier<Transaction> sTransactionFactory = Transaction::new; + + /** + * Class that collects the {@link SyncTarget}s and notifies when all the surfaces have + * a frame ready. + */ + private final Object mLock = new Object(); + + @GuardedBy("mLock") + private final Set<Integer> mPendingSyncs = new ArraySet<>(); + @GuardedBy("mLock") + private final Transaction mTransaction = sTransactionFactory.get(); + @GuardedBy("mLock") + private boolean mSyncReady; + @GuardedBy("mLock") + private final Set<SyncTarget> mSyncTargets = new ArraySet<>(); + + @GuardedBy("mLock") + private Consumer<Transaction> mSyncRequestCompleteCallback; + + @GuardedBy("mLock") + private final Set<SurfaceSyncGroup> mMergedSyncGroups = new ArraySet<>(); + + @GuardedBy("mLock") + private boolean mFinished; + + @GuardedBy("mLock") + private final ArraySet<Pair<Executor, Runnable>> mSyncCompleteCallbacks = new ArraySet<>(); + + /** + * @hide + */ + public static void setTransactionFactory(Supplier<Transaction> transactionFactory) { + sTransactionFactory = transactionFactory; + } + + /** + * Starts a sync and will automatically apply the final, merged transaction. + */ + public SurfaceSyncGroup() { + this(transaction -> { + if (transaction != null) { + transaction.apply(); + } + }); + + } + + /** + * Creates a sync. + * + * @param syncRequestComplete The complete callback that contains the syncId and transaction + * with all the sync data merged. The Transaction passed back can be + * null. + * + * NOTE: Only should be used by ViewRootImpl + * @hide + */ + public SurfaceSyncGroup(Consumer<Transaction> syncRequestComplete) { + mSyncRequestCompleteCallback = transaction -> { + syncRequestComplete.accept(transaction); + synchronized (mLock) { + for (Pair<Executor, Runnable> callback : mSyncCompleteCallbacks) { + callback.first.execute(callback.second); + } + } + }; + + if (DEBUG) { + Log.d(TAG, "setupSync"); + } + } + + /** + * Add a {@link Runnable} to be executed when the sync completes. + * + * @param executor The Executor to invoke the Runnable on + * @param runnable The Runnable to get called + */ + public void addSyncCompleteCallback(Executor executor, Runnable runnable) { + synchronized (mLock) { + mSyncCompleteCallbacks.add(new Pair<>(executor, runnable)); + } + } + + /** + * Add a SurfaceView to a sync set. This is different than + * {@link #addToSync(AttachedSurfaceControl)} because it requires the caller to notify the start + * and finish drawing in order to sync. + * + * @param surfaceView The SurfaceView to add to the sync. + * @param frameCallbackConsumer The callback that's invoked to allow the caller to notify + * the + * Syncer when the SurfaceView has started drawing and + * finished. + * @return true if the SurfaceView was successfully added to the SyncGroup, false otherwise. + */ + @UiThread + public boolean addToSync(SurfaceView surfaceView, + Consumer<SurfaceViewFrameCallback> frameCallbackConsumer) { + return addToSync(new SurfaceViewSyncTarget(surfaceView, frameCallbackConsumer)); + } + + /** + * Add a View's rootView to a sync set. + * + * @param viewRoot The viewRoot that will be add to the sync set + * @return true if the View was successfully added to the SyncGroup, false otherwise. + */ + @UiThread + public boolean addToSync(@Nullable AttachedSurfaceControl viewRoot) { + if (viewRoot == null) { + return false; + } + return addToSync(viewRoot.getSyncTarget()); + } + + /** + * Add a {@link SyncTarget} to a sync set. The sync set will wait for all + * SyncableSurfaces to complete before notifying. + * + * @param syncTarget A SyncableSurface that implements how to handle syncing + * buffers. + * @return true if the SyncTarget was successfully added to the SyncGroup, false otherwise. + */ + public boolean addToSync(SyncTarget syncTarget) { + SyncBufferCallback syncBufferCallback = new SyncBufferCallback() { + @Override + public void onBufferReady(Transaction t) { + synchronized (mLock) { + if (t != null) { + mTransaction.merge(t); + } + mPendingSyncs.remove(hashCode()); + checkIfSyncIsComplete(); + } + } + }; + + synchronized (mLock) { + if (mSyncReady) { + Log.e(TAG, "Sync " + this + " was already marked as ready. No more " + + "SyncTargets can be added."); + return false; + } + mPendingSyncs.add(syncBufferCallback.hashCode()); + mSyncTargets.add(syncTarget); + } + syncTarget.onReadyToSync(syncBufferCallback); + return true; + } + + /** + * Mark the sync set as ready to complete. No more data can be added to the specified + * syncId. + * Once the sync set is marked as ready, it will be able to complete once all Syncables in the + * set have completed their sync + */ + public void markSyncReady() { + synchronized (mLock) { + mSyncReady = true; + checkIfSyncIsComplete(); + } + } + + @GuardedBy("mLock") + private void checkIfSyncIsComplete() { + if (!mSyncReady || !mPendingSyncs.isEmpty() || !mMergedSyncGroups.isEmpty()) { + if (DEBUG) { + Log.d(TAG, "Syncable is not complete. mSyncReady=" + mSyncReady + + " mPendingSyncs=" + mPendingSyncs.size() + " mergedSyncs=" + + mMergedSyncGroups.size()); + } + return; + } + + if (DEBUG) { + Log.d(TAG, "Successfully finished sync id=" + this); + } + + for (SyncTarget syncTarget : mSyncTargets) { + syncTarget.onSyncComplete(); + } + mSyncTargets.clear(); + mSyncRequestCompleteCallback.accept(mTransaction); + mFinished = true; + } + + /** + * Add a Transaction to this sync set. This allows the caller to provide other info that + * should be synced with the buffers. + */ + public void addTransactionToSync(Transaction t) { + synchronized (mLock) { + mTransaction.merge(t); + } + } + + private void updateCallback(Consumer<Transaction> transactionConsumer) { + synchronized (mLock) { + if (mFinished) { + Log.e(TAG, "Attempting to merge SyncGroup " + this + " when sync is" + + " already complete"); + transactionConsumer.accept(null); + } + + final Consumer<Transaction> oldCallback = mSyncRequestCompleteCallback; + mSyncRequestCompleteCallback = transaction -> { + oldCallback.accept(null); + transactionConsumer.accept(transaction); + }; + } + } + + /** + * Merge a SyncGroup into this SyncGroup. Since SyncGroups could still have pending SyncTargets, + * we need to make sure those can still complete before the mergeTo SyncGroup is considered + * complete. + * + * We keep track of all the merged SyncGroups until they are marked as done, and then they + * are removed from the set. This SyncGroup is not considered done until all the merged + * SyncGroups are done. + * + * When the merged SyncGroup is complete, it will invoke the original syncRequestComplete + * callback but send an empty transaction to ensure the changes are applied early. This + * is needed in case the original sync is relying on the callback to continue processing. + * + * @param otherSyncGroup The other SyncGroup to merge into this one. + */ + public void merge(SurfaceSyncGroup otherSyncGroup) { + synchronized (mLock) { + mMergedSyncGroups.add(otherSyncGroup); + } + otherSyncGroup.updateCallback(transaction -> { + synchronized (mLock) { + mMergedSyncGroups.remove(otherSyncGroup); + if (transaction != null) { + mTransaction.merge(transaction); + } + checkIfSyncIsComplete(); + } + }); + } + + /** + * Wrapper class to help synchronize SurfaceViews + */ + private static class SurfaceViewSyncTarget implements SyncTarget { + private final SurfaceView mSurfaceView; + private final Consumer<SurfaceViewFrameCallback> mFrameCallbackConsumer; + + SurfaceViewSyncTarget(SurfaceView surfaceView, + Consumer<SurfaceViewFrameCallback> frameCallbackConsumer) { + mSurfaceView = surfaceView; + mFrameCallbackConsumer = frameCallbackConsumer; + } + + @Override + public void onReadyToSync(SyncBufferCallback syncBufferCallback) { + mFrameCallbackConsumer.accept( + () -> mSurfaceView.syncNextFrame(syncBufferCallback::onBufferReady)); + } + } + + /** + * A SyncTarget that can be added to a sync set. + */ + public interface SyncTarget { + /** + * Called when the Syncable is ready to begin handing a sync request. When invoked, the + * implementor is required to call {@link SyncBufferCallback#onBufferReady(Transaction)} + * and {@link SyncBufferCallback#onBufferReady(Transaction)} in order for this Syncable + * to be marked as complete. + * + * Always invoked on the thread that initiated the call to {@link #addToSync(SyncTarget)} + * + * @param syncBufferCallback A SyncBufferCallback that the caller must invoke onBufferReady + */ + void onReadyToSync(SyncBufferCallback syncBufferCallback); + + /** + * There's no guarantee about the thread this callback is invoked on. + */ + default void onSyncComplete() { + } + } + + /** + * Interface so the SurfaceSyncer can know when it's safe to start and when everything has been + * completed. The caller should invoke the calls when the rendering has started and finished a + * frame. + */ + public interface SyncBufferCallback { + /** + * Invoked when the transaction contains the buffer and is ready to sync. + * + * @param t The transaction that contains the buffer to be synced. This can be null if + * there's nothing to sync + */ + void onBufferReady(@Nullable Transaction t); + } + + /** + * A frame callback that is used to synchronize SurfaceViews. The owner of the SurfaceView must + * implement onFrameStarted when trying to sync the SurfaceView. This is to ensure the sync + * knows when the frame is ready to add to the sync. + */ + public interface SurfaceViewFrameCallback { + /** + * Called when the SurfaceView is going to render a frame + */ + void onFrameStarted(); + } +} diff --git a/core/java/android/window/SurfaceSyncGroup.md b/core/java/android/window/SurfaceSyncGroup.md new file mode 100644 index 000000000000..659aade24a91 --- /dev/null +++ b/core/java/android/window/SurfaceSyncGroup.md @@ -0,0 +1,86 @@ +## SurfaceSyncGroup + +### Overview + +A generic way for data to be gathered so multiple surfaces can be synced. This is intended to be used with Views, SurfaceView, and any other surface that wants to be involved in a sync. This allows different parts of the Android system to synchronize different windows and layers themselves without having to go through WindowManagerService + +### Code + +SurfaceSyncGroup is a class that manages sync requests and reports back when all participants in the sync are ready. + +##### Constructor +The first step is to create a sync request. This is done by creating a new `SurfaceSyncGroup`. +There are two constructors: one that accepts a `Consumer<Transaction>` and one that's empty. The empty constructor will automatically apply the final transaction. The second constructor should only be used by ViewRootImpl. The purpose of this one is to allow the caller to get back the merged transaction without it being applied. ViewRootImpl uses it to send the transaction to WindowManagerService to be synced there. Using this one for other cases is unsafe because the caller may hold the transaction longer than expected and prevent buffers from being latched and released. + +##### markSyncReady + +When the caller has added all the `SyncTarget` to the sync, they should call `markSyncReady()` If the caller doesn't call this, the sync will never complete since the SurfaceSyncGroup wants to give the caller a chance to add all the SyncTargets before considering the sync ready. Before `markSyncReady` is called, the `SyncTargets` can actually produce a frame, which will just be held in a transaction until all other `SyncTargets` are ready AND `markSyncReady` has been called. Once markSyncReady has been called, you cannot add any more `SyncTargets` to that particular SurfaceSyncGroup. + +##### addToSync + +The caller will invoke `addToSync` for every `SyncTarget` that it wants included. There are a few helper methods since the most common cases are Views and SurfaceView +* `addToSync(AttachedSurfaceControl)` - This is used for syncing the root of the View, specificially the ViewRootImpl +* `addToSync(SurfaceView, Consumer<SurfaceViewFrameCallback>)` - This is to sync a SurfaceView. Since SurfaceViews are rendered by the app, the caller will be expected to provide a way to get back the buffer to sync. More details about that [below](#surfaceviewframecallback) +* `addToSync(SyncTarget)` - This is the generic method. It can be used to sync arbitrary info. The SyncTarget interface has required methods that need to be implemented to properly get the transaction to sync. + +When calling addToSync with either AttachedSurfaceControl or SurfaceView, it must be called on the UI Thread. This is to ensure consistent behavior, where any UI changes done while still on the UI thread are included in this frame. The next vsync will pick up those changes and request to draw. + +##### addTransactionToSync + +This is a simple method that allows callers to add generic Transactions to the sync. The caller invokes `addTransactionToSync(Transaction)`. This can be used for any additional things that need to be included in the same SyncGroup. + +##### merge + +To add more flexibility to Syncs, an API is provided to merge SurfaceSyncGroups. The caller provides the SurfaceSyncGroup it wants merged. The current SurfaceSyncGroup will now wait for the passed in SurfaceSyncGroup to complete, as well as its own SyncTargets to complete before invoking the callback. The passed in SurfaceSyncGroup will also get a complete callback but only when its SurfaceSyncGroup completes, not the one it merged into. If a `Consumer<Transaction>` was passed in to the SurfaceSyncGroup, it will get back an emtpy Transaction so it can't accidentally apply things that were meant to be merged. + +##### addSyncCompleteCallback + +This allows callers to receive a callback when the sync is complete. The method takes in an Executor and a Runnable that will be invoked when the SurfaceSyncGroup has completed. The Executor is used to invoke the callback on the desired thread. You can add more than one callback. + +##### SyncTarget + +This interface is used to handle syncs. The interface has two methods +* `onReadyToSync(SyncBufferCallback)` - This one must be implemented. The sync will notify the `SyncTarget` so it can invoke the `SyncBufferCallback`, letting the sync know when it's ready. +* `onSyncComplete()` - This method is optional. It's used to notify the `SyncTarget` that the entire sync is complete. This is similar to the callback sent in `setupSync`, but it's invoked to the `SyncTargets` rather than the caller who started the sync. This is used by ViewRootImpl to restore the state when the entire sync is done + +When syncing ViewRootImpl, these methods are implemented already since ViewRootImpl handles the rendering requests and timing. + +##### SyncBufferCallback + +This interface is used to tell the sync that this SyncTarget is ready. There's only method here, `onBufferReady(Transaction)`, that sends back the transaction that contains the data to be synced, normally with a buffer. + +##### SurfaceViewFrameCallback + +As mentioned above, SurfaceViews are a special case because the buffers produced are handled by the app, and not the framework. Because of this, the SurfaceSyncGroup doesn't know which frame to sync. Therefore, to sync SurfaceViews, the caller must provide a way to notify the SurfaceSyncGroup that it's going to render a buffer and that this next buffer is the one to sync. The `SurfaceViewFrameCallback` has one method `onFrameStarted()`. When this is invoked, the SurfaceSyncGroup sets up a request to sync the next buffer for the SurfaceView. + + +### Example + +A simple example where you want to sync two windows and also include a transaction in the sync + +```java +SurfaceSyncGroup syncGroup = new SurfaceSyncGroup(); +SyncGroup.addSyncCompleteCallback(mMainThreadExecutor, () -> { + Log.d(TAG, "syncComplete"); +}; +syncGroup.addToSync(view1.getRootSurfaceControl()); +syncGroup.addToSync(view2.getRootSurfaceControl()); +syncGroup.addTransactionToSync(transaction); +syncGroup.markSyncReady(); +``` + +A SurfaceView example: +See `frameworks/base/tests/SurfaceViewSyncTest` for a working example + +```java +SurfaceSyncGroup syncGroup = new SurfaceSyncGroup(); +syncGroup.addSyncCompleteCallback(mMainThreadExecutor, () -> { + Log.d(TAG, "syncComplete"); +}; +syncGroup.addToSync(container.getRootSurfaceControl()); +syncGroup.addToSync(surfaceView, frameCallback -> { + // Call this when the SurfaceView is ready to render a new frame with the changes. + frameCallback.onFrameStarted() +} +syncGroup.markSyncReady(); +```
\ No newline at end of file diff --git a/core/java/android/window/SurfaceSyncer.java b/core/java/android/window/SurfaceSyncer.java deleted file mode 100644 index e6eb07162a3b..000000000000 --- a/core/java/android/window/SurfaceSyncer.java +++ /dev/null @@ -1,472 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.window; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.annotation.UiThread; -import android.os.Handler; -import android.os.Looper; -import android.util.ArraySet; -import android.util.Log; -import android.util.SparseArray; -import android.view.SurfaceControl.Transaction; -import android.view.SurfaceView; -import android.view.View; -import android.view.ViewRootImpl; - -import com.android.internal.annotations.GuardedBy; - -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * Used to organize syncs for surfaces. - * - * The SurfaceSyncer allows callers to add desired syncs into a set and wait for them to all - * complete before getting a callback. The purpose of the Syncer is to be an accounting mechanism - * so each sync implementation doesn't need to handle it themselves. The Syncer class is used the - * following way. - * - * 1. {@link #setupSync(Runnable)} is called - * 2. {@link #addToSync(int, SyncTarget)} is called for every SyncTarget object that wants to be - * included in the sync. If the addSync is called for a View or SurfaceView it needs to be called - * on the UI thread. When addToSync is called, it's guaranteed that any UI updates that were - * requested before addToSync but after the last frame drew, will be included in the sync. - * 3. {@link #markSyncReady(int)} should be called when all the {@link SyncTarget}s have been added - * to the SyncSet. Now the SyncSet is closed and no more SyncTargets can be added to it. - * 4. The SyncSet will gather the data for each SyncTarget using the steps described below. When - * all the SyncTargets have finished, the syncRequestComplete will be invoked and the transaction - * will either be applied or sent to the caller. In most cases, only the SurfaceSyncer should be - * handling the Transaction object directly. However, there are some cases where the framework - * needs to send the Transaction elsewhere, like in ViewRootImpl, so that option is provided. - * - * The following is what happens within the {@link SyncSet} - * 1. Each SyncableTarget will get a {@link SyncTarget#onReadyToSync} callback that contains - * a {@link SyncBufferCallback}. - * 2. Each {@link SyncTarget} needs to invoke {@link SyncBufferCallback#onBufferReady(Transaction)}. - * This makes sure the SyncSet knows when the SyncTarget is complete, allowing the SyncSet to get - * the Transaction that contains the buffer. - * 3. When the final SyncBufferCallback finishes for the SyncSet, the syncRequestComplete Consumer - * will be invoked with the transaction that contains all information requested in the sync. This - * could include buffers and geometry changes. The buffer update will include the UI changes that - * were requested for the View. - * - * @hide - */ -public class SurfaceSyncer { - private static final String TAG = "SurfaceSyncer"; - private static final boolean DEBUG = false; - - private static Supplier<Transaction> sTransactionFactory = Transaction::new; - - private final Object mSyncSetLock = new Object(); - @GuardedBy("mSyncSetLock") - private final SparseArray<SyncSet> mSyncSets = new SparseArray<>(); - @GuardedBy("mSyncSetLock") - private int mIdCounter = 0; - - /** - * @hide - */ - public static void setTransactionFactory(Supplier<Transaction> transactionFactory) { - sTransactionFactory = transactionFactory; - } - - /** - * Starts a sync and will automatically apply the final, merged transaction. - * - * @param onComplete The runnable that is invoked when the sync has completed. This will run on - * the same thread that the sync was started on. - * @return The syncId for the newly created sync. - * @see #setupSync(Consumer) - */ - public int setupSync(@Nullable Runnable onComplete) { - Handler handler = new Handler(Looper.myLooper()); - return setupSync(transaction -> { - transaction.apply(); - if (onComplete != null) { - handler.post(onComplete); - } - }); - } - - /** - * Starts a sync. - * - * @param syncRequestComplete The complete callback that contains the syncId and transaction - * with all the sync data merged. - * @return The syncId for the newly created sync. - * @hide - * @see #setupSync(Runnable) - */ - public int setupSync(@NonNull Consumer<Transaction> syncRequestComplete) { - synchronized (mSyncSetLock) { - final int syncId = mIdCounter++; - if (DEBUG) { - Log.d(TAG, "setupSync " + syncId); - } - SyncSet syncSet = new SyncSet(syncId, transaction -> { - synchronized (mSyncSetLock) { - mSyncSets.remove(syncId); - } - syncRequestComplete.accept(transaction); - }); - mSyncSets.put(syncId, syncSet); - return syncId; - } - } - - /** - * Mark the sync set as ready to complete. No more data can be added to the specified syncId. - * Once the sync set is marked as ready, it will be able to complete once all Syncables in the - * set have completed their sync - * - * @param syncId The syncId to mark as ready. - */ - public void markSyncReady(int syncId) { - SyncSet syncSet; - synchronized (mSyncSetLock) { - syncSet = mSyncSets.get(syncId); - } - if (syncSet == null) { - Log.e(TAG, "Failed to find syncSet for syncId=" + syncId); - return; - } - syncSet.markSyncReady(); - } - - /** - * Merge another SyncSet into the specified syncId. - * @param syncId The current syncId to merge into - * @param otherSyncId The other syncId to be merged - * @param otherSurfaceSyncer The other SurfaceSyncer where the otherSyncId is from - */ - public void merge(int syncId, int otherSyncId, SurfaceSyncer otherSurfaceSyncer) { - SyncSet syncSet; - synchronized (mSyncSetLock) { - syncSet = mSyncSets.get(syncId); - } - - SyncSet otherSyncSet = otherSurfaceSyncer.getAndValidateSyncSet(otherSyncId); - if (otherSyncSet == null) { - return; - } - - if (DEBUG) { - Log.d(TAG, - "merge id=" + otherSyncId + " from=" + otherSurfaceSyncer + " into id=" + syncId - + " from" + this); - } - syncSet.merge(otherSyncSet); - } - - /** - * Add a SurfaceView to a sync set. This is different than {@link #addToSync(int, View)} because - * it requires the caller to notify the start and finish drawing in order to sync. - * - * @param syncId The syncId to add an entry to. - * @param surfaceView The SurfaceView to add to the sync. - * @param frameCallbackConsumer The callback that's invoked to allow the caller to notify the - * Syncer when the SurfaceView has started drawing and finished. - * - * @return true if the SurfaceView was successfully added to the SyncSet, false otherwise. - */ - @UiThread - public boolean addToSync(int syncId, SurfaceView surfaceView, - Consumer<SurfaceViewFrameCallback> frameCallbackConsumer) { - return addToSync(syncId, new SurfaceViewSyncTarget(surfaceView, frameCallbackConsumer)); - } - - /** - * Add a View's rootView to a sync set. - * - * @param syncId The syncId to add an entry to. - * @param view The view where the root will be add to the sync set - * - * @return true if the View was successfully added to the SyncSet, false otherwise. - */ - @UiThread - public boolean addToSync(int syncId, @NonNull View view) { - ViewRootImpl viewRoot = view.getViewRootImpl(); - if (viewRoot == null) { - return false; - } - return addToSync(syncId, viewRoot.mSyncTarget); - } - - /** - * Add a {@link SyncTarget} to a sync set. The sync set will wait for all - * SyncableSurfaces to complete before notifying. - * - * @param syncId The syncId to add an entry to. - * @param syncTarget A SyncableSurface that implements how to handle syncing - * buffers. - * - * @return true if the SyncTarget was successfully added to the SyncSet, false otherwise. - */ - public boolean addToSync(int syncId, @NonNull SyncTarget syncTarget) { - SyncSet syncSet = getAndValidateSyncSet(syncId); - if (syncSet == null) { - return false; - } - if (DEBUG) { - Log.d(TAG, "addToSync id=" + syncId); - } - return syncSet.addSyncableSurface(syncTarget); - } - - /** - * Add a transaction to a specific sync so it can be merged along with the frames from the - * Syncables in the set. This is so the caller can add arbitrary transaction info that will be - * applied at the same time as the buffers - * @param syncId The syncId where the transaction will be merged to. - * @param t The transaction to merge in the sync set. - */ - public void addTransactionToSync(int syncId, Transaction t) { - SyncSet syncSet = getAndValidateSyncSet(syncId); - if (syncSet != null) { - syncSet.addTransactionToSync(t); - } - } - - private SyncSet getAndValidateSyncSet(int syncId) { - SyncSet syncSet; - synchronized (mSyncSetLock) { - syncSet = mSyncSets.get(syncId); - } - if (syncSet == null) { - Log.e(TAG, "Failed to find sync for id=" + syncId); - return null; - } - return syncSet; - } - - /** - * A SyncTarget that can be added to a sync set. - */ - public interface SyncTarget { - /** - * Called when the Syncable is ready to begin handing a sync request. When invoked, the - * implementor is required to call {@link SyncBufferCallback#onBufferReady(Transaction)} - * and {@link SyncBufferCallback#onBufferReady(Transaction)} in order for this Syncable - * to be marked as complete. - * - * Always invoked on the thread that initiated the call to - * {@link #addToSync(int, SyncTarget)} - * - * @param syncBufferCallback A SyncBufferCallback that the caller must invoke onBufferReady - */ - void onReadyToSync(SyncBufferCallback syncBufferCallback); - - /** - * There's no guarantee about the thread this callback is invoked on. - */ - default void onSyncComplete() {} - } - - /** - * Interface so the SurfaceSyncer can know when it's safe to start and when everything has been - * completed. The caller should invoke the calls when the rendering has started and finished a - * frame. - */ - public interface SyncBufferCallback { - /** - * Invoked when the transaction contains the buffer and is ready to sync. - * - * @param t The transaction that contains the buffer to be synced. This can be null if - * there's nothing to sync - */ - void onBufferReady(@Nullable Transaction t); - } - - /** - * Class that collects the {@link SyncTarget}s and notifies when all the surfaces have - * a frame ready. - */ - private static class SyncSet { - private final Object mLock = new Object(); - - @GuardedBy("mLock") - private final Set<Integer> mPendingSyncs = new ArraySet<>(); - @GuardedBy("mLock") - private final Transaction mTransaction = sTransactionFactory.get(); - @GuardedBy("mLock") - private boolean mSyncReady; - @GuardedBy("mLock") - private final Set<SyncTarget> mSyncTargets = new ArraySet<>(); - - private final int mSyncId; - @GuardedBy("mLock") - private Consumer<Transaction> mSyncRequestCompleteCallback; - - @GuardedBy("mLock") - private final Set<SyncSet> mMergedSyncSets = new ArraySet<>(); - - @GuardedBy("mLock") - private boolean mFinished; - - private SyncSet(int syncId, Consumer<Transaction> syncRequestComplete) { - mSyncId = syncId; - mSyncRequestCompleteCallback = syncRequestComplete; - } - - boolean addSyncableSurface(SyncTarget syncTarget) { - SyncBufferCallback syncBufferCallback = new SyncBufferCallback() { - @Override - public void onBufferReady(Transaction t) { - synchronized (mLock) { - if (t != null) { - mTransaction.merge(t); - } - mPendingSyncs.remove(hashCode()); - checkIfSyncIsComplete(); - } - } - }; - - synchronized (mLock) { - if (mSyncReady) { - Log.e(TAG, "Sync " + mSyncId + " was already marked as ready. No more " - + "SyncTargets can be added."); - return false; - } - mPendingSyncs.add(syncBufferCallback.hashCode()); - mSyncTargets.add(syncTarget); - } - syncTarget.onReadyToSync(syncBufferCallback); - return true; - } - - void markSyncReady() { - synchronized (mLock) { - mSyncReady = true; - checkIfSyncIsComplete(); - } - } - - @GuardedBy("mLock") - private void checkIfSyncIsComplete() { - if (!mSyncReady || !mPendingSyncs.isEmpty() || !mMergedSyncSets.isEmpty()) { - if (DEBUG) { - Log.d(TAG, "Syncable is not complete. mSyncReady=" + mSyncReady - + " mPendingSyncs=" + mPendingSyncs.size() + " mergedSyncs=" - + mMergedSyncSets.size()); - } - return; - } - - if (DEBUG) { - Log.d(TAG, "Successfully finished sync id=" + mSyncId); - } - - for (SyncTarget syncTarget : mSyncTargets) { - syncTarget.onSyncComplete(); - } - mSyncTargets.clear(); - mSyncRequestCompleteCallback.accept(mTransaction); - mFinished = true; - } - - /** - * Add a Transaction to this sync set. This allows the caller to provide other info that - * should be synced with the buffers. - */ - void addTransactionToSync(Transaction t) { - synchronized (mLock) { - mTransaction.merge(t); - } - } - - public void updateCallback(Consumer<Transaction> transactionConsumer) { - synchronized (mLock) { - if (mFinished) { - Log.e(TAG, "Attempting to merge SyncSet " + mSyncId + " when sync is" - + " already complete"); - transactionConsumer.accept(new Transaction()); - } - - final Consumer<Transaction> oldCallback = mSyncRequestCompleteCallback; - mSyncRequestCompleteCallback = transaction -> { - oldCallback.accept(new Transaction()); - transactionConsumer.accept(transaction); - }; - } - } - - /** - * Merge a SyncSet into this SyncSet. Since SyncSets could still have pending SyncTargets, - * we need to make sure those can still complete before the mergeTo syncSet is considered - * complete. - * - * We keep track of all the merged SyncSets until they are marked as done, and then they - * are removed from the set. This SyncSet is not considered done until all the merged - * SyncSets are done. - * - * When the merged SyncSet is complete, it will invoke the original syncRequestComplete - * callback but send an empty transaction to ensure the changes are applied early. This - * is needed in case the original sync is relying on the callback to continue processing. - * - * @param otherSyncSet The other SyncSet to merge into this one. - */ - public void merge(SyncSet otherSyncSet) { - synchronized (mLock) { - mMergedSyncSets.add(otherSyncSet); - } - otherSyncSet.updateCallback(transaction -> { - synchronized (mLock) { - mMergedSyncSets.remove(otherSyncSet); - mTransaction.merge(transaction); - checkIfSyncIsComplete(); - } - }); - } - } - - /** - * Wrapper class to help synchronize SurfaceViews - */ - private static class SurfaceViewSyncTarget implements SyncTarget { - private final SurfaceView mSurfaceView; - private final Consumer<SurfaceViewFrameCallback> mFrameCallbackConsumer; - - SurfaceViewSyncTarget(SurfaceView surfaceView, - Consumer<SurfaceViewFrameCallback> frameCallbackConsumer) { - mSurfaceView = surfaceView; - mFrameCallbackConsumer = frameCallbackConsumer; - } - - @Override - public void onReadyToSync(SyncBufferCallback syncBufferCallback) { - mFrameCallbackConsumer.accept( - () -> mSurfaceView.syncNextFrame(syncBufferCallback::onBufferReady)); - } - } - - /** - * A frame callback that is used to synchronize SurfaceViews. The owner of the SurfaceView must - * implement onFrameStarted when trying to sync the SurfaceView. This is to ensure the sync - * knows when the frame is ready to add to the sync. - */ - public interface SurfaceViewFrameCallback { - /** - * Called when the SurfaceView is going to render a frame - */ - void onFrameStarted(); - } -} diff --git a/core/java/android/window/SurfaceSyncer.md b/core/java/android/window/SurfaceSyncer.md deleted file mode 100644 index 1394bd1ad6ff..000000000000 --- a/core/java/android/window/SurfaceSyncer.md +++ /dev/null @@ -1,80 +0,0 @@ -## SurfaceSyncer - -### Overview - -A generic way for data to be gathered so multiple surfaces can be synced. This is intended to be used with Views, SurfaceView, and any other surface that wants to be involved in a sync. This allows different parts of the Android system to synchronize different windows and layers themselves without having to go through WindowManagerService - -### Code - -SurfaceSyncer is a class that manages sync requests and reports back when all participants in the sync are ready. - -##### setupSync -The first step is to create a sync request. This is done by calling `setupSync`. -There are two setupSync methods: one that accepts a `Runnable` and one that accepts a `Consumer<Transaction>`. The `setupSync(Runnable)` will automatically apply the final transaction and invokes the Runnable to notify the caller that the sync is complete. The `Runnable` can be null since not all cases care about the sync being complete. The second `setupSync(Consumer<Transaction>)` should only be used by ViewRootImpl. The purpose of this one is to allow the caller to get back the merged transaction without it being applied. ViewRootImpl uses it to send the transaction to WindowManagerService to be synced there. Using this one for other cases is unsafe because the caller may hold the transaction longer than expected and prevent buffers from being latched and released. - -The setupSync returns a syncId which is used for the other APIs - -##### markSyncReady - -When the caller has added all the `SyncTarget` to the sync, they should call `markSyncReady(syncId)` If the caller doesn't call this, the sync will never complete since the SurfaceSyncer wants to give the caller a chance to add all the SyncTargets before considering the sync ready. Before `markSyncReady` is called, the `SyncTargets` can actually produce a frame, which will just be held in a transaction until all other `SyncTargets` are ready AND `markSyncReady` has been called. Once markSyncReady has been called, you cannot add any more `SyncTargets` to that particular syncId. - -##### addToSync - -The caller will invoke `addToSync` for every `SyncTarget` that it wants included. The caller must specify which syncId they want to add the `SyncTarget` too since there can be multiple syncs open at the same time. There are a few helper methods since the most common cases are Views and SurfaceView -* `addToSync(int syncId, View)` - This is used for syncing the root of the View, specificially the ViewRootImpl -* `addToSync(int syncId, SurfaceView, Consumer<SurfaceViewFrameCallback>)` - This is to sync a SurfaceView. Since SurfaceViews are rendered by the app, the caller will be expected to provide a way to get back the buffer to sync. More details about that [below](#surfaceviewframecallback) -* `addToSync(int syncId, SyncTarget)` - This is the generic method. It can be used to sync arbitrary info. The SyncTarget interface has required methods that need to be implemented to properly get the transaction to sync. - -When calling addToSync with either View or SurfaceView, it must occur on the UI Thread. This is to ensure consistent behavior, where any UI changes done while still on the UI thread are included in this frame. The next vsync will pick up those changes and request to draw. - -##### addTransactionToSync - -This is a simple method that allows callers to add generic Transactions to the sync. The caller invokes `addTransactionToSync(int syncId, Transaction)`. This can be used for things that need to be synced with content, but aren't updating content themselves. - -##### SyncTarget - -This interface is used to handle syncs. The interface has two methods -* `onReadyToSync(SyncBufferCallback)` - This one must be implemented. The sync will notify the `SyncTarget` so it can invoke the `SyncBufferCallback`, letting the sync know when it's ready. -* `onSyncComplete()` - This method is optional. It's used to notify the `SyncTarget` that the entire sync is complete. This is similar to the callback sent in `setupSync`, but it's invoked to the `SyncTargets` rather than the caller who started the sync. This is used by ViewRootImpl to restore the state when the entire sync is done - -When syncing ViewRootImpl, these methods are implemented already since ViewRootImpl handles the rendering requests and timing. - -##### SyncBufferCallback - -This interface is used to tell the sync that this SyncTarget is ready. There's only method here, `onBufferReady(Transaction)`, that sends back the transaction that contains the data to be synced, normally with a buffer. - -##### SurfaceViewFrameCallback - -As mentioned above, SurfaceViews are a special case because the buffers produced are handled by the app, and not the framework. Because of this, the syncer doesn't know which frame to sync. Therefore, to sync SurfaceViews, the caller must provide a way to notify the syncer that it's going to render a buffer and that this next buffer is the one to sync. The `SurfaceViewFrameCallback` has one method `onFrameStarted()`. When this is invoked, the Syncer sets up a request to sync the next buffer for the SurfaceView. - - -### Example - -A simple example where you want to sync two windows and also include a transaction in the sync - -```java -SurfaceSyncer syncer = new SurfaceSyncer(); -int syncId = syncer.setupSync(() -> { - Log.d(TAG, "syncComplete"); -}; -syncer.addToSync(syncId, view1); -syncer.addToSync(syncId, view2); -syncer.addTransactionToSync(syncId, transaction); -syncer.markSyncReady(syncId); -``` - -A SurfaceView example: -See `frameworks/base/tests/SurfaceViewSyncTest` for a working example - -```java -SurfaceSyncer syncer = new SurfaceSyncer(); -int syncId = syncer.setupSync(() -> { - Log.d(TAG, "syncComplete"); -}; -syncer.addToSync(syncId, container); -syncer.addToSync(syncId, surfaceView, frameCallback -> { - // Call this when the SurfaceView is ready to render a new frame with the changes. - frameCallback.onFrameStarted() -} -syncer.markSyncReady(syncId); -```
\ No newline at end of file diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/ViewRootSync.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/ViewRootSync.kt index 77640f1992e1..163cab468fc0 100644 --- a/packages/SystemUI/animation/src/com/android/systemui/animation/ViewRootSync.kt +++ b/packages/SystemUI/animation/src/com/android/systemui/animation/ViewRootSync.kt @@ -1,12 +1,11 @@ package com.android.systemui.animation import android.view.View -import android.window.SurfaceSyncer +import android.window.SurfaceSyncGroup /** A util class to synchronize 2 view roots. */ // TODO(b/200284684): Remove this class. object ViewRootSync { - private var surfaceSyncer: SurfaceSyncer? = null /** * Synchronize the next draw between the view roots of [view] and [otherView], then run [then]. @@ -29,13 +28,11 @@ object ViewRootSync { return } - surfaceSyncer = - SurfaceSyncer().apply { - val syncId = setupSync(Runnable { then() }) - addToSync(syncId, view) - addToSync(syncId, otherView) - markSyncReady(syncId) - } + val syncGroup = SurfaceSyncGroup() + syncGroup.addSyncCompleteCallback(view.context.mainExecutor) { then() } + syncGroup.addToSync(view.rootSurfaceControl) + syncGroup.addToSync(otherView.rootSurfaceControl) + syncGroup.markSyncReady() } /** A Java-friendly API for [synchronizeNextDraw]. */ diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java b/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java index 029cabb0bc0b..718befadd2b5 100644 --- a/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java +++ b/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java @@ -31,6 +31,7 @@ import com.android.systemui.media.taptotransfer.MediaTttCommandLineHelper; import com.android.systemui.media.taptotransfer.receiver.MediaTttChipControllerReceiver; import com.android.systemui.media.taptotransfer.sender.MediaTttChipControllerSender; import com.android.systemui.people.PeopleProvider; +import com.android.systemui.statusbar.pipeline.ConnectivityInfoProcessor; import com.android.systemui.statusbar.policy.ConfigurationController; import com.android.systemui.unfold.FoldStateLogger; import com.android.systemui.unfold.FoldStateLoggingProvider; @@ -130,6 +131,7 @@ public interface SysUIComponent { getMediaTttCommandLineHelper(); getMediaMuteAwaitConnectionCli(); getNearbyMediaDevicesManager(); + getConnectivityInfoProcessor(); getUnfoldLatencyTracker().init(); getFoldStateLoggingProvider().ifPresent(FoldStateLoggingProvider::init); getFoldStateLogger().ifPresent(FoldStateLogger::init); @@ -212,6 +214,9 @@ public interface SysUIComponent { /** */ Optional<NearbyMediaDevicesManager> getNearbyMediaDevicesManager(); + /** */ + Optional<ConnectivityInfoProcessor> getConnectivityInfoProcessor(); + /** * Returns {@link CoreStartable}s that should be started with the application. */ diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java index fe9622250e67..ceb702eafe1e 100644 --- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java +++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java @@ -70,7 +70,7 @@ import com.android.systemui.statusbar.notification.row.dagger.NotificationShelfC import com.android.systemui.statusbar.phone.CentralSurfaces; import com.android.systemui.statusbar.phone.ShadeController; import com.android.systemui.statusbar.phone.dagger.CentralSurfacesComponent; -import com.android.systemui.statusbar.policy.ConfigurationController; +import com.android.systemui.statusbar.pipeline.dagger.StatusBarPipelineModule; import com.android.systemui.statusbar.policy.HeadsUpManager; import com.android.systemui.statusbar.policy.KeyguardStateController; import com.android.systemui.statusbar.policy.ZenModeController; @@ -91,7 +91,6 @@ import com.android.systemui.wallet.dagger.WalletModule; import com.android.systemui.wmshell.BubblesManager; import com.android.wm.shell.bubbles.Bubbles; import com.android.wm.shell.dagger.DynamicOverride; -import com.android.wm.shell.sysui.ShellController; import java.util.Optional; import java.util.concurrent.Executor; @@ -135,6 +134,7 @@ import dagger.Provides; SettingsUtilModule.class, SmartRepliesInflationModule.class, SmartspaceModule.class, + StatusBarPipelineModule.class, StatusBarPolicyModule.class, StatusBarWindowModule.class, SysUIConcurrencyModule.class, diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.java b/packages/SystemUI/src/com/android/systemui/flags/Flags.java index b7b0a29992ec..73bc92d270b7 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/Flags.java +++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.java @@ -151,6 +151,8 @@ public class Flags { public static final BooleanFlag STATUS_BAR_LETTERBOX_APPEARANCE = new BooleanFlag(603, false); + public static final BooleanFlag NEW_STATUS_BAR_PIPELINE = new BooleanFlag(604, false); + /***************************************/ // 700 - dialer/calls public static final BooleanFlag ONGOING_CALL_STATUS_BAR_CHIP = diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java index eda3446c8cb6..f4b7772a1453 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java @@ -57,10 +57,8 @@ import com.android.systemui.keyguard.WakefulnessLifecycle; import com.android.systemui.qs.QSPanelController; import com.android.systemui.shade.NotificationPanelView; import com.android.systemui.shade.NotificationPanelViewController; -import com.android.systemui.shade.NotificationShadeWindowView; import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.DisableFlagsLogger; -import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController; import com.android.systemui.statusbar.phone.dagger.CentralSurfacesComponent; @@ -91,19 +89,16 @@ public class CentralSurfacesCommandQueueCallbacks implements CommandQueue.Callba private final StatusBarKeyguardViewManager mStatusBarKeyguardViewManager; private final AssistManager mAssistManager; private final DozeServiceHost mDozeServiceHost; - private final SysuiStatusBarStateController mStatusBarStateController; - private final NotificationShadeWindowView mNotificationShadeWindowView; private final NotificationStackScrollLayoutController mNotificationStackScrollLayoutController; private final StatusBarHideIconsForBouncerManager mStatusBarHideIconsForBouncerManager; private final PowerManager mPowerManager; private final VibratorHelper mVibratorHelper; private final Optional<Vibrator> mVibratorOptional; - private final LightBarController mLightBarController; private final DisableFlagsLogger mDisableFlagsLogger; private final int mDisplayId; private final boolean mVibrateOnOpening; private final VibrationEffect mCameraLaunchGestureVibrationEffect; - + private final SystemBarAttributesListener mSystemBarAttributesListener; private static final VibrationAttributes HARDWARE_FEEDBACK_VIBRATION_ATTRIBUTES = VibrationAttributes.createForUsage(VibrationAttributes.USAGE_HARDWARE_FEEDBACK); @@ -126,16 +121,14 @@ public class CentralSurfacesCommandQueueCallbacks implements CommandQueue.Callba StatusBarKeyguardViewManager statusBarKeyguardViewManager, AssistManager assistManager, DozeServiceHost dozeServiceHost, - SysuiStatusBarStateController statusBarStateController, - NotificationShadeWindowView notificationShadeWindowView, NotificationStackScrollLayoutController notificationStackScrollLayoutController, StatusBarHideIconsForBouncerManager statusBarHideIconsForBouncerManager, PowerManager powerManager, VibratorHelper vibratorHelper, Optional<Vibrator> vibratorOptional, - LightBarController lightBarController, DisableFlagsLogger disableFlagsLogger, - @DisplayId int displayId) { + @DisplayId int displayId, + SystemBarAttributesListener systemBarAttributesListener) { mCentralSurfaces = centralSurfaces; mContext = context; @@ -152,20 +145,18 @@ public class CentralSurfacesCommandQueueCallbacks implements CommandQueue.Callba mStatusBarKeyguardViewManager = statusBarKeyguardViewManager; mAssistManager = assistManager; mDozeServiceHost = dozeServiceHost; - mStatusBarStateController = statusBarStateController; - mNotificationShadeWindowView = notificationShadeWindowView; mNotificationStackScrollLayoutController = notificationStackScrollLayoutController; mStatusBarHideIconsForBouncerManager = statusBarHideIconsForBouncerManager; mPowerManager = powerManager; mVibratorHelper = vibratorHelper; mVibratorOptional = vibratorOptional; - mLightBarController = lightBarController; mDisableFlagsLogger = disableFlagsLogger; mDisplayId = displayId; mVibrateOnOpening = resources.getBoolean(R.bool.config_vibrateOnIconAnimation); mCameraLaunchGestureVibrationEffect = getCameraGestureVibrationEffect( mVibratorOptional, resources); + mSystemBarAttributesListener = systemBarAttributesListener; } @Override @@ -472,14 +463,18 @@ public class CentralSurfacesCommandQueueCallbacks implements CommandQueue.Callba if (displayId != mDisplayId) { return; } - boolean barModeChanged = mCentralSurfaces.setAppearance(appearance); - - mLightBarController.onStatusBarAppearanceChanged(appearanceRegions, barModeChanged, - mCentralSurfaces.getBarMode(), navbarColorManagedByIme); - - mCentralSurfaces.updateBubblesVisibility(); - mStatusBarStateController.setSystemBarAttributes( - appearance, behavior, requestedVisibilities, packageName); + // SystemBarAttributesListener should __always__ be the top-level listener for system bar + // attributes changed. + mSystemBarAttributesListener.onSystemBarAttributesChanged( + displayId, + appearance, + appearanceRegions, + navbarColorManagedByIme, + behavior, + requestedVisibilities, + packageName, + letterboxDetails + ); } @Override diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemBarAttributesListener.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemBarAttributesListener.kt new file mode 100644 index 000000000000..a0415f2f3d7c --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemBarAttributesListener.kt @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.systemui.statusbar.phone + +import android.view.InsetsVisibilities +import android.view.WindowInsetsController.Appearance +import android.view.WindowInsetsController.Behavior +import com.android.internal.statusbar.LetterboxDetails +import com.android.internal.view.AppearanceRegion +import com.android.systemui.dump.DumpManager +import com.android.systemui.flags.FeatureFlags +import com.android.systemui.flags.Flags +import com.android.systemui.statusbar.SysuiStatusBarStateController +import com.android.systemui.statusbar.phone.dagger.CentralSurfacesComponent +import com.android.systemui.statusbar.phone.dagger.CentralSurfacesComponent.CentralSurfacesScope +import java.io.PrintWriter +import javax.inject.Inject + +/** + * Top-level listener of system attributes changed. This class is __always the first__ one to be + * notified about changes. + * + * It is responsible for modifying any attributes if necessary, and then notifying the other + * downstream listeners. + */ +@CentralSurfacesScope +class SystemBarAttributesListener +@Inject +internal constructor( + private val centralSurfaces: CentralSurfaces, + private val featureFlags: FeatureFlags, + private val letterboxAppearanceCalculator: LetterboxAppearanceCalculator, + private val statusBarStateController: SysuiStatusBarStateController, + private val lightBarController: LightBarController, + private val dumpManager: DumpManager, +) : CentralSurfacesComponent.Startable, StatusBarBoundsProvider.BoundsChangeListener { + + private var lastLetterboxAppearance: LetterboxAppearance? = null + private var lastSystemBarAttributesParams: SystemBarAttributesParams? = null + + override fun start() { + dumpManager.registerDumpable(javaClass.simpleName, this::dump) + } + + override fun stop() { + dumpManager.unregisterDumpable(javaClass.simpleName) + } + + override fun onStatusBarBoundsChanged() { + val params = lastSystemBarAttributesParams + if (params != null && shouldUseLetterboxAppearance(params.letterboxesArray)) { + onSystemBarAttributesChanged( + params.displayId, + params.appearance, + params.appearanceRegionsArray, + params.navbarColorManagedByIme, + params.behavior, + params.requestedVisibilities, + params.packageName, + params.letterboxesArray) + } + } + + fun onSystemBarAttributesChanged( + displayId: Int, + @Appearance originalAppearance: Int, + originalAppearanceRegions: Array<AppearanceRegion>, + navbarColorManagedByIme: Boolean, + @Behavior behavior: Int, + requestedVisibilities: InsetsVisibilities, + packageName: String, + letterboxDetails: Array<LetterboxDetails> + ) { + lastSystemBarAttributesParams = + SystemBarAttributesParams( + displayId, + originalAppearance, + originalAppearanceRegions.toList(), + navbarColorManagedByIme, + behavior, + requestedVisibilities, + packageName, + letterboxDetails.toList()) + + val (appearance, appearanceRegions) = + modifyAppearanceIfNeeded( + originalAppearance, originalAppearanceRegions, letterboxDetails) + + val barModeChanged = centralSurfaces.setAppearance(appearance) + + lightBarController.onStatusBarAppearanceChanged( + appearanceRegions, barModeChanged, centralSurfaces.barMode, navbarColorManagedByIme) + + centralSurfaces.updateBubblesVisibility() + statusBarStateController.setSystemBarAttributes( + appearance, behavior, requestedVisibilities, packageName) + } + + private fun modifyAppearanceIfNeeded( + appearance: Int, + appearanceRegions: Array<AppearanceRegion>, + letterboxDetails: Array<LetterboxDetails> + ): Pair<Int, Array<AppearanceRegion>> = + if (shouldUseLetterboxAppearance(letterboxDetails)) { + val letterboxAppearance = + letterboxAppearanceCalculator.getLetterboxAppearance( + appearance, appearanceRegions, letterboxDetails) + lastLetterboxAppearance = letterboxAppearance + Pair(letterboxAppearance.appearance, letterboxAppearance.appearanceRegions) + } else { + lastLetterboxAppearance = null + Pair(appearance, appearanceRegions) + } + + private fun shouldUseLetterboxAppearance(letterboxDetails: Array<LetterboxDetails>) = + isLetterboxAppearanceFlagEnabled() && letterboxDetails.isNotEmpty() + + private fun isLetterboxAppearanceFlagEnabled() = + featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE) + + private fun dump(printWriter: PrintWriter, strings: Array<String>) { + printWriter.println("lastSystemBarAttributesParams: $lastSystemBarAttributesParams") + printWriter.println("lastLetterboxAppearance: $lastLetterboxAppearance") + printWriter.println("letterbox appearance flag: ${isLetterboxAppearanceFlagEnabled()}") + } +} + +/** + * Keeps track of the parameters passed in + * [SystemBarAttributesListener.onSystemBarAttributesChanged]. + */ +private data class SystemBarAttributesParams( + val displayId: Int, + @Appearance val appearance: Int, + val appearanceRegions: List<AppearanceRegion>, + val navbarColorManagedByIme: Boolean, + @Behavior val behavior: Int, + val requestedVisibilities: InsetsVisibilities, + val packageName: String, + val letterboxes: List<LetterboxDetails>, +) { + val letterboxesArray = letterboxes.toTypedArray() + val appearanceRegionsArray = appearanceRegions.toTypedArray() +} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesStartableModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesStartableModule.java index 590522fc8751..d57e6a791489 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesStartableModule.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/CentralSurfacesStartableModule.java @@ -17,6 +17,7 @@ package com.android.systemui.statusbar.phone.dagger; import com.android.systemui.statusbar.phone.LetterboxAppearanceCalculator; +import com.android.systemui.statusbar.phone.SystemBarAttributesListener; import java.util.Set; @@ -34,4 +35,9 @@ interface CentralSurfacesStartableModule { @IntoSet CentralSurfacesComponent.Startable letterboxAppearanceCalculator( LetterboxAppearanceCalculator letterboxAppearanceCalculator); + + @Binds + @IntoSet + CentralSurfacesComponent.Startable sysBarAttrsListener( + SystemBarAttributesListener systemBarAttributesListener); } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java index ac0b9e31b80d..200f45f7f8a3 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java @@ -52,10 +52,12 @@ import com.android.systemui.statusbar.notification.stack.NotificationStackScroll import com.android.systemui.statusbar.phone.KeyguardBottomAreaView; import com.android.systemui.statusbar.phone.LetterboxAppearanceCalculator; import com.android.systemui.statusbar.phone.NotificationIconAreaController; +import com.android.systemui.statusbar.phone.StatusBarBoundsProvider; import com.android.systemui.statusbar.phone.StatusBarHideIconsForBouncerManager; import com.android.systemui.statusbar.phone.StatusBarIconController; import com.android.systemui.statusbar.phone.StatusBarLocationPublisher; import com.android.systemui.statusbar.phone.StatusIconContainer; +import com.android.systemui.statusbar.phone.SystemBarAttributesListener; import com.android.systemui.statusbar.phone.TapAgainView; import com.android.systemui.statusbar.phone.fragment.CollapsedStatusBarFragment; import com.android.systemui.statusbar.phone.fragment.CollapsedStatusBarFragmentLogger; @@ -257,6 +259,11 @@ public abstract class StatusBarViewModule { LetterboxAppearanceCalculator letterboxAppearanceCalculator ); + @Binds + @IntoSet + abstract StatusBarBoundsProvider.BoundsChangeListener sysBarAttrsListenerAsBoundsListener( + SystemBarAttributesListener systemBarAttributesListener); + /** * Creates a new {@link CollapsedStatusBarFragment}. * diff --git a/apct-tests/perftests/core/src/android/view/HandwritingImeService.java b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessor.kt index 27cb16e9a19f..bd6cf9a1d101 100644 --- a/apct-tests/perftests/core/src/android/view/HandwritingImeService.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessor.kt @@ -14,19 +14,17 @@ * limitations under the License. */ -package android.view; +package com.android.systemui.statusbar.pipeline -import android.content.ComponentName; -import android.inputmethodservice.InputMethodService; +import com.android.systemui.dagger.SysUISingleton +import javax.inject.Inject -public class HandwritingImeService extends InputMethodService { - private static final String PACKAGE_NAME = "com.android.perftests.core"; - - private static ComponentName getComponentName() { - return new ComponentName(PACKAGE_NAME, HandwritingImeService.class.getName()); - } - - static String getImeId() { - return getComponentName().flattenToShortString(); - } -} +/** + * A processor that transforms raw connectivity information that we get from callbacks and turns it + * into a list of displayable connectivity information. + * + * This will be used for the new status bar pipeline to calculate the list of icons that should be + * displayed in the RHS of the status bar. + */ +@SysUISingleton +class ConnectivityInfoProcessor @Inject constructor() diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/dagger/StatusBarPipelineModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/dagger/StatusBarPipelineModule.kt new file mode 100644 index 000000000000..734bd2d8e5b3 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/dagger/StatusBarPipelineModule.kt @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.systemui.statusbar.pipeline.dagger + +import com.android.systemui.dagger.SysUISingleton +import com.android.systemui.flags.FeatureFlags +import com.android.systemui.flags.Flags +import com.android.systemui.statusbar.pipeline.ConnectivityInfoProcessor +import dagger.Lazy +import dagger.Module +import dagger.Provides +import java.util.Optional + +@Module +class StatusBarPipelineModule { + @Provides + @SysUISingleton + fun provideConnectivityInfoProcessor( + featureFlags: FeatureFlags, + processorLazy: Lazy<ConnectivityInfoProcessor> + ): Optional<ConnectivityInfoProcessor> { + return if (featureFlags.isEnabled(Flags.NEW_STATUS_BAR_PIPELINE)) { + Optional.of(processorLazy.get()) + } else { + Optional.empty() + } + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt index 214ba16dfc44..64d025628754 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt @@ -98,7 +98,7 @@ class ChannelEditorDialogControllerTest : SysuiTestCase() { @Test fun testPrepareDialogForApp_onlyDefaultChannel() { - group.channels = listOf(channelDefault) + group.addChannel(channelDefault) controller.prepareDialogForApp(TEST_APP_NAME, TEST_PACKAGE_NAME, TEST_UID, setOf(channelDefault), appIcon, clickListener) diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java index d79f3361408b..7b7a48be5b17 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacksTest.java @@ -22,26 +22,28 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import android.app.StatusBarManager; import android.os.PowerManager; import android.os.Vibrator; import android.testing.AndroidTestingRunner; +import android.view.InsetsVisibilities; import androidx.test.filters.SmallTest; import com.android.internal.logging.MetricsLogger; import com.android.internal.logging.testing.FakeMetricsLogger; +import com.android.internal.statusbar.LetterboxDetails; +import com.android.internal.view.AppearanceRegion; import com.android.keyguard.KeyguardUpdateMonitor; import com.android.systemui.SysuiTestCase; import com.android.systemui.assist.AssistManager; import com.android.systemui.keyguard.WakefulnessLifecycle; import com.android.systemui.shade.NotificationPanelViewController; -import com.android.systemui.shade.NotificationShadeWindowView; import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.DisableFlagsLogger; -import com.android.systemui.statusbar.StatusBarStateControllerImpl; import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController; import com.android.systemui.statusbar.policy.DeviceProvisionedController; @@ -60,6 +62,7 @@ import java.util.Optional; @SmallTest @RunWith(AndroidTestingRunner.class) public class CentralSurfacesCommandQueueCallbacksTest extends SysuiTestCase { + @Mock private CentralSurfaces mCentralSurfaces; @Mock private ShadeController mShadeController; @Mock private CommandQueue mCommandQueue; @@ -74,14 +77,12 @@ public class CentralSurfacesCommandQueueCallbacksTest extends SysuiTestCase { @Mock private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager; @Mock private AssistManager mAssistManager; @Mock private DozeServiceHost mDozeServiceHost; - @Mock private StatusBarStateControllerImpl mStatusBarStateController; - @Mock private NotificationShadeWindowView mNotificationShadeWindowView; @Mock private NotificationStackScrollLayoutController mNotificationStackScrollLayoutController; @Mock private PowerManager mPowerManager; @Mock private VibratorHelper mVibratorHelper; @Mock private Vibrator mVibrator; - @Mock private LightBarController mLightBarController; @Mock private StatusBarHideIconsForBouncerManager mStatusBarHideIconsForBouncerManager; + @Mock private SystemBarAttributesListener mSystemBarAttributesListener; CentralSurfacesCommandQueueCallbacks mSbcqCallbacks; @@ -106,16 +107,14 @@ public class CentralSurfacesCommandQueueCallbacksTest extends SysuiTestCase { mStatusBarKeyguardViewManager, mAssistManager, mDozeServiceHost, - mStatusBarStateController, - mNotificationShadeWindowView, mNotificationStackScrollLayoutController, mStatusBarHideIconsForBouncerManager, mPowerManager, mVibratorHelper, Optional.of(mVibrator), - mLightBarController, new DisableFlagsLogger(), - DEFAULT_DISPLAY); + DEFAULT_DISPLAY, + mSystemBarAttributesListener); when(mDeviceProvisionedController.isCurrentUserSetup()).thenReturn(true); when(mRemoteInputQuickSettingsDisabler.adjustDisableFlags(anyInt())) @@ -170,5 +169,59 @@ public class CentralSurfacesCommandQueueCallbacksTest extends SysuiTestCase { verify(mDozeServiceHost).setAlwaysOnSuppressed(false); } + @Test + public void onSystemBarAttributesChanged_forwardsToSysBarAttrsListener() { + int displayId = DEFAULT_DISPLAY; + int appearance = 123; + AppearanceRegion[] appearanceRegions = new AppearanceRegion[]{}; + boolean navbarColorManagedByIme = true; + int behavior = 456; + InsetsVisibilities requestedVisibilities = new InsetsVisibilities(); + String packageName = "test package name"; + LetterboxDetails[] letterboxDetails = new LetterboxDetails[]{}; + + mSbcqCallbacks.onSystemBarAttributesChanged( + displayId, + appearance, + appearanceRegions, + navbarColorManagedByIme, + behavior, + requestedVisibilities, + packageName, + letterboxDetails); + + verify(mSystemBarAttributesListener).onSystemBarAttributesChanged( + displayId, + appearance, + appearanceRegions, + navbarColorManagedByIme, + behavior, + requestedVisibilities, + packageName, + letterboxDetails + ); + } + @Test + public void onSystemBarAttributesChanged_differentDisplayId_doesNotForwardToAttrsListener() { + int appearance = 123; + AppearanceRegion[] appearanceRegions = new AppearanceRegion[]{}; + boolean navbarColorManagedByIme = true; + int behavior = 456; + InsetsVisibilities requestedVisibilities = new InsetsVisibilities(); + String packageName = "test package name"; + LetterboxDetails[] letterboxDetails = new LetterboxDetails[]{}; + + mSbcqCallbacks.onSystemBarAttributesChanged( + DEFAULT_DISPLAY + 1, + appearance, + appearanceRegions, + navbarColorManagedByIme, + behavior, + requestedVisibilities, + packageName, + letterboxDetails); + + verifyZeroInteractions(mSystemBarAttributesListener); + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemBarAttributesListenerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemBarAttributesListenerTest.kt new file mode 100644 index 000000000000..fa7b2599c108 --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemBarAttributesListenerTest.kt @@ -0,0 +1,250 @@ +package com.android.systemui.statusbar.phone + +import android.graphics.Rect +import android.testing.AndroidTestingRunner +import android.view.Display +import android.view.InsetsVisibilities +import android.view.WindowInsetsController +import android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS +import android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS +import android.view.WindowInsetsController.APPEARANCE_LOW_PROFILE_BARS +import android.view.WindowInsetsController.Appearance +import androidx.test.filters.SmallTest +import com.android.internal.statusbar.LetterboxDetails +import com.android.internal.view.AppearanceRegion +import com.android.systemui.SysuiTestCase +import com.android.systemui.dump.DumpManager +import com.android.systemui.flags.FeatureFlags +import com.android.systemui.flags.Flags +import com.android.systemui.statusbar.SysuiStatusBarStateController +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers.any +import org.mockito.ArgumentMatchers.anyBoolean +import org.mockito.ArgumentMatchers.anyInt +import org.mockito.ArgumentMatchers.eq +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.Mockito.reset +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyZeroInteractions +import org.mockito.Mockito.`when` as whenever +import org.mockito.MockitoAnnotations + +@SmallTest +@RunWith(AndroidTestingRunner::class) +class SystemBarAttributesListenerTest : SysuiTestCase() { + + @Mock private lateinit var dumpManager: DumpManager + @Mock private lateinit var lightBarController: LightBarController + @Mock private lateinit var statusBarStateController: SysuiStatusBarStateController + @Mock private lateinit var letterboxAppearanceCalculator: LetterboxAppearanceCalculator + @Mock private lateinit var featureFlags: FeatureFlags + @Mock private lateinit var centralSurfaces: CentralSurfaces + + private lateinit var sysBarAttrsListener: SystemBarAttributesListener + + @Before + fun setUp() { + MockitoAnnotations.initMocks(this) + + whenever( + letterboxAppearanceCalculator.getLetterboxAppearance( + anyInt(), anyObject(), anyObject())) + .thenReturn(TEST_LETTERBOX_APPEARANCE) + + sysBarAttrsListener = + SystemBarAttributesListener( + centralSurfaces, + featureFlags, + letterboxAppearanceCalculator, + statusBarStateController, + lightBarController, + dumpManager) + } + + @Test + fun onSysBarAttrsChanged_forwardsAppearanceToCentralSurfaces() { + val appearance = APPEARANCE_LIGHT_STATUS_BARS or APPEARANCE_LIGHT_NAVIGATION_BARS + + changeSysBarAttrs(appearance) + + verify(centralSurfaces).setAppearance(appearance) + } + + @Test + fun onSysBarAttrsChanged_flagTrue_forwardsLetterboxAppearanceToCentralSurfaces() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + + changeSysBarAttrs(TEST_APPEARANCE, TEST_LETTERBOX_DETAILS) + + verify(centralSurfaces).setAppearance(TEST_LETTERBOX_APPEARANCE.appearance) + } + + @Test + fun onSysBarAttrsChanged_flagTrue_noLetterbox_forwardsOriginalAppearanceToCtrlSrfcs() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + + changeSysBarAttrs(TEST_APPEARANCE, arrayOf<LetterboxDetails>()) + + verify(centralSurfaces).setAppearance(TEST_APPEARANCE) + } + + @Test + fun onSysBarAttrsChanged_forwardsAppearanceToStatusBarStateController() { + changeSysBarAttrs(TEST_APPEARANCE) + + verify(statusBarStateController) + .setSystemBarAttributes(eq(TEST_APPEARANCE), anyInt(), any(), any()) + } + + @Test + fun onSysBarAttrsChanged_flagTrue_forwardsLetterboxAppearanceToStatusBarStateCtrl() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + + changeSysBarAttrs(TEST_APPEARANCE, TEST_LETTERBOX_DETAILS) + + verify(statusBarStateController) + .setSystemBarAttributes( + eq(TEST_LETTERBOX_APPEARANCE.appearance), anyInt(), any(), any()) + } + + @Test + fun onSysBarAttrsChanged_forwardsAppearanceToLightBarController() { + changeSysBarAttrs(TEST_APPEARANCE, TEST_APPEARANCE_REGIONS) + + verify(lightBarController) + .onStatusBarAppearanceChanged( + eq(TEST_APPEARANCE_REGIONS), anyBoolean(), anyInt(), anyBoolean()) + } + + @Test + fun onSysBarAttrsChanged_flagTrue_forwardsLetterboxAppearanceToLightBarController() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + + changeSysBarAttrs(TEST_APPEARANCE, TEST_APPEARANCE_REGIONS, TEST_LETTERBOX_DETAILS) + + verify(lightBarController) + .onStatusBarAppearanceChanged( + eq(TEST_LETTERBOX_APPEARANCE.appearanceRegions), + anyBoolean(), + anyInt(), + anyBoolean()) + } + + @Test + fun onStatusBarBoundsChanged_forwardsLetterboxAppearanceToStatusBarStateController() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + changeSysBarAttrs(TEST_APPEARANCE, TEST_APPEARANCE_REGIONS, TEST_LETTERBOX_DETAILS) + reset(centralSurfaces, lightBarController, statusBarStateController) + + sysBarAttrsListener.onStatusBarBoundsChanged() + + verify(statusBarStateController) + .setSystemBarAttributes( + eq(TEST_LETTERBOX_APPEARANCE.appearance), anyInt(), any(), any()) + } + + @Test + fun onStatusBarBoundsChanged_forwardsLetterboxAppearanceToLightBarController() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + changeSysBarAttrs(TEST_APPEARANCE, TEST_APPEARANCE_REGIONS, TEST_LETTERBOX_DETAILS) + reset(centralSurfaces, lightBarController, statusBarStateController) + + sysBarAttrsListener.onStatusBarBoundsChanged() + + verify(lightBarController) + .onStatusBarAppearanceChanged( + eq(TEST_LETTERBOX_APPEARANCE.appearanceRegions), + anyBoolean(), + anyInt(), + anyBoolean()) + } + + @Test + fun onStatusBarBoundsChanged_forwardsLetterboxAppearanceToCentralSurfaces() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + changeSysBarAttrs(TEST_APPEARANCE, TEST_APPEARANCE_REGIONS, TEST_LETTERBOX_DETAILS) + reset(centralSurfaces, lightBarController, statusBarStateController) + + sysBarAttrsListener.onStatusBarBoundsChanged() + + verify(centralSurfaces).setAppearance(TEST_LETTERBOX_APPEARANCE.appearance) + } + + @Test + fun onStatusBarBoundsChanged_previousCallEmptyLetterbox_doesNothing() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(true) + changeSysBarAttrs(TEST_APPEARANCE, TEST_APPEARANCE_REGIONS, arrayOf()) + reset(centralSurfaces, lightBarController, statusBarStateController) + + sysBarAttrsListener.onStatusBarBoundsChanged() + + verifyZeroInteractions(centralSurfaces, lightBarController, statusBarStateController) + } + + @Test + fun onStatusBarBoundsChanged_flagFalse_doesNothing() { + whenever(featureFlags.isEnabled(Flags.STATUS_BAR_LETTERBOX_APPEARANCE)).thenReturn(false) + changeSysBarAttrs(TEST_APPEARANCE, TEST_APPEARANCE_REGIONS, TEST_LETTERBOX_DETAILS) + reset(centralSurfaces, lightBarController, statusBarStateController) + + sysBarAttrsListener.onStatusBarBoundsChanged() + + verifyZeroInteractions(centralSurfaces, lightBarController, statusBarStateController) + } + + private fun changeSysBarAttrs(@Appearance appearance: Int) { + changeSysBarAttrs(appearance, arrayOf<LetterboxDetails>()) + } + + private fun changeSysBarAttrs( + @Appearance appearance: Int, + letterboxDetails: Array<LetterboxDetails> + ) { + changeSysBarAttrs(appearance, arrayOf(), letterboxDetails) + } + + private fun changeSysBarAttrs( + @Appearance appearance: Int, + appearanceRegions: Array<AppearanceRegion> + ) { + changeSysBarAttrs(appearance, appearanceRegions, arrayOf()) + } + + private fun changeSysBarAttrs( + @Appearance appearance: Int, + appearanceRegions: Array<AppearanceRegion>, + letterboxDetails: Array<LetterboxDetails> + ) { + sysBarAttrsListener.onSystemBarAttributesChanged( + Display.DEFAULT_DISPLAY, + appearance, + appearanceRegions, + /* navbarColorManagedByIme= */ false, + WindowInsetsController.BEHAVIOR_DEFAULT, + InsetsVisibilities(), + "package name", + letterboxDetails) + } + + companion object { + private const val TEST_APPEARANCE = + APPEARANCE_LIGHT_STATUS_BARS or APPEARANCE_LIGHT_NAVIGATION_BARS + private val TEST_APPEARANCE_REGION = AppearanceRegion(TEST_APPEARANCE, Rect(0, 0, 150, 300)) + private val TEST_APPEARANCE_REGIONS = arrayOf(TEST_APPEARANCE_REGION) + private val TEST_LETTERBOX_DETAILS = + arrayOf( + LetterboxDetails( + /* letterboxInnerBounds= */ Rect(0, 0, 0, 0), + /* letterboxFullBounds= */ Rect(0, 0, 0, 0), + /* appAppearance= */ 0)) + private val TEST_LETTERBOX_APPEARANCE = + LetterboxAppearance(/* appearance= */ APPEARANCE_LOW_PROFILE_BARS, arrayOf()) + } +} + +private fun <T> anyObject(): T { + return Mockito.anyObject<T>() +} diff --git a/services/core/java/com/android/server/display/AutomaticBrightnessController.java b/services/core/java/com/android/server/display/AutomaticBrightnessController.java index 6fd88411593f..114690a03324 100644 --- a/services/core/java/com/android/server/display/AutomaticBrightnessController.java +++ b/services/core/java/com/android/server/display/AutomaticBrightnessController.java @@ -46,7 +46,7 @@ import com.android.internal.annotations.VisibleForTesting; import com.android.internal.display.BrightnessSynchronizer; import com.android.internal.os.BackgroundThread; import com.android.server.EventLogTags; -import com.android.server.display.DisplayPowerController.BrightnessEvent; +import com.android.server.display.brightness.BrightnessEvent; import java.io.PrintWriter; @@ -337,14 +337,15 @@ class AutomaticBrightnessController { float getAutomaticScreenBrightness(BrightnessEvent brightnessEvent) { if (brightnessEvent != null) { - brightnessEvent.lux = - mAmbientLuxValid ? mAmbientLux : PowerManager.BRIGHTNESS_INVALID_FLOAT; - brightnessEvent.preThresholdLux = mPreThresholdLux; - brightnessEvent.preThresholdBrightness = mPreThresholdBrightness; - brightnessEvent.recommendedBrightness = mScreenAutoBrightness; - brightnessEvent.flags |= (!mAmbientLuxValid ? BrightnessEvent.FLAG_INVALID_LUX : 0) + brightnessEvent.setLux( + mAmbientLuxValid ? mAmbientLux : PowerManager.BRIGHTNESS_INVALID_FLOAT); + brightnessEvent.setPreThresholdLux(mPreThresholdLux); + brightnessEvent.setPreThresholdBrightness(mPreThresholdBrightness); + brightnessEvent.setRecommendedBrightness(mScreenAutoBrightness); + brightnessEvent.setFlags(brightnessEvent.getFlags() + | (!mAmbientLuxValid ? BrightnessEvent.FLAG_INVALID_LUX : 0) | (mDisplayPolicy == DisplayPowerRequest.POLICY_DOZE - ? BrightnessEvent.FLAG_DOZE_SCALE : 0); + ? BrightnessEvent.FLAG_DOZE_SCALE : 0)); } if (!mAmbientLuxValid) { diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java index 95c8fef12976..4e33fd07c28e 100644 --- a/services/core/java/com/android/server/display/DisplayPowerController.java +++ b/services/core/java/com/android/server/display/DisplayPowerController.java @@ -67,6 +67,8 @@ import com.android.internal.util.RingBuffer; import com.android.server.LocalServices; import com.android.server.am.BatteryStatsService; import com.android.server.display.RampAnimator.DualRampAnimator; +import com.android.server.display.brightness.BrightnessEvent; +import com.android.server.display.brightness.BrightnessReason; import com.android.server.display.color.ColorDisplayService.ColorDisplayServiceInternal; import com.android.server.display.color.ColorDisplayService.ReduceBrightColorsListener; import com.android.server.display.utils.SensorUtils; @@ -76,7 +78,6 @@ import com.android.server.display.whitebalance.DisplayWhiteBalanceSettings; import com.android.server.policy.WindowManagerPolicy; import java.io.PrintWriter; -import java.util.Objects; /** * Controls the power state of the display. @@ -1430,7 +1431,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call // we broadcast this change through setting. final float unthrottledBrightnessState = brightnessState; if (mBrightnessThrottler.isThrottled()) { - mTempBrightnessEvent.thermalMax = mBrightnessThrottler.getBrightnessCap(); + mTempBrightnessEvent.setThermalMax(mBrightnessThrottler.getBrightnessCap()); brightnessState = Math.min(brightnessState, mBrightnessThrottler.getBrightnessCap()); mBrightnessReasonTemp.addModifier(BrightnessReason.MODIFIER_THROTTLED); if (!mAppliedThrottling) { @@ -1551,8 +1552,9 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call // TODO(b/216365040): The decision to prevent HBM for HDR in low power mode should be // done in HighBrightnessModeController. if (mHbmController.getHighBrightnessMode() == BrightnessInfo.HIGH_BRIGHTNESS_MODE_HDR - && ((mBrightnessReason.modifier & BrightnessReason.MODIFIER_DIMMED) == 0 - || (mBrightnessReason.modifier & BrightnessReason.MODIFIER_LOW_POWER) == 0)) { + && ((mBrightnessReason.getModifier() & BrightnessReason.MODIFIER_DIMMED) == 0 + || (mBrightnessReason.getModifier() & BrightnessReason.MODIFIER_LOW_POWER) + == 0)) { // We want to scale HDR brightness level with the SDR level animateValue = mHbmController.getHdrBrightnessValue(); } @@ -1615,7 +1617,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call + mBrightnessReasonTemp.toString(brightnessAdjustmentFlags) + "', previous reason: '" + mBrightnessReason + "'."); mBrightnessReason.set(mBrightnessReasonTemp); - } else if (mBrightnessReasonTemp.reason == BrightnessReason.REASON_MANUAL + } else if (mBrightnessReasonTemp.getReason() == BrightnessReason.REASON_MANUAL && userSetBrightnessChanged) { Slog.v(TAG, "Brightness [" + brightnessState + "] manual adjustment."); } @@ -1624,17 +1626,19 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call // Log brightness events when a detail of significance has changed. Generally this is the // brightness itself changing, but also includes data like HBM cap, thermal throttling // brightness cap, RBC state, etc. - mTempBrightnessEvent.time = System.currentTimeMillis(); - mTempBrightnessEvent.brightness = brightnessState; - mTempBrightnessEvent.reason.set(mBrightnessReason); - mTempBrightnessEvent.hbmMax = mHbmController.getCurrentBrightnessMax(); - mTempBrightnessEvent.hbmMode = mHbmController.getHighBrightnessMode(); - mTempBrightnessEvent.flags |= (mIsRbcActive ? BrightnessEvent.FLAG_RBC : 0); + mTempBrightnessEvent.setTime(System.currentTimeMillis()); + mTempBrightnessEvent.setBrightness(brightnessState); + mTempBrightnessEvent.setReason(mBrightnessReason); + mTempBrightnessEvent.setHbmMax(mHbmController.getCurrentBrightnessMax()); + mTempBrightnessEvent.setHbmMode(mHbmController.getHighBrightnessMode()); + mTempBrightnessEvent.setFlags(mTempBrightnessEvent.getFlags() + | (mIsRbcActive ? BrightnessEvent.FLAG_RBC : 0)); // Temporary is what we use during slider interactions. We avoid logging those so that // we don't spam logcat when the slider is being used. boolean tempToTempTransition = - mTempBrightnessEvent.reason.reason == BrightnessReason.REASON_TEMPORARY - && mLastBrightnessEvent.reason.reason == BrightnessReason.REASON_TEMPORARY; + mTempBrightnessEvent.getReason().getReason() == BrightnessReason.REASON_TEMPORARY + && mLastBrightnessEvent.getReason().getReason() + == BrightnessReason.REASON_TEMPORARY; if ((!mTempBrightnessEvent.equalsMainData(mLastBrightnessEvent) && !tempToTempTransition) || brightnessAdjustmentFlags != 0) { mLastBrightnessEvent.copyFrom(mTempBrightnessEvent); @@ -1642,8 +1646,9 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call // Adjustment flags (and user-set flag) only get added after the equality checks since // they are transient. - newEvent.adjustmentFlags = brightnessAdjustmentFlags; - newEvent.flags |= (userSetBrightnessChanged ? BrightnessEvent.FLAG_USER_SET : 0); + newEvent.setAdjustmentFlags(brightnessAdjustmentFlags); + newEvent.setFlags(newEvent.getFlags() | (userSetBrightnessChanged + ? BrightnessEvent.FLAG_USER_SET : 0)); Slog.i(TAG, newEvent.toString(/* includeTime= */ false)); if (mBrightnessEventRingBuffer != null) { @@ -2734,117 +2739,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call } } - class BrightnessEvent { - static final int FLAG_RBC = 0x1; - static final int FLAG_INVALID_LUX = 0x2; - static final int FLAG_DOZE_SCALE = 0x3; - static final int FLAG_USER_SET = 0x4; - - public final BrightnessReason reason = new BrightnessReason(); - - public int displayId; - public float lux; - public float preThresholdLux; - public long time; - public float brightness; - public float recommendedBrightness; - public float preThresholdBrightness; - public float hbmMax; - public float thermalMax; - public int hbmMode; - public int flags; - public int adjustmentFlags; - - BrightnessEvent(BrightnessEvent that) { - copyFrom(that); - } - - BrightnessEvent(int displayId) { - this.displayId = displayId; - reset(); - } - - void copyFrom(BrightnessEvent that) { - displayId = that.displayId; - time = that.time; - lux = that.lux; - preThresholdLux = that.preThresholdLux; - brightness = that.brightness; - recommendedBrightness = that.recommendedBrightness; - preThresholdBrightness = that.preThresholdBrightness; - hbmMax = that.hbmMax; - thermalMax = that.thermalMax; - flags = that.flags; - hbmMode = that.hbmMode; - reason.set(that.reason); - adjustmentFlags = that.adjustmentFlags; - } - - void reset() { - time = SystemClock.uptimeMillis(); - brightness = PowerManager.BRIGHTNESS_INVALID_FLOAT; - recommendedBrightness = PowerManager.BRIGHTNESS_INVALID_FLOAT; - lux = 0; - preThresholdLux = 0; - preThresholdBrightness = PowerManager.BRIGHTNESS_INVALID_FLOAT; - hbmMax = PowerManager.BRIGHTNESS_MAX; - thermalMax = PowerManager.BRIGHTNESS_MAX; - flags = 0; - hbmMode = BrightnessInfo.HIGH_BRIGHTNESS_MODE_OFF; - reason.set(null); - adjustmentFlags = 0; - } - - boolean equalsMainData(BrightnessEvent that) { - // This equals comparison purposefully ignores time since it is regularly changing and - // we don't want to log a brightness event just because the time changed. - return displayId == that.displayId - && Float.floatToRawIntBits(brightness) - == Float.floatToRawIntBits(that.brightness) - && Float.floatToRawIntBits(recommendedBrightness) - == Float.floatToRawIntBits(that.recommendedBrightness) - && Float.floatToRawIntBits(preThresholdBrightness) - == Float.floatToRawIntBits(that.preThresholdBrightness) - && Float.floatToRawIntBits(lux) == Float.floatToRawIntBits(that.lux) - && Float.floatToRawIntBits(preThresholdLux) - == Float.floatToRawIntBits(that.preThresholdLux) - && Float.floatToRawIntBits(hbmMax) == Float.floatToRawIntBits(that.hbmMax) - && hbmMode == that.hbmMode - && Float.floatToRawIntBits(thermalMax) - == Float.floatToRawIntBits(that.thermalMax) - && flags == that.flags - && adjustmentFlags == that.adjustmentFlags - && reason.equals(that.reason); - } - - public String toString(boolean includeTime) { - return (includeTime ? TimeUtils.formatForLogging(time) + " - " : "") - + "BrightnessEvent: " - + "disp=" + displayId - + ", brt=" + brightness + ((flags & FLAG_USER_SET) != 0 ? "(user_set)" : "") - + ", rcmdBrt=" + recommendedBrightness - + ", preBrt=" + preThresholdBrightness - + ", lux=" + lux - + ", preLux=" + preThresholdLux - + ", hbmMax=" + hbmMax - + ", hbmMode=" + BrightnessInfo.hbmToString(hbmMode) - + ", thrmMax=" + thermalMax - + ", flags=" + flagsToString() - + ", reason=" + reason.toString(adjustmentFlags); - } - - @Override - public String toString() { - return toString(/* includeTime */ true); - } - private String flagsToString() { - return ((flags & FLAG_USER_SET) != 0 ? "user_set " : "") - + ((flags & FLAG_RBC) != 0 ? "rbc " : "") - + ((flags & FLAG_INVALID_LUX) != 0 ? "invalid_lux " : "") - + ((flags & FLAG_DOZE_SCALE) != 0 ? "doze_scale " : ""); - } - } private final class DisplayControllerHandler extends Handler { public DisplayControllerHandler(Looper looper) { @@ -2996,137 +2891,6 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call } } - /** - * Stores data about why the brightness was changed. Made up of one main - * {@code BrightnessReason.REASON_*} reason and various {@code BrightnessReason.MODIFIER_*} - * modifiers. - */ - private final class BrightnessReason { - static final int REASON_UNKNOWN = 0; - static final int REASON_MANUAL = 1; - static final int REASON_DOZE = 2; - static final int REASON_DOZE_DEFAULT = 3; - static final int REASON_AUTOMATIC = 4; - static final int REASON_SCREEN_OFF = 5; - static final int REASON_VR = 6; - static final int REASON_OVERRIDE = 7; - static final int REASON_TEMPORARY = 8; - static final int REASON_BOOST = 9; - static final int REASON_MAX = REASON_BOOST; - - static final int MODIFIER_DIMMED = 0x1; - static final int MODIFIER_LOW_POWER = 0x2; - static final int MODIFIER_HDR = 0x4; - static final int MODIFIER_THROTTLED = 0x8; - static final int MODIFIER_MASK = MODIFIER_DIMMED | MODIFIER_LOW_POWER | MODIFIER_HDR - | MODIFIER_THROTTLED; - - // ADJUSTMENT_* - // These things can happen at any point, even if the main brightness reason doesn't - // fundamentally change, so they're not stored. - - // Auto-brightness adjustment factor changed - static final int ADJUSTMENT_AUTO_TEMP = 0x1; - // Temporary adjustment to the auto-brightness adjustment factor. - static final int ADJUSTMENT_AUTO = 0x2; - - // One of REASON_* - public int reason; - // Any number of MODIFIER_* - public int modifier; - - public void set(BrightnessReason other) { - setReason(other == null ? REASON_UNKNOWN : other.reason); - setModifier(other == null ? 0 : other.modifier); - } - - public void setReason(int reason) { - if (reason < REASON_UNKNOWN || reason > REASON_MAX) { - Slog.w(TAG, "brightness reason out of bounds: " + reason); - } else { - this.reason = reason; - } - } - - public void setModifier(int modifier) { - if ((modifier & ~MODIFIER_MASK) != 0) { - Slog.w(TAG, "brightness modifier out of bounds: 0x" - + Integer.toHexString(modifier)); - } else { - this.modifier = modifier; - } - } - - public void addModifier(int modifier) { - setModifier(modifier | this.modifier); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof BrightnessReason)) { - return false; - } - BrightnessReason other = (BrightnessReason) obj; - return other.reason == reason && other.modifier == modifier; - } - - @Override - public int hashCode() { - return Objects.hash(reason, modifier); - } - - @Override - public String toString() { - return toString(0); - } - - public String toString(int adjustments) { - final StringBuilder sb = new StringBuilder(); - sb.append(reasonToString(reason)); - sb.append(" ["); - if ((adjustments & ADJUSTMENT_AUTO_TEMP) != 0) { - sb.append(" temp_adj"); - } - if ((adjustments & ADJUSTMENT_AUTO) != 0) { - sb.append(" auto_adj"); - } - if ((modifier & MODIFIER_LOW_POWER) != 0) { - sb.append(" low_pwr"); - } - if ((modifier & MODIFIER_DIMMED) != 0) { - sb.append(" dim"); - } - if ((modifier & MODIFIER_HDR) != 0) { - sb.append(" hdr"); - } - if ((modifier & MODIFIER_THROTTLED) != 0) { - sb.append(" throttled"); - } - int strlen = sb.length(); - if (sb.charAt(strlen - 1) == '[') { - sb.setLength(strlen - 2); - } else { - sb.append(" ]"); - } - return sb.toString(); - } - - private String reasonToString(int reason) { - switch (reason) { - case REASON_MANUAL: return "manual"; - case REASON_DOZE: return "doze"; - case REASON_DOZE_DEFAULT: return "doze_default"; - case REASON_AUTOMATIC: return "automatic"; - case REASON_SCREEN_OFF: return "screen_off"; - case REASON_VR: return "vr"; - case REASON_OVERRIDE: return "override"; - case REASON_TEMPORARY: return "temporary"; - case REASON_BOOST: return "boost"; - default: return Integer.toString(reason); - } - } - } - static class CachedBrightnessInfo { public MutableFloat brightness = new MutableFloat(PowerManager.BRIGHTNESS_INVALID_FLOAT); public MutableFloat adjustedBrightness = diff --git a/services/core/java/com/android/server/display/brightness/BrightnessEvent.java b/services/core/java/com/android/server/display/brightness/BrightnessEvent.java new file mode 100644 index 000000000000..6698612dc652 --- /dev/null +++ b/services/core/java/com/android/server/display/brightness/BrightnessEvent.java @@ -0,0 +1,262 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.server.display.brightness; + +import android.hardware.display.BrightnessInfo; +import android.os.PowerManager; +import android.os.SystemClock; +import android.util.TimeUtils; + +/** + * Represents a particular brightness change event. + */ +public final class BrightnessEvent { + public static final int FLAG_RBC = 0x1; + public static final int FLAG_INVALID_LUX = 0x2; + public static final int FLAG_DOZE_SCALE = 0x3; + public static final int FLAG_USER_SET = 0x4; + + private BrightnessReason mReason = new BrightnessReason(); + private int mDisplayId; + private float mLux; + private float mPreThresholdLux; + private long mTime; + private float mBrightness; + private float mRecommendedBrightness; + private float mPreThresholdBrightness; + private float mHbmMax; + private float mThermalMax; + private int mHbmMode; + private int mFlags; + private int mAdjustmentFlags; + + public BrightnessEvent(BrightnessEvent that) { + copyFrom(that); + } + + public BrightnessEvent(int displayId) { + this.mDisplayId = displayId; + reset(); + } + + /** + * A utility to clone a brightness event into another event + * + * @param that BrightnessEvent which is to be copied + */ + public void copyFrom(BrightnessEvent that) { + mDisplayId = that.getDisplayId(); + mTime = that.getTime(); + mLux = that.getLux(); + mPreThresholdLux = that.getPreThresholdLux(); + mBrightness = that.getBrightness(); + mRecommendedBrightness = that.getRecommendedBrightness(); + mPreThresholdBrightness = that.getPreThresholdBrightness(); + mHbmMax = that.getHbmMax(); + mThermalMax = that.getThermalMax(); + mFlags = that.getFlags(); + mHbmMode = that.getHbmMode(); + mReason.set(that.getReason()); + mAdjustmentFlags = that.getAdjustmentFlags(); + } + + /** + * A utility to reset the BrightnessEvent to default values + */ + public void reset() { + mTime = SystemClock.uptimeMillis(); + mBrightness = PowerManager.BRIGHTNESS_INVALID_FLOAT; + mRecommendedBrightness = PowerManager.BRIGHTNESS_INVALID_FLOAT; + mLux = 0; + mPreThresholdLux = 0; + mPreThresholdBrightness = PowerManager.BRIGHTNESS_INVALID_FLOAT; + mHbmMax = PowerManager.BRIGHTNESS_MAX; + mThermalMax = PowerManager.BRIGHTNESS_MAX; + mFlags = 0; + mHbmMode = BrightnessInfo.HIGH_BRIGHTNESS_MODE_OFF; + mReason.set(null); + mAdjustmentFlags = 0; + } + + /** + * A utility to compare two BrightnessEvents. This purposefully ignores comparing time as the + * two events might have been created at different times, but essentially hold the same + * underlying values + * + * @param that The brightnessEvent with which the current brightnessEvent is to be compared + * @return A boolean value representing if the two events are same or not. + */ + public boolean equalsMainData(BrightnessEvent that) { + // This equals comparison purposefully ignores time since it is regularly changing and + // we don't want to log a brightness event just because the time changed. + return mDisplayId == that.mDisplayId + && Float.floatToRawIntBits(mBrightness) + == Float.floatToRawIntBits(that.mBrightness) + && Float.floatToRawIntBits(mRecommendedBrightness) + == Float.floatToRawIntBits(that.mRecommendedBrightness) + && Float.floatToRawIntBits(mPreThresholdBrightness) + == Float.floatToRawIntBits(that.mPreThresholdBrightness) + && Float.floatToRawIntBits(mLux) == Float.floatToRawIntBits(that.mLux) + && Float.floatToRawIntBits(mPreThresholdLux) + == Float.floatToRawIntBits(that.mPreThresholdLux) + && Float.floatToRawIntBits(mHbmMax) == Float.floatToRawIntBits(that.mHbmMax) + && mHbmMode == that.mHbmMode + && Float.floatToRawIntBits(mThermalMax) + == Float.floatToRawIntBits(that.mThermalMax) + && mFlags == that.mFlags + && mAdjustmentFlags == that.mAdjustmentFlags + && mReason.equals(that.mReason); + } + + /** + * A utility to stringify a BrightnessEvent + * @param includeTime Indicates if the time field is to be added in the stringify version of the + * BrightnessEvent + * @return A stringified BrightnessEvent + */ + public String toString(boolean includeTime) { + return (includeTime ? TimeUtils.formatForLogging(mTime) + " - " : "") + + "BrightnessEvent: " + + "disp=" + mDisplayId + + ", brt=" + mBrightness + ((mFlags & FLAG_USER_SET) != 0 ? "(user_set)" : "") + + ", rcmdBrt=" + mRecommendedBrightness + + ", preBrt=" + mPreThresholdBrightness + + ", lux=" + mLux + + ", preLux=" + mPreThresholdLux + + ", hbmMax=" + mHbmMax + + ", hbmMode=" + BrightnessInfo.hbmToString(mHbmMode) + + ", thrmMax=" + mThermalMax + + ", flags=" + flagsToString() + + ", reason=" + mReason.toString(mAdjustmentFlags); + } + + @Override + public String toString() { + return toString(/* includeTime */ true); + } + + public void setReason(BrightnessReason reason) { + this.mReason = reason; + } + + public BrightnessReason getReason() { + return mReason; + } + + public int getDisplayId() { + return mDisplayId; + } + + public void setDisplayId(int displayId) { + this.mDisplayId = displayId; + } + + public float getLux() { + return mLux; + } + + public void setLux(float lux) { + this.mLux = lux; + } + + public float getPreThresholdLux() { + return mPreThresholdLux; + } + + public void setPreThresholdLux(float preThresholdLux) { + this.mPreThresholdLux = preThresholdLux; + } + + public long getTime() { + return mTime; + } + + public void setTime(long time) { + this.mTime = time; + } + + public float getBrightness() { + return mBrightness; + } + + public void setBrightness(float brightness) { + this.mBrightness = brightness; + } + + public float getRecommendedBrightness() { + return mRecommendedBrightness; + } + + public void setRecommendedBrightness(float recommendedBrightness) { + this.mRecommendedBrightness = recommendedBrightness; + } + + public float getPreThresholdBrightness() { + return mPreThresholdBrightness; + } + + public void setPreThresholdBrightness(float preThresholdBrightness) { + this.mPreThresholdBrightness = preThresholdBrightness; + } + + public float getHbmMax() { + return mHbmMax; + } + + public void setHbmMax(float hbmMax) { + this.mHbmMax = hbmMax; + } + + public float getThermalMax() { + return mThermalMax; + } + + public void setThermalMax(float thermalMax) { + this.mThermalMax = thermalMax; + } + + public int getHbmMode() { + return mHbmMode; + } + + public void setHbmMode(int hbmMode) { + this.mHbmMode = hbmMode; + } + + public int getFlags() { + return mFlags; + } + + public void setFlags(int flags) { + this.mFlags = flags; + } + + public int getAdjustmentFlags() { + return mAdjustmentFlags; + } + + public void setAdjustmentFlags(int adjustmentFlags) { + this.mAdjustmentFlags = adjustmentFlags; + } + + private String flagsToString() { + return ((mFlags & FLAG_USER_SET) != 0 ? "user_set " : "") + + ((mFlags & FLAG_RBC) != 0 ? "rbc " : "") + + ((mFlags & FLAG_INVALID_LUX) != 0 ? "invalid_lux " : "") + + ((mFlags & FLAG_DOZE_SCALE) != 0 ? "doze_scale " : ""); + } +} diff --git a/services/core/java/com/android/server/display/brightness/BrightnessReason.java b/services/core/java/com/android/server/display/brightness/BrightnessReason.java new file mode 100644 index 000000000000..d8eacd930d40 --- /dev/null +++ b/services/core/java/com/android/server/display/brightness/BrightnessReason.java @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.server.display.brightness; + +import android.util.Slog; + +import java.util.Objects; + +/** + * Stores data about why the brightness was changed. Made up of one main + * {@code BrightnessReason.REASON_*} reason and various {@code BrightnessReason.MODIFIER_*} + * modifiers. + */ +public final class BrightnessReason { + private static final String TAG = "BrightnessReason"; + + public static final int REASON_UNKNOWN = 0; + public static final int REASON_MANUAL = 1; + public static final int REASON_DOZE = 2; + public static final int REASON_DOZE_DEFAULT = 3; + public static final int REASON_AUTOMATIC = 4; + public static final int REASON_SCREEN_OFF = 5; + public static final int REASON_VR = 6; + public static final int REASON_OVERRIDE = 7; + public static final int REASON_TEMPORARY = 8; + public static final int REASON_BOOST = 9; + public static final int REASON_MAX = REASON_BOOST; + + public static final int MODIFIER_DIMMED = 0x1; + public static final int MODIFIER_LOW_POWER = 0x2; + public static final int MODIFIER_HDR = 0x4; + public static final int MODIFIER_THROTTLED = 0x8; + public static final int MODIFIER_MASK = MODIFIER_DIMMED | MODIFIER_LOW_POWER | MODIFIER_HDR + | MODIFIER_THROTTLED; + + // ADJUSTMENT_* + // These things can happen at any point, even if the main brightness reason doesn't + // fundamentally change, so they're not stored. + + // Auto-brightness adjustment factor changed + public static final int ADJUSTMENT_AUTO_TEMP = 0x1; + // Temporary adjustment to the auto-brightness adjustment factor. + public static final int ADJUSTMENT_AUTO = 0x2; + + // One of REASON_* + private int mReason; + // Any number of MODIFIER_* + private int mModifier; + + /** + * A utility to clone a BrightnessReason from another BrightnessReason event + * + * @param other The BrightnessReason object which is to be cloned + */ + public void set(BrightnessReason other) { + setReason(other == null ? REASON_UNKNOWN : other.mReason); + setModifier(other == null ? 0 : other.mModifier); + } + + /** + * A utility to add a modifier to the BrightnessReason object + * + * @param modifier The modifier which is to be added + */ + public void addModifier(int modifier) { + setModifier(modifier | this.mModifier); + } + + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BrightnessReason)) { + return false; + } + BrightnessReason other = (BrightnessReason) obj; + return other.mReason == mReason && other.mModifier == mModifier; + } + + @Override + public int hashCode() { + return Objects.hash(mReason, mModifier); + } + + @Override + public String toString() { + return toString(0); + } + + /** + * A utility to stringify a BrightnessReason + * + * @param adjustments Indicates if the adjustments field is to be added in the stringify version + * of the BrightnessReason + * @return A stringified BrightnessReason + */ + public String toString(int adjustments) { + final StringBuilder sb = new StringBuilder(); + sb.append(reasonToString(mReason)); + sb.append(" ["); + if ((adjustments & ADJUSTMENT_AUTO_TEMP) != 0) { + sb.append(" temp_adj"); + } + if ((adjustments & ADJUSTMENT_AUTO) != 0) { + sb.append(" auto_adj"); + } + if ((mModifier & MODIFIER_LOW_POWER) != 0) { + sb.append(" low_pwr"); + } + if ((mModifier & MODIFIER_DIMMED) != 0) { + sb.append(" dim"); + } + if ((mModifier & MODIFIER_HDR) != 0) { + sb.append(" hdr"); + } + if ((mModifier & MODIFIER_THROTTLED) != 0) { + sb.append(" throttled"); + } + int strlen = sb.length(); + if (sb.charAt(strlen - 1) == '[') { + sb.setLength(strlen - 2); + } else { + sb.append(" ]"); + } + return sb.toString(); + } + + /** + * A utility to set the reason of the BrightnessReason object + * + * @param reason The value to which the reason is to be updated. + */ + public void setReason(int reason) { + if (reason < REASON_UNKNOWN || reason > REASON_MAX) { + Slog.w(TAG, "brightness reason out of bounds: " + reason); + } else { + this.mReason = reason; + } + } + + public int getReason() { + return mReason; + } + + public int getModifier() { + return mModifier; + } + + /** + * A utility to set the modified of the current BrightnessReason object + * + * @param modifier The value to which the modifier is to be updated + */ + public void setModifier(int modifier) { + if ((modifier & ~MODIFIER_MASK) != 0) { + Slog.w(TAG, "brightness modifier out of bounds: 0x" + + Integer.toHexString(modifier)); + } else { + this.mModifier = modifier; + } + } + + private String reasonToString(int reason) { + switch (reason) { + case REASON_MANUAL: + return "manual"; + case REASON_DOZE: + return "doze"; + case REASON_DOZE_DEFAULT: + return "doze_default"; + case REASON_AUTOMATIC: + return "automatic"; + case REASON_SCREEN_OFF: + return "screen_off"; + case REASON_VR: + return "vr"; + case REASON_OVERRIDE: + return "override"; + case REASON_TEMPORARY: + return "temporary"; + case REASON_BOOST: + return "boost"; + default: + return Integer.toString(reason); + } + } +} diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java index 8569dbc4ede4..f8604c0161e2 100755 --- a/services/core/java/com/android/server/notification/NotificationManagerService.java +++ b/services/core/java/com/android/server/notification/NotificationManagerService.java @@ -9924,10 +9924,16 @@ public class NotificationManagerService extends SystemService { * given NAS is bound in. */ private boolean isInteractionVisibleToListener(ManagedServiceInfo info, int userId) { - boolean isAssistantService = mAssistants.isServiceTokenValidLocked(info.service); + boolean isAssistantService = isServiceTokenValid(info.service); return !isAssistantService || info.isSameUser(userId); } + private boolean isServiceTokenValid(IInterface service) { + synchronized (mNotificationLock) { + return mAssistants.isServiceTokenValidLocked(service); + } + } + private boolean isPackageSuspendedForUser(String pkg, int uid) { final long identity = Binder.clearCallingIdentity(); int userId = UserHandle.getUserId(uid); @@ -11189,7 +11195,7 @@ public class NotificationManagerService extends SystemService { BackgroundThread.getHandler().post(() -> { if (info.isSystem || hasCompanionDevice(info) - || mAssistants.isServiceTokenValidLocked(info.service)) { + || isServiceTokenValid(info.service)) { notifyNotificationChannelChanged( info, pkg, user, channel, modificationType); } diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java index 066692d374d0..477b8da61e0f 100644 --- a/services/core/java/com/android/server/notification/PreferencesHelper.java +++ b/services/core/java/com/android/server/notification/PreferencesHelper.java @@ -86,7 +86,6 @@ import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -1328,17 +1327,16 @@ public class PreferencesHelper implements RankingConfig { return null; } NotificationChannelGroup group = r.groups.get(groupId).clone(); - ArrayList channels = new ArrayList(); + group.setChannels(new ArrayList<>()); int N = r.channels.size(); for (int i = 0; i < N; i++) { final NotificationChannel nc = r.channels.valueAt(i); if (includeDeleted || !nc.isDeleted()) { if (groupId.equals(nc.getGroup())) { - channels.add(nc); + group.addChannel(nc); } } } - group.setChannels(channels); return group; } } @@ -1359,48 +1357,44 @@ public class PreferencesHelper implements RankingConfig { public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg, int uid, boolean includeDeleted, boolean includeNonGrouped, boolean includeEmpty) { Objects.requireNonNull(pkg); - List<NotificationChannelGroup> groups = new ArrayList<>(); + Map<String, NotificationChannelGroup> groups = new ArrayMap<>(); synchronized (mPackagePreferences) { PackagePreferences r = getPackagePreferencesLocked(pkg, uid); if (r == null) { return ParceledListSlice.emptyList(); } - Map<String, ArrayList<NotificationChannel>> groupedChannels = new HashMap(); + NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null); int N = r.channels.size(); for (int i = 0; i < N; i++) { final NotificationChannel nc = r.channels.valueAt(i); if (includeDeleted || !nc.isDeleted()) { if (nc.getGroup() != null) { if (r.groups.get(nc.getGroup()) != null) { - ArrayList<NotificationChannel> channels = groupedChannels.getOrDefault( - nc.getGroup(), new ArrayList<>()); - channels.add(nc); - groupedChannels.put(nc.getGroup(), channels); + NotificationChannelGroup ncg = groups.get(nc.getGroup()); + if (ncg == null) { + ncg = r.groups.get(nc.getGroup()).clone(); + ncg.setChannels(new ArrayList<>()); + groups.put(nc.getGroup(), ncg); + + } + ncg.addChannel(nc); } } else { - ArrayList<NotificationChannel> channels = groupedChannels.getOrDefault( - null, new ArrayList<>()); - channels.add(nc); - groupedChannels.put(null, channels); + nonGrouped.addChannel(nc); } } } - for (NotificationChannelGroup group : r.groups.values()) { - ArrayList<NotificationChannel> channels = - groupedChannels.getOrDefault(group.getId(), new ArrayList<>()); - if (includeEmpty || !channels.isEmpty()) { - NotificationChannelGroup clone = group.clone(); - clone.setChannels(channels); - groups.add(clone); - } + if (includeNonGrouped && nonGrouped.getChannels().size() > 0) { + groups.put(null, nonGrouped); } - - if (includeNonGrouped && groupedChannels.containsKey(null)) { - NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null); - nonGrouped.setChannels(groupedChannels.get(null)); - groups.add(nonGrouped); + if (includeEmpty) { + for (NotificationChannelGroup group : r.groups.values()) { + if (!groups.containsKey(group.getId())) { + groups.put(group.getId(), group); + } + } } - return new ParceledListSlice<>(groups); + return new ParceledListSlice<>(new ArrayList<>(groups.values())); } } diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java index 6ee43a0268b6..66a97b3b9a89 100644 --- a/services/core/java/com/android/server/pm/PackageInstallerService.java +++ b/services/core/java/com/android/server/pm/PackageInstallerService.java @@ -912,8 +912,10 @@ public class PackageInstallerService extends IPackageInstaller.Stub implements if (session == null || !isCallingUidOwner(session)) { throw new SecurityException("Caller has no access to session " + sessionId); } - session.params.appLabel = appLabel; - mInternalCallback.onSessionBadgingChanged(session); + if (!appLabel.equals(session.params.appLabel)) { + session.params.appLabel = appLabel; + mInternalCallback.onSessionBadgingChanged(session); + } } } diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java index 71b1bc2e24bc..bec3754536e2 100644 --- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java +++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java @@ -1207,7 +1207,7 @@ public class StatusBarManagerService extends IStatusBarService.Stub implements D private int mImeBackDisposition = 0; private boolean mShowImeSwitcher = false; private IBinder mImeToken = null; - private LetterboxDetails[] mLetterboxDetails; + private LetterboxDetails[] mLetterboxDetails = new LetterboxDetails[0]; private void setBarAttributes(@Appearance int appearance, AppearanceRegion[] appearanceRegions, boolean navbarColorManagedByIme, diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java index 136b908bb397..b54cd415d8df 100644 --- a/services/core/java/com/android/server/wm/DisplayContent.java +++ b/services/core/java/com/android/server/wm/DisplayContent.java @@ -4265,6 +4265,17 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp void detach(Transaction t) { removeImeSurface(t); } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(64); + sb.append("ImeScreenshot{"); + sb.append(Integer.toHexString(System.identityHashCode(this))); + sb.append(" imeTarget=" + mImeTarget); + sb.append(" surface=" + mImeSurface); + sb.append('}'); + return sb.toString(); + } } private void attachAndShowImeScreenshotOnTarget() { @@ -4297,15 +4308,23 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp } /** - * Removes the IME screenshot when necessary. - * - * Used when app transition animation finished or obsoleted screenshot surface like size - * changed by rotation. + * Removes the IME screenshot when the caller is a part of the attached target window. */ - void removeImeScreenshotIfPossible() { - if (mImeLayeringTarget == null - || mImeLayeringTarget.mAttrs.type != TYPE_APPLICATION_STARTING - && !mImeLayeringTarget.inTransitionSelfOrParent()) { + void removeImeSurfaceByTarget(WindowContainer win) { + if (mImeScreenshot == null || win == null) { + return; + } + // The starting window shouldn't be the input target to attach the IME screenshot during + // transitioning. + if (win.asWindowState() != null + && win.asWindowState().mAttrs.type == TYPE_APPLICATION_STARTING) { + return; + } + + final WindowState screenshotTarget = mImeScreenshot.getImeTarget(); + final boolean winIsOrContainsScreenshotTarget = (win == screenshotTarget + || win.getWindow(w -> w == screenshotTarget) != null); + if (winIsOrContainsScreenshotTarget) { removeImeSurfaceImmediately(); } } @@ -4652,10 +4671,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp wc, SurfaceAnimator.animationTypeToString(type), mImeScreenshot, mImeScreenshot.getImeTarget()); } - if (mImeScreenshot != null && (wc == mImeScreenshot.getImeTarget() - || wc.getWindow(w -> w == mImeScreenshot.getImeTarget()) != null) - && (type & WindowState.EXIT_ANIMATING_TYPES) != 0) { - removeImeSurfaceImmediately(); + if ((type & WindowState.EXIT_ANIMATING_TYPES) != 0) { + removeImeSurfaceByTarget(wc); } } diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java index 658b6acbc16d..3ef4aaeffd0c 100644 --- a/services/core/java/com/android/server/wm/WindowState.java +++ b/services/core/java/com/android/server/wm/WindowState.java @@ -2448,8 +2448,8 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP final DisplayContent dc = getDisplayContent(); if (isImeLayeringTarget()) { - // Remove the IME screenshot surface if the layering target is not animating. - dc.removeImeScreenshotIfPossible(); + // Remove the attached IME screenshot surface. + dc.removeImeSurfaceByTarget(this); // Make sure to set mImeLayeringTarget as null when the removed window is the // IME target, in case computeImeTarget may use the outdated target. dc.setImeLayeringTarget(null); @@ -3583,6 +3583,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP } else { logExclusionRestrictions(EXCLUSION_LEFT); logExclusionRestrictions(EXCLUSION_RIGHT); + getDisplayContent().removeImeSurfaceByTarget(this); } // Exclude toast because legacy apps may show toast window by themselves, so the misused // apps won't always be considered as foreground state. diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessEventTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessEventTest.java new file mode 100644 index 000000000000..e305957c6290 --- /dev/null +++ b/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessEventTest.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.server.display.brightness; + +import static org.junit.Assert.assertEquals; + +import android.hardware.display.BrightnessInfo; +import android.platform.test.annotations.Presubmit; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +@SmallTest +@Presubmit +@RunWith(AndroidJUnit4.class) +public final class BrightnessEventTest { + private BrightnessEvent mBrightnessEvent; + + @Before + public void setUp() { + mBrightnessEvent = new BrightnessEvent(1); + mBrightnessEvent.setReason( + getReason(BrightnessReason.REASON_DOZE, BrightnessReason.MODIFIER_LOW_POWER)); + mBrightnessEvent.setLux(100.0f); + mBrightnessEvent.setPreThresholdLux(150.0f); + mBrightnessEvent.setTime(System.currentTimeMillis()); + mBrightnessEvent.setBrightness(0.6f); + mBrightnessEvent.setRecommendedBrightness(0.6f); + mBrightnessEvent.setHbmMax(0.62f); + mBrightnessEvent.setThermalMax(0.65f); + mBrightnessEvent.setHbmMode(BrightnessInfo.HIGH_BRIGHTNESS_MODE_OFF); + mBrightnessEvent.setFlags(0); + mBrightnessEvent.setAdjustmentFlags(0); + } + + @Test + public void testEqualsMainDataComparesAllFieldsExceptTime() { + BrightnessEvent secondBrightnessEvent = new BrightnessEvent(1); + secondBrightnessEvent.copyFrom(mBrightnessEvent); + secondBrightnessEvent.setTime(0); + assertEquals(secondBrightnessEvent.equalsMainData(mBrightnessEvent), true); + } + + @Test + public void testToStringWorksAsExpected() { + String actualString = mBrightnessEvent.toString(false); + String expectedString = + "BrightnessEvent: disp=1, brt=0.6, rcmdBrt=0.6, preBrt=NaN, lux=100.0, preLux=150" + + ".0, hbmMax=0.62, hbmMode=off, thrmMax=0.65, flags=, reason=doze [ " + + "low_pwr ]"; + assertEquals(actualString, expectedString); + } + + private BrightnessReason getReason(int reason, int modifier) { + BrightnessReason brightnessReason = new BrightnessReason(); + brightnessReason.setReason(reason); + brightnessReason.setModifier(modifier); + return brightnessReason; + } +} diff --git a/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessReasonTest.java b/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessReasonTest.java new file mode 100644 index 000000000000..ffc2e0dfe26c --- /dev/null +++ b/services/tests/servicestests/src/com/android/server/display/brightness/BrightnessReasonTest.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.server.display.brightness; + +import static org.junit.Assert.assertEquals; + +import android.platform.test.annotations.Presubmit; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +@SmallTest +@Presubmit +@RunWith(AndroidJUnit4.class) +public final class BrightnessReasonTest { + private BrightnessReason mBrightnessReason; + + @Before + public void setUp() { + mBrightnessReason = getReason(BrightnessReason.REASON_DOZE, + BrightnessReason.MODIFIER_LOW_POWER); + } + + @Test + public void setSetsAppropriateValues() { + mBrightnessReason.set(null); + assertEquals(mBrightnessReason.getReason(), BrightnessReason.REASON_UNKNOWN); + assertEquals(mBrightnessReason.getModifier(), 0); + + mBrightnessReason.set( + getReason(BrightnessReason.REASON_BOOST, BrightnessReason.MODIFIER_THROTTLED)); + assertEquals(mBrightnessReason.getReason(), BrightnessReason.REASON_BOOST); + assertEquals(mBrightnessReason.getModifier(), BrightnessReason.MODIFIER_THROTTLED); + } + + @Test + public void toStringGeneratesExpectedString() { + String actualString = mBrightnessReason.toString(); + String expectedString = "doze [ low_pwr ]"; + assertEquals(actualString, expectedString); + } + + @Test + public void setModifierDoesntSetIfModifierIsBeyondExtremes() { + int extremeModifier = 0x16; + mBrightnessReason.setModifier(extremeModifier); + assertEquals(mBrightnessReason.getModifier(), BrightnessReason.MODIFIER_LOW_POWER); + } + + @Test + public void setReasonDoesntSetIfModifierIsBeyondExtremes() { + int extremeReason = 10; + mBrightnessReason.setReason(extremeReason); + assertEquals(mBrightnessReason.getReason(), BrightnessReason.REASON_DOZE); + + extremeReason = -1; + mBrightnessReason.setReason(extremeReason); + assertEquals(mBrightnessReason.getReason(), BrightnessReason.REASON_DOZE); + } + + @Test + public void addModifierWorksAsExpected() { + mBrightnessReason.addModifier(BrightnessReason.REASON_BOOST); + assertEquals(mBrightnessReason.getModifier(), + BrightnessReason.REASON_DOZE | BrightnessReason.REASON_BOOST); + } + + private BrightnessReason getReason(int reason, int modifier) { + BrightnessReason brightnessReason = new BrightnessReason(); + brightnessReason.setReason(reason); + brightnessReason.setModifier(modifier); + return brightnessReason; + } +} diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java index 1f07b20acc13..d6b807fc223e 100644 --- a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java @@ -2207,6 +2207,52 @@ public class DisplayContentTests extends WindowTestsBase { assertNotEquals(curSnapshot, mDisplayContent.mImeScreenshot); } + @UseTestDisplay(addWindows = {W_INPUT_METHOD}) + @Test + public void testRemoveImeScreenshot_whenTargetSurfaceWasInvisible() { + final Task rootTask = createTask(mDisplayContent); + final Task task = createTaskInRootTask(rootTask, 0 /* userId */); + final ActivityRecord activity = createActivityRecord(mDisplayContent, task); + final WindowState win = createWindow(null, TYPE_BASE_APPLICATION, activity, "win"); + win.onSurfaceShownChanged(true); + makeWindowVisible(win, mDisplayContent.mInputMethodWindow); + task.getDisplayContent().prepareAppTransition(TRANSIT_CLOSE); + doReturn(true).when(task).okToAnimate(); + ArrayList<WindowContainer> sources = new ArrayList<>(); + sources.add(activity); + + mDisplayContent.setImeLayeringTarget(win); + mDisplayContent.setImeInputTarget(win); + mDisplayContent.getInsetsStateController().getImeSourceProvider().setImeShowing(true); + task.applyAnimation(null, TRANSIT_OLD_TASK_CLOSE, false /* enter */, + false /* isVoiceInteraction */, sources); + assertNotNull(mDisplayContent.mImeScreenshot); + + win.onSurfaceShownChanged(false); + assertNull(mDisplayContent.mImeScreenshot); + } + + @UseTestDisplay(addWindows = {W_INPUT_METHOD}) + @Test + public void testRemoveImeScreenshot_whenWindowRemoveImmediately() { + final Task rootTask = createTask(mDisplayContent); + final Task task = createTaskInRootTask(rootTask, 0 /* userId */); + final ActivityRecord activity = createActivityRecord(mDisplayContent, task); + final WindowState win = createWindow(null, TYPE_BASE_APPLICATION, activity, "win"); + makeWindowVisible(mDisplayContent.mInputMethodWindow); + + mDisplayContent.setImeLayeringTarget(win); + mDisplayContent.setImeInputTarget(win); + mDisplayContent.getInsetsStateController().getImeSourceProvider().setImeShowing(true); + mDisplayContent.showImeScreenshot(); + assertNotNull(mDisplayContent.mImeScreenshot); + + // Expect IME snapshot will be removed when the win is IME layering target and invoked + // removeImeSurfaceByTarget. + win.removeImmediately(); + assertNull(mDisplayContent.mImeScreenshot); + } + @Test public void testRotateBounds_keepSamePhysicalPosition() { final DisplayContent dc = diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncerContinuousTest.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncGroupContinuousTest.java index 1e3250080514..8c49c26f3802 100644 --- a/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncerContinuousTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncGroupContinuousTest.java @@ -24,7 +24,7 @@ import android.app.KeyguardManager; import android.os.PowerManager; import android.view.SurfaceControl; import android.view.cts.surfacevalidator.CapturedActivity; -import android.window.SurfaceSyncer; +import android.window.SurfaceSyncGroup; import androidx.test.rule.ActivityTestRule; @@ -35,7 +35,7 @@ import org.junit.rules.TestName; import java.util.Objects; -public class SurfaceSyncerContinuousTest { +public class SurfaceSyncGroupContinuousTest { @Rule public TestName mName = new TestName(); @@ -60,7 +60,7 @@ public class SurfaceSyncerContinuousTest { @Test public void testSurfaceViewSyncDuringResize() throws Throwable { - SurfaceSyncer.setTransactionFactory(SurfaceControl.Transaction::new); - mCapturedActivity.verifyTest(new SurfaceSyncerValidatorTestCase(), mName); + SurfaceSyncGroup.setTransactionFactory(SurfaceControl.Transaction::new); + mCapturedActivity.verifyTest(new SurfaceSyncGroupValidatorTestCase(), mName); } } diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncerTest.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncGroupTest.java index 87382952314b..846a5066e036 100644 --- a/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncerTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncGroupTest.java @@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue; import android.platform.test.annotations.Presubmit; import android.view.SurfaceControl; -import android.window.SurfaceSyncer; +import android.window.SurfaceSyncGroup; import androidx.test.filters.SmallTest; @@ -35,22 +35,20 @@ import java.util.concurrent.TimeUnit; @SmallTest @Presubmit -public class SurfaceSyncerTest { - private SurfaceSyncer mSurfaceSyncer; +public class SurfaceSyncGroupTest { @Before public void setup() { - mSurfaceSyncer = new SurfaceSyncer(); - SurfaceSyncer.setTransactionFactory(StubTransaction::new); + SurfaceSyncGroup.setTransactionFactory(StubTransaction::new); } @Test public void testSyncOne() throws InterruptedException { final CountDownLatch finishedLatch = new CountDownLatch(1); - int startSyncId = mSurfaceSyncer.setupSync(transaction -> finishedLatch.countDown()); + SurfaceSyncGroup syncGroup = new SurfaceSyncGroup(transaction -> finishedLatch.countDown()); SyncTarget syncTarget = new SyncTarget(); - mSurfaceSyncer.addToSync(startSyncId, syncTarget); - mSurfaceSyncer.markSyncReady(startSyncId); + syncGroup.addToSync(syncTarget); + syncGroup.markSyncReady(); syncTarget.onBufferReady(); @@ -61,15 +59,15 @@ public class SurfaceSyncerTest { @Test public void testSyncMultiple() throws InterruptedException { final CountDownLatch finishedLatch = new CountDownLatch(1); - int startSyncId = mSurfaceSyncer.setupSync(transaction -> finishedLatch.countDown()); + SurfaceSyncGroup syncGroup = new SurfaceSyncGroup(transaction -> finishedLatch.countDown()); SyncTarget syncTarget1 = new SyncTarget(); SyncTarget syncTarget2 = new SyncTarget(); SyncTarget syncTarget3 = new SyncTarget(); - mSurfaceSyncer.addToSync(startSyncId, syncTarget1); - mSurfaceSyncer.addToSync(startSyncId, syncTarget2); - mSurfaceSyncer.addToSync(startSyncId, syncTarget3); - mSurfaceSyncer.markSyncReady(startSyncId); + syncGroup.addToSync(syncTarget1); + syncGroup.addToSync(syncTarget2); + syncGroup.addToSync(syncTarget3); + syncGroup.markSyncReady(); syncTarget1.onBufferReady(); assertNotEquals(0, finishedLatch.getCount()); @@ -84,39 +82,36 @@ public class SurfaceSyncerTest { } @Test - public void testInvalidSyncId() { - assertFalse(mSurfaceSyncer.addToSync(0, new SyncTarget())); - } - - @Test - public void testAddSyncWhenSyncComplete() throws InterruptedException { + public void testAddSyncWhenSyncComplete() { final CountDownLatch finishedLatch = new CountDownLatch(1); - int startSyncId = mSurfaceSyncer.setupSync(transaction -> finishedLatch.countDown()); + SurfaceSyncGroup syncGroup = new SurfaceSyncGroup(transaction -> finishedLatch.countDown()); SyncTarget syncTarget1 = new SyncTarget(); SyncTarget syncTarget2 = new SyncTarget(); - assertTrue(mSurfaceSyncer.addToSync(startSyncId, syncTarget1)); - mSurfaceSyncer.markSyncReady(startSyncId); + assertTrue(syncGroup.addToSync(syncTarget1)); + syncGroup.markSyncReady(); // Adding to a sync that has been completed is also invalid since the sync id has been // cleared. - assertFalse(mSurfaceSyncer.addToSync(startSyncId, syncTarget2)); + assertFalse(syncGroup.addToSync(syncTarget2)); } @Test - public void testMultipleSyncSets() throws InterruptedException { + public void testMultiplesyncGroups() throws InterruptedException { final CountDownLatch finishedLatch1 = new CountDownLatch(1); final CountDownLatch finishedLatch2 = new CountDownLatch(1); - int startSyncId1 = mSurfaceSyncer.setupSync(transaction -> finishedLatch1.countDown()); - int startSyncId2 = mSurfaceSyncer.setupSync(transaction -> finishedLatch2.countDown()); + SurfaceSyncGroup syncGroup1 = new SurfaceSyncGroup( + transaction -> finishedLatch1.countDown()); + SurfaceSyncGroup syncGroup2 = new SurfaceSyncGroup( + transaction -> finishedLatch2.countDown()); SyncTarget syncTarget1 = new SyncTarget(); SyncTarget syncTarget2 = new SyncTarget(); - assertTrue(mSurfaceSyncer.addToSync(startSyncId1, syncTarget1)); - assertTrue(mSurfaceSyncer.addToSync(startSyncId2, syncTarget2)); - mSurfaceSyncer.markSyncReady(startSyncId1); - mSurfaceSyncer.markSyncReady(startSyncId2); + assertTrue(syncGroup1.addToSync(syncTarget1)); + assertTrue(syncGroup2.addToSync(syncTarget2)); + syncGroup1.markSyncReady(); + syncGroup2.markSyncReady(); syncTarget1.onBufferReady(); @@ -134,19 +129,21 @@ public class SurfaceSyncerTest { public void testMergeSync() throws InterruptedException { final CountDownLatch finishedLatch1 = new CountDownLatch(1); final CountDownLatch finishedLatch2 = new CountDownLatch(1); - int startSyncId1 = mSurfaceSyncer.setupSync(transaction -> finishedLatch1.countDown()); - int startSyncId2 = mSurfaceSyncer.setupSync(transaction -> finishedLatch2.countDown()); + SurfaceSyncGroup syncGroup1 = new SurfaceSyncGroup( + transaction -> finishedLatch1.countDown()); + SurfaceSyncGroup syncGroup2 = new SurfaceSyncGroup( + transaction -> finishedLatch2.countDown()); SyncTarget syncTarget1 = new SyncTarget(); SyncTarget syncTarget2 = new SyncTarget(); - assertTrue(mSurfaceSyncer.addToSync(startSyncId1, syncTarget1)); - assertTrue(mSurfaceSyncer.addToSync(startSyncId2, syncTarget2)); - mSurfaceSyncer.markSyncReady(startSyncId1); - mSurfaceSyncer.merge(startSyncId2, startSyncId1, mSurfaceSyncer); - mSurfaceSyncer.markSyncReady(startSyncId2); + assertTrue(syncGroup1.addToSync(syncTarget1)); + assertTrue(syncGroup2.addToSync(syncTarget2)); + syncGroup1.markSyncReady(); + syncGroup2.merge(syncGroup1); + syncGroup2.markSyncReady(); - // Finish syncTarget2 first to test that the syncSet is not complete until the merged sync + // Finish syncTarget2 first to test that the syncGroup is not complete until the merged sync // is also done. syncTarget2.onBufferReady(); finishedLatch2.await(1, TimeUnit.SECONDS); @@ -167,23 +164,25 @@ public class SurfaceSyncerTest { public void testMergeSyncAlreadyComplete() throws InterruptedException { final CountDownLatch finishedLatch1 = new CountDownLatch(1); final CountDownLatch finishedLatch2 = new CountDownLatch(1); - int startSyncId1 = mSurfaceSyncer.setupSync(transaction -> finishedLatch1.countDown()); - int startSyncId2 = mSurfaceSyncer.setupSync(transaction -> finishedLatch2.countDown()); + SurfaceSyncGroup syncGroup1 = new SurfaceSyncGroup( + transaction -> finishedLatch1.countDown()); + SurfaceSyncGroup syncGroup2 = new SurfaceSyncGroup( + transaction -> finishedLatch2.countDown()); SyncTarget syncTarget1 = new SyncTarget(); SyncTarget syncTarget2 = new SyncTarget(); - assertTrue(mSurfaceSyncer.addToSync(startSyncId1, syncTarget1)); - assertTrue(mSurfaceSyncer.addToSync(startSyncId2, syncTarget2)); - mSurfaceSyncer.markSyncReady(startSyncId1); + assertTrue(syncGroup1.addToSync(syncTarget1)); + assertTrue(syncGroup2.addToSync(syncTarget2)); + syncGroup1.markSyncReady(); syncTarget1.onBufferReady(); // The first sync will still get a callback when it's sync requirements are done. finishedLatch1.await(5, TimeUnit.SECONDS); assertEquals(0, finishedLatch1.getCount()); - mSurfaceSyncer.merge(startSyncId2, startSyncId1, mSurfaceSyncer); - mSurfaceSyncer.markSyncReady(startSyncId2); + syncGroup2.merge(syncGroup1); + syncGroup2.markSyncReady(); syncTarget2.onBufferReady(); // Verify that the second sync will receive complete since the merged sync was already @@ -192,11 +191,11 @@ public class SurfaceSyncerTest { assertEquals(0, finishedLatch2.getCount()); } - private static class SyncTarget implements SurfaceSyncer.SyncTarget { - private SurfaceSyncer.SyncBufferCallback mSyncBufferCallback; + private static class SyncTarget implements SurfaceSyncGroup.SyncTarget { + private SurfaceSyncGroup.SyncBufferCallback mSyncBufferCallback; @Override - public void onReadyToSync(SurfaceSyncer.SyncBufferCallback syncBufferCallback) { + public void onReadyToSync(SurfaceSyncGroup.SyncBufferCallback syncBufferCallback) { mSyncBufferCallback = syncBufferCallback; } diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncerValidatorTestCase.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncGroupValidatorTestCase.java index d65b80ae0700..2df3085c8751 100644 --- a/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncerValidatorTestCase.java +++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceSyncGroupValidatorTestCase.java @@ -31,18 +31,18 @@ import android.view.ViewGroup; import android.view.cts.surfacevalidator.ISurfaceValidatorTestCase; import android.view.cts.surfacevalidator.PixelChecker; import android.widget.FrameLayout; -import android.window.SurfaceSyncer; +import android.window.SurfaceSyncGroup; import androidx.annotation.NonNull; /** * A validator class that will create a SurfaceView and then update its size over and over. The code * will request to sync the SurfaceView content with the main window and validate that there was - * never an empty area (black color). The test uses {@link SurfaceSyncer} class to gather the + * never an empty area (black color). The test uses {@link SurfaceSyncGroup} class to gather the * content it wants to synchronize. */ -public class SurfaceSyncerValidatorTestCase implements ISurfaceValidatorTestCase { - private static final String TAG = "SurfaceSyncerValidatorTestCase"; +public class SurfaceSyncGroupValidatorTestCase implements ISurfaceValidatorTestCase { + private static final String TAG = "SurfaceSyncGroupValidatorTestCase"; private final Runnable mRunnable = new Runnable() { @Override @@ -55,12 +55,11 @@ public class SurfaceSyncerValidatorTestCase implements ISurfaceValidatorTestCase private Handler mHandler; private SurfaceView mSurfaceView; private boolean mLastExpanded = true; - private final SurfaceSyncer mSurfaceSyncer = new SurfaceSyncer(); private RenderingThread mRenderingThread; private FrameLayout mParent; - private int mLastSyncId = -1; + private SurfaceSyncGroup mSyncGroup; final SurfaceHolder.Callback mCallback = new SurfaceHolder.Callback() { @Override @@ -76,11 +75,11 @@ public class SurfaceSyncerValidatorTestCase implements ISurfaceValidatorTestCase @Override public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) { - if (mLastSyncId >= 0) { - mSurfaceSyncer.addToSync(mLastSyncId, mSurfaceView, frameCallback -> + if (mSyncGroup != null) { + mSyncGroup.addToSync(mSurfaceView, frameCallback -> mRenderingThread.setFrameCallback(frameCallback)); - mSurfaceSyncer.markSyncReady(mLastSyncId); - mLastSyncId = -1; + mSyncGroup.markSyncReady(); + mSyncGroup = null; } } @@ -118,7 +117,7 @@ public class SurfaceSyncerValidatorTestCase implements ISurfaceValidatorTestCase } public void updateSurfaceViewSize() { - if (mRenderingThread == null || mLastSyncId >= 0 || !mRenderingThread.isReadyToSync()) { + if (mRenderingThread == null || mSyncGroup != null || !mRenderingThread.isReadyToSync()) { return; } @@ -133,8 +132,8 @@ public class SurfaceSyncerValidatorTestCase implements ISurfaceValidatorTestCase mLastExpanded = !mLastExpanded; mRenderingThread.pauseRendering(); - mLastSyncId = mSurfaceSyncer.setupSync(() -> { }); - mSurfaceSyncer.addToSync(mLastSyncId, mParent); + mSyncGroup = new SurfaceSyncGroup(); + mSyncGroup.addToSync(mParent.getRootSurfaceControl()); ViewGroup.LayoutParams svParams = mSurfaceView.getLayoutParams(); svParams.height = height; @@ -143,7 +142,7 @@ public class SurfaceSyncerValidatorTestCase implements ISurfaceValidatorTestCase private static class RenderingThread extends HandlerThread { private final SurfaceHolder mSurfaceHolder; - private SurfaceSyncer.SurfaceViewFrameCallback mFrameCallback; + private SurfaceSyncGroup.SurfaceViewFrameCallback mFrameCallback; private boolean mPauseRendering; private boolean mComplete; @@ -202,7 +201,7 @@ public class SurfaceSyncerValidatorTestCase implements ISurfaceValidatorTestCase return mFrameCallback == null; } } - public void setFrameCallback(SurfaceSyncer.SurfaceViewFrameCallback frameCallback) { + public void setFrameCallback(SurfaceSyncGroup.SurfaceViewFrameCallback frameCallback) { synchronized (this) { mFrameCallback = frameCallback; mPauseRendering = false; diff --git a/tests/SurfaceViewSyncTest/src/com/android/test/SurfaceViewSyncActivity.java b/tests/SurfaceViewSyncTest/src/com/android/test/SurfaceViewSyncActivity.java index ab7f24a8d326..03f61fa49926 100644 --- a/tests/SurfaceViewSyncTest/src/com/android/test/SurfaceViewSyncActivity.java +++ b/tests/SurfaceViewSyncTest/src/com/android/test/SurfaceViewSyncActivity.java @@ -35,11 +35,11 @@ import android.view.WindowMetrics; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Switch; -import android.window.SurfaceSyncer; +import android.window.SurfaceSyncGroup; /** * Test app that allows the user to resize the SurfaceView and have the new buffer sync with the - * main window. This tests that {@link SurfaceSyncer} is working correctly. + * main window. This tests that {@link SurfaceSyncGroup} is working correctly. */ public class SurfaceViewSyncActivity extends Activity implements SurfaceHolder.Callback { private static final String TAG = "SurfaceViewSyncActivity"; @@ -49,12 +49,10 @@ public class SurfaceViewSyncActivity extends Activity implements SurfaceHolder.C private RenderingThread mRenderingThread; - private final SurfaceSyncer mSurfaceSyncer = new SurfaceSyncer(); - private Button mExpandButton; private Switch mEnableSyncSwitch; - private int mLastSyncId = -1; + private SurfaceSyncGroup mSyncGroup; @Override protected void onCreate(Bundle savedInstanceState) { @@ -76,7 +74,7 @@ public class SurfaceViewSyncActivity extends Activity implements SurfaceHolder.C } private void updateSurfaceViewSize(Rect bounds, View container) { - if (mLastSyncId >= 0) { + if (mSyncGroup != null) { return; } @@ -91,8 +89,8 @@ public class SurfaceViewSyncActivity extends Activity implements SurfaceHolder.C mLastExpanded = !mLastExpanded; if (mEnableSyncSwitch.isChecked()) { - mLastSyncId = mSurfaceSyncer.setupSync(() -> { }); - mSurfaceSyncer.addToSync(mLastSyncId, container); + mSyncGroup = new SurfaceSyncGroup(); + mSyncGroup.addToSync(container.getRootSurfaceControl()); } ViewGroup.LayoutParams svParams = mSurfaceView.getLayoutParams(); @@ -112,14 +110,14 @@ public class SurfaceViewSyncActivity extends Activity implements SurfaceHolder.C @Override public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) { if (mEnableSyncSwitch.isChecked()) { - if (mLastSyncId < 0) { + if (mSyncGroup == null) { mRenderingThread.renderFrame(null, width, height); return; } - mSurfaceSyncer.addToSync(mLastSyncId, mSurfaceView, frameCallback -> + mSyncGroup.addToSync(mSurfaceView, frameCallback -> mRenderingThread.renderFrame(frameCallback, width, height)); - mSurfaceSyncer.markSyncReady(mLastSyncId); - mLastSyncId = -1; + mSyncGroup.markSyncReady(); + mSyncGroup = null; } else { mRenderingThread.renderFrame(null, width, height); } @@ -133,7 +131,7 @@ public class SurfaceViewSyncActivity extends Activity implements SurfaceHolder.C private static class RenderingThread extends HandlerThread { private final SurfaceHolder mSurfaceHolder; private Handler mHandler; - private SurfaceSyncer.SurfaceViewFrameCallback mFrameCallback; + private SurfaceSyncGroup.SurfaceViewFrameCallback mFrameCallback; private final Point mSurfaceSize = new Point(); int mColorValue = 0; @@ -147,7 +145,7 @@ public class SurfaceViewSyncActivity extends Activity implements SurfaceHolder.C mPaint.setTextSize(100); } - public void renderFrame(SurfaceSyncer.SurfaceViewFrameCallback frameCallback, int width, + public void renderFrame(SurfaceSyncGroup.SurfaceViewFrameCallback frameCallback, int width, int height) { if (mHandler != null) { mHandler.post(() -> { |