From a0f5e6d5b69b807f0d3635a81ae89423337168fa Mon Sep 17 00:00:00 2001 From: Suphon Thanakornpakapong Date: Sun, 8 May 2022 17:40:59 +0700 Subject: [PATCH] Update systemui shared lib --- .../src/com/android/systemui/flags/Flag.kt | 183 ++++++ .../com/android/systemui/flags/FlagManager.kt | 172 +++++ .../com/android/systemui/flags/FlagReader.kt | 43 ++ .../buttons/KeyButtonRipple.java | 531 ++++++++++++++++ .../animation/UnfoldMoveFromCenterAnimator.kt | 175 ++++++ .../navigationbar/RegionSamplingHelper.java | 302 +++++++++ .../pip/PipSurfaceTransactionHelper.java | 26 +- .../shared/plugins/PluginActionManager.java | 432 +++++++++++++ .../shared/plugins/PluginInitializer.java | 45 -- .../shared/plugins/PluginInstance.java | 228 +++++++ .../shared/plugins/PluginInstanceManager.java | 462 -------------- .../shared/plugins/PluginManager.java | 16 +- .../shared/plugins/PluginManagerImpl.java | 266 ++------ .../systemui/shared/plugins/VersionInfo.java | 12 + .../shared/recents/IOverviewProxy.aidl | 25 +- .../shared/recents/ISystemUiProxy.aidl | 17 +- .../systemui/shared/recents/model/Task.java | 16 +- .../shared/recents/model/ThumbnailData.java | 19 +- .../shared/recents/utilities/Utilities.java | 76 +++ .../shared/recents/utilities/ViewRippler.java | 55 ++ .../rotation/FloatingRotationButton.java | 311 +++++++++ ...loatingRotationButtonPositionCalculator.kt | 65 ++ .../rotation/FloatingRotationButtonView.java | 102 +++ .../shared/rotation/RotationButton.java | 59 ++ .../rotation/RotationButtonController.java | 591 ++++++++++++++++++ .../shared/system/ActivityManagerWrapper.java | 33 +- .../system/InteractionJankMonitorWrapper.java | 3 +- .../shared/system/QuickStepContract.java | 21 +- .../RecentsAnimationControllerCompat.java | 8 +- .../system/RecentsAnimationListener.java | 6 +- .../system/RemoteAnimationAdapterCompat.java | 77 +-- .../system/RemoteAnimationTargetCompat.java | 26 +- .../shared/system/RemoteTransitionCompat.java | 227 +++++-- .../shared/system/WindowManagerWrapper.java | 5 + .../statusbar/policy/CallbackController.java | 54 ++ .../unfold/UnfoldTransitionFactory.kt | 79 +++ .../UnfoldTransitionProgressProvider.kt | 38 ++ .../config/ResourceUnfoldTransitionConfig.kt | 47 ++ .../unfold/config/UnfoldTransitionConfig.kt | 21 + .../FixedTimingTransitionProgressProvider.kt | 117 ++++ ...csBasedUnfoldTransitionProgressProvider.kt | 207 ++++++ .../unfold/updates/DeviceFoldStateProvider.kt | 206 ++++++ .../unfold/updates/FoldStateProvider.kt | 59 ++ .../updates/hinge/EmptyHingeAngleProvider.kt | 17 + .../updates/hinge/HingeAngleProvider.kt | 18 + .../updates/hinge/HingeSensorAngleProvider.kt | 42 ++ .../updates/screen/ScreenStatusProvider.kt | 29 + .../NaturalRotationUnfoldProgressProvider.kt | 72 +++ .../ScaleAwareTransitionProgressProvider.kt | 50 ++ ...copedUnfoldTransitionProgressProvider.java | 142 +++++ 50 files changed, 4955 insertions(+), 878 deletions(-) create mode 100644 SystemUIShared/src/com/android/systemui/flags/Flag.kt create mode 100644 SystemUIShared/src/com/android/systemui/flags/FlagManager.kt create mode 100644 SystemUIShared/src/com/android/systemui/flags/FlagReader.kt create mode 100644 SystemUIShared/src/com/android/systemui/navigationbar/buttons/KeyButtonRipple.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/animation/UnfoldMoveFromCenterAnimator.kt create mode 100644 SystemUIShared/src/com/android/systemui/shared/navigationbar/RegionSamplingHelper.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginActionManager.java delete mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstance.java delete mode 100644 SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/recents/utilities/ViewRippler.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButton.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonPositionCalculator.kt create mode 100644 SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonView.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/rotation/RotationButton.java create mode 100644 SystemUIShared/src/com/android/systemui/shared/rotation/RotationButtonController.java create mode 100644 SystemUIShared/src/com/android/systemui/statusbar/policy/CallbackController.java create mode 100644 SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/updates/FoldStateProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt create mode 100644 SystemUIShared/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.java diff --git a/SystemUIShared/src/com/android/systemui/flags/Flag.kt b/SystemUIShared/src/com/android/systemui/flags/Flag.kt new file mode 100644 index 0000000000..9574101b46 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/flags/Flag.kt @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2021 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.flags + +import android.os.Parcel +import android.os.Parcelable + +interface Flag : Parcelable { + val id: Int + val default: T + val resourceOverride: Int + + override fun describeContents() = 0 + + fun hasResourceOverride(): Boolean { + return resourceOverride != -1 + } +} + +// Consider using the "parcelize" kotlin library. + +data class BooleanFlag @JvmOverloads constructor( + override val id: Int, + override val default: Boolean = false, + override val resourceOverride: Int = -1 +) : Flag { + + companion object { + @JvmField + val CREATOR = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel) = BooleanFlag(parcel) + override fun newArray(size: Int) = arrayOfNulls(size) + } + } + + private constructor(parcel: Parcel) : this( + id = parcel.readInt(), + default = parcel.readBoolean() + ) + + override fun writeToParcel(parcel: Parcel, flags: Int) { + parcel.writeInt(id) + parcel.writeBoolean(default) + } +} + +data class StringFlag @JvmOverloads constructor( + override val id: Int, + override val default: String = "", + override val resourceOverride: Int = -1 +) : Flag { + companion object { + @JvmField + val CREATOR = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel) = StringFlag(parcel) + override fun newArray(size: Int) = arrayOfNulls(size) + } + } + + private constructor(parcel: Parcel) : this( + id = parcel.readInt(), + default = parcel.readString() ?: "" + ) + + override fun writeToParcel(parcel: Parcel, flags: Int) { + parcel.writeInt(id) + parcel.writeString(default) + } +} + +data class IntFlag @JvmOverloads constructor( + override val id: Int, + override val default: Int = 0, + override val resourceOverride: Int = -1 +) : Flag { + + companion object { + @JvmField + val CREATOR = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel) = IntFlag(parcel) + override fun newArray(size: Int) = arrayOfNulls(size) + } + } + + private constructor(parcel: Parcel) : this( + id = parcel.readInt(), + default = parcel.readInt() + ) + + override fun writeToParcel(parcel: Parcel, flags: Int) { + parcel.writeInt(id) + parcel.writeInt(default) + } +} + +data class LongFlag @JvmOverloads constructor( + override val id: Int, + override val default: Long = 0, + override val resourceOverride: Int = -1 +) : Flag { + + companion object { + @JvmField + val CREATOR = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel) = LongFlag(parcel) + override fun newArray(size: Int) = arrayOfNulls(size) + } + } + + private constructor(parcel: Parcel) : this( + id = parcel.readInt(), + default = parcel.readLong() + ) + + override fun writeToParcel(parcel: Parcel, flags: Int) { + parcel.writeInt(id) + parcel.writeLong(default) + } +} + +data class FloatFlag @JvmOverloads constructor( + override val id: Int, + override val default: Float = 0f, + override val resourceOverride: Int = -1 +) : Flag { + + companion object { + @JvmField + val CREATOR = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel) = FloatFlag(parcel) + override fun newArray(size: Int) = arrayOfNulls(size) + } + } + + private constructor(parcel: Parcel) : this( + id = parcel.readInt(), + default = parcel.readFloat() + ) + + override fun writeToParcel(parcel: Parcel, flags: Int) { + parcel.writeInt(id) + parcel.writeFloat(default) + } +} + +data class DoubleFlag @JvmOverloads constructor( + override val id: Int, + override val default: Double = 0.0, + override val resourceOverride: Int = -1 +) : Flag { + + companion object { + @JvmField + val CREATOR = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel) = DoubleFlag(parcel) + override fun newArray(size: Int) = arrayOfNulls(size) + } + } + + private constructor(parcel: Parcel) : this( + id = parcel.readInt(), + default = parcel.readDouble() + ) + + override fun writeToParcel(parcel: Parcel, flags: Int) { + parcel.writeInt(id) + parcel.writeDouble(default) + } +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/flags/FlagManager.kt b/SystemUIShared/src/com/android/systemui/flags/FlagManager.kt new file mode 100644 index 0000000000..e61cb5c9a5 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/flags/FlagManager.kt @@ -0,0 +1,172 @@ +/* + * Copyright (C) 2021 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.flags + +import android.app.Activity +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.database.ContentObserver +import android.net.Uri +import android.os.Bundle +import android.os.Handler +import android.provider.Settings +import androidx.concurrent.futures.CallbackToFutureAdapter +import com.google.common.util.concurrent.ListenableFuture +import org.json.JSONException +import org.json.JSONObject + +class FlagManager constructor( + private val context: Context, + private val handler: Handler +) : FlagReader { + companion object { + const val RECEIVING_PACKAGE = "com.android.systemui" + const val ACTION_SET_FLAG = "com.android.systemui.action.SET_FLAG" + const val ACTION_GET_FLAGS = "com.android.systemui.action.GET_FLAGS" + const val FLAGS_PERMISSION = "com.android.systemui.permission.FLAGS" + const val FIELD_ID = "id" + const val FIELD_VALUE = "value" + const val FIELD_TYPE = "type" + const val FIELD_FLAGS = "flags" + const val TYPE_BOOLEAN = "boolean" + private const val SETTINGS_PREFIX = "systemui/flags" + } + + private val listeners: MutableSet = mutableSetOf() + private val settingsObserver: ContentObserver = SettingsObserver() + + fun getFlagsFuture(): ListenableFuture>> { + val intent = Intent(ACTION_GET_FLAGS) + intent.setPackage(RECEIVING_PACKAGE) + + return CallbackToFutureAdapter.getFuture { + completer: CallbackToFutureAdapter.Completer -> + context.sendOrderedBroadcast(intent, null, + object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val extras: Bundle? = getResultExtras(false) + val listOfFlags: java.util.ArrayList>? = + extras?.getParcelableArrayList(FIELD_FLAGS) + if (listOfFlags != null) { + completer.set(listOfFlags) + } else { + completer.setException(NoFlagResultsException()) + } + } + }, null, Activity.RESULT_OK, "extra data", null) + "QueryingFlags" + } as ListenableFuture>> + } + + fun setFlagValue(id: Int, enabled: Boolean) { + val intent = createIntent(id) + intent.putExtra(FIELD_VALUE, enabled) + + context.sendBroadcast(intent) + } + + fun eraseFlag(id: Int) { + val intent = createIntent(id) + + context.sendBroadcast(intent) + } + + override fun isEnabled(id: Int, def: Boolean): Boolean { + return isEnabled(id) ?: def + } + + /** Returns the stored value or null if not set. */ + fun isEnabled(id: Int): Boolean? { + val data: String? = Settings.Secure.getString( + context.contentResolver, keyToSettingsPrefix(id)) + if (data == null || data?.isEmpty()) { + return null + } + val json: JSONObject + try { + json = JSONObject(data) + return if (!assertType(json, TYPE_BOOLEAN)) { + null + } else json.getBoolean(FIELD_VALUE) + } catch (e: JSONException) { + throw InvalidFlagStorageException() + } + } + + override fun addListener(listener: FlagReader.Listener) { + synchronized(listeners) { + val registerNeeded = listeners.isEmpty() + listeners.add(listener) + if (registerNeeded) { + context.contentResolver.registerContentObserver( + Settings.Secure.getUriFor(SETTINGS_PREFIX), true, settingsObserver) + } + } + } + + override fun removeListener(listener: FlagReader.Listener) { + synchronized(listeners) { + val isRegistered = !listeners.isEmpty() + listeners.remove(listener) + if (isRegistered && listeners.isEmpty()) { + context.contentResolver.unregisterContentObserver(settingsObserver) + } + } + } + + private fun createIntent(id: Int): Intent { + val intent = Intent(ACTION_SET_FLAG) + intent.setPackage(RECEIVING_PACKAGE) + intent.putExtra(FIELD_ID, id) + + return intent + } + + fun keyToSettingsPrefix(key: Int): String { + return SETTINGS_PREFIX + "/" + key + } + + private fun assertType(json: JSONObject, type: String): Boolean { + return try { + json.getString(FIELD_TYPE) == TYPE_BOOLEAN + } catch (e: JSONException) { + false + } + } + + inner class SettingsObserver : ContentObserver(handler) { + override fun onChange(selfChange: Boolean, uri: Uri?) { + if (uri == null) { + return + } + val parts = uri.pathSegments + val idStr = parts[parts.size - 1] + try { + val id = idStr.toInt() + listeners.forEach { l -> l.onFlagChanged(id) } + } catch (e: NumberFormatException) { + // no-op + } + } + } +} + +class InvalidFlagStorageException : Exception("Data found but is invalid") + +class NoFlagResultsException : Exception( + "SystemUI failed to communicate its flags back successfully") \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/flags/FlagReader.kt b/SystemUIShared/src/com/android/systemui/flags/FlagReader.kt new file mode 100644 index 0000000000..91a391272b --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/flags/FlagReader.kt @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2021 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.flags + +/** + * Plugin for loading flag values + */ +interface FlagReader { + /** Returns a boolean value for the given flag. */ + fun isEnabled(flag: BooleanFlag): Boolean { + return flag.default + } + + /** Returns a boolean value for the given flag. */ + fun isEnabled(id: Int, def: Boolean): Boolean { + return def + } + + /** Add a listener to be alerted when any flag changes. */ + fun addListener(listener: Listener) {} + + /** Remove a listener to be alerted when any flag changes. */ + fun removeListener(listener: Listener) {} + + /** A simple listener to be alerted when a flag changes. */ + fun interface Listener { + /** */ + fun onFlagChanged(id: Int) + } +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/navigationbar/buttons/KeyButtonRipple.java b/SystemUIShared/src/com/android/systemui/navigationbar/buttons/KeyButtonRipple.java new file mode 100644 index 0000000000..8aa3abac83 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/navigationbar/buttons/KeyButtonRipple.java @@ -0,0 +1,531 @@ +/* + * Copyright (C) 2020 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.navigationbar.buttons; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ObjectAnimator; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.CanvasProperty; +import android.graphics.ColorFilter; +import android.graphics.Paint; +import android.graphics.PixelFormat; +import android.graphics.RecordingCanvas; +import android.graphics.drawable.Drawable; +import android.os.Handler; +import android.os.Trace; +import android.view.RenderNodeAnimator; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.animation.Interpolator; +import android.view.animation.PathInterpolator; + +import androidx.annotation.DimenRes; +import androidx.annotation.Keep; + +import java.util.ArrayList; +import java.util.HashSet; + +public class KeyButtonRipple extends Drawable { + + private static final float GLOW_MAX_SCALE_FACTOR = 1.35f; + private static final float GLOW_MAX_ALPHA = 0.2f; + private static final float GLOW_MAX_ALPHA_DARK = 0.1f; + private static final int ANIMATION_DURATION_SCALE = 350; + private static final int ANIMATION_DURATION_FADE = 450; + private static final Interpolator ALPHA_OUT_INTERPOLATOR = + new PathInterpolator(0f, 0f, 0.8f, 1f); + + @DimenRes + private final int mMaxWidthResource; + + private Paint mRipplePaint; + private CanvasProperty mLeftProp; + private CanvasProperty mTopProp; + private CanvasProperty mRightProp; + private CanvasProperty mBottomProp; + private CanvasProperty mRxProp; + private CanvasProperty mRyProp; + private CanvasProperty mPaintProp; + private float mGlowAlpha = 0f; + private float mGlowScale = 1f; + private boolean mPressed; + private boolean mVisible; + private boolean mDrawingHardwareGlow; + private int mMaxWidth; + private boolean mLastDark; + private boolean mDark; + private boolean mDelayTouchFeedback; + + private final Interpolator mInterpolator = new LogInterpolator(); + private boolean mSupportHardware; + private final View mTargetView; + private final Handler mHandler = new Handler(); + + private final HashSet mRunningAnimations = new HashSet<>(); + private final ArrayList mTmpArray = new ArrayList<>(); + + private final TraceAnimatorListener mExitHwTraceAnimator = + new TraceAnimatorListener("exitHardware"); + private final TraceAnimatorListener mEnterHwTraceAnimator = + new TraceAnimatorListener("enterHardware"); + + public enum Type { + OVAL, + ROUNDED_RECT + } + + private Type mType = Type.ROUNDED_RECT; + + public KeyButtonRipple(Context ctx, View targetView, @DimenRes int maxWidthResource) { + mMaxWidthResource = maxWidthResource; + mMaxWidth = ctx.getResources().getDimensionPixelSize(maxWidthResource); + mTargetView = targetView; + } + + public void updateResources() { + mMaxWidth = mTargetView.getContext().getResources() + .getDimensionPixelSize(mMaxWidthResource); + invalidateSelf(); + } + + public void setDarkIntensity(float darkIntensity) { + mDark = darkIntensity >= 0.5f; + } + + public void setDelayTouchFeedback(boolean delay) { + mDelayTouchFeedback = delay; + } + + public void setType(Type type) { + mType = type; + } + + private Paint getRipplePaint() { + if (mRipplePaint == null) { + mRipplePaint = new Paint(); + mRipplePaint.setAntiAlias(true); + mRipplePaint.setColor(mLastDark ? 0xff000000 : 0xffffffff); + } + return mRipplePaint; + } + + private void drawSoftware(Canvas canvas) { + if (mGlowAlpha > 0f) { + final Paint p = getRipplePaint(); + p.setAlpha((int)(mGlowAlpha * 255f)); + + final float w = getBounds().width(); + final float h = getBounds().height(); + final boolean horizontal = w > h; + final float diameter = getRippleSize() * mGlowScale; + final float radius = diameter * .5f; + final float cx = w * .5f; + final float cy = h * .5f; + final float rx = horizontal ? radius : cx; + final float ry = horizontal ? cy : radius; + final float corner = horizontal ? cy : cx; + + if (mType == Type.ROUNDED_RECT) { + canvas.drawRoundRect(cx - rx, cy - ry, cx + rx, cy + ry, corner, corner, p); + } else { + canvas.save(); + canvas.translate(cx, cy); + float r = Math.min(rx, ry); + canvas.drawOval(-r, -r, r, r, p); + canvas.restore(); + } + } + } + + @Override + public void draw(Canvas canvas) { + mSupportHardware = canvas.isHardwareAccelerated(); + if (mSupportHardware) { + drawHardware((RecordingCanvas) canvas); + } else { + drawSoftware(canvas); + } + } + + @Override + public void setAlpha(int alpha) { + // Not supported. + } + + @Override + public void setColorFilter(ColorFilter colorFilter) { + // Not supported. + } + + @Override + public int getOpacity() { + return PixelFormat.TRANSLUCENT; + } + + private boolean isHorizontal() { + return getBounds().width() > getBounds().height(); + } + + private void drawHardware(RecordingCanvas c) { + if (mDrawingHardwareGlow) { + if (mType == Type.ROUNDED_RECT) { + c.drawRoundRect(mLeftProp, mTopProp, mRightProp, mBottomProp, mRxProp, mRyProp, + mPaintProp); + } else { + CanvasProperty cx = CanvasProperty.createFloat(getBounds().width() / 2); + CanvasProperty cy = CanvasProperty.createFloat(getBounds().height() / 2); + int d = Math.min(getBounds().width(), getBounds().height()); + CanvasProperty r = CanvasProperty.createFloat(1.0f * d / 2); + c.drawCircle(cx, cy, r, mPaintProp); + } + } + } + + /** Gets the glow alpha, used by {@link android.animation.ObjectAnimator} via reflection. */ + @Keep + public float getGlowAlpha() { + return mGlowAlpha; + } + + /** Sets the glow alpha, used by {@link android.animation.ObjectAnimator} via reflection. */ + @Keep + public void setGlowAlpha(float x) { + mGlowAlpha = x; + invalidateSelf(); + } + + /** Gets the glow scale, used by {@link android.animation.ObjectAnimator} via reflection. */ + @Keep + public float getGlowScale() { + return mGlowScale; + } + + /** Sets the glow scale, used by {@link android.animation.ObjectAnimator} via reflection. */ + @Keep + public void setGlowScale(float x) { + mGlowScale = x; + invalidateSelf(); + } + + private float getMaxGlowAlpha() { + return mLastDark ? GLOW_MAX_ALPHA_DARK : GLOW_MAX_ALPHA; + } + + @Override + protected boolean onStateChange(int[] state) { + boolean pressed = false; + for (int i = 0; i < state.length; i++) { + if (state[i] == android.R.attr.state_pressed) { + pressed = true; + break; + } + } + if (pressed != mPressed) { + setPressed(pressed); + mPressed = pressed; + return true; + } else { + return false; + } + } + + @Override + public boolean setVisible(boolean visible, boolean restart) { + boolean changed = super.setVisible(visible, restart); + if (changed) { + // End any existing animations when the visibility changes + jumpToCurrentState(); + } + return changed; + } + + @Override + public void jumpToCurrentState() { + endAnimations("jumpToCurrentState", false /* cancel */); + } + + @Override + public boolean isStateful() { + return true; + } + + @Override + public boolean hasFocusStateSpecified() { + return true; + } + + public void setPressed(boolean pressed) { + if (mDark != mLastDark && pressed) { + mRipplePaint = null; + mLastDark = mDark; + } + if (mSupportHardware) { + setPressedHardware(pressed); + } else { + setPressedSoftware(pressed); + } + } + + /** + * Abort the ripple while it is delayed and before shown used only when setShouldDelayStartTouch + * is enabled. + */ + public void abortDelayedRipple() { + mHandler.removeCallbacksAndMessages(null); + } + + private void endAnimations(String reason, boolean cancel) { + Trace.beginSection("KeyButtonRipple.endAnim: reason=" + reason + " cancel=" + cancel); + Trace.endSection(); + mVisible = false; + mTmpArray.addAll(mRunningAnimations); + int size = mTmpArray.size(); + for (int i = 0; i < size; i++) { + Animator a = mTmpArray.get(i); + if (cancel) { + a.cancel(); + } else { + a.end(); + } + } + mTmpArray.clear(); + mRunningAnimations.clear(); + mHandler.removeCallbacksAndMessages(null); + } + + private void setPressedSoftware(boolean pressed) { + if (pressed) { + if (mDelayTouchFeedback) { + if (mRunningAnimations.isEmpty()) { + mHandler.removeCallbacksAndMessages(null); + mHandler.postDelayed(this::enterSoftware, ViewConfiguration.getTapTimeout()); + } else if (mVisible) { + enterSoftware(); + } + } else { + enterSoftware(); + } + } else { + exitSoftware(); + } + } + + private void enterSoftware() { + endAnimations("enterSoftware", true /* cancel */); + mVisible = true; + mGlowAlpha = getMaxGlowAlpha(); + ObjectAnimator scaleAnimator = ObjectAnimator.ofFloat(this, "glowScale", + 0f, GLOW_MAX_SCALE_FACTOR); + scaleAnimator.setInterpolator(mInterpolator); + scaleAnimator.setDuration(ANIMATION_DURATION_SCALE); + scaleAnimator.addListener(mAnimatorListener); + scaleAnimator.start(); + mRunningAnimations.add(scaleAnimator); + + // With the delay, it could eventually animate the enter animation with no pressed state, + // then immediately show the exit animation. If this is skipped there will be no ripple. + if (mDelayTouchFeedback && !mPressed) { + exitSoftware(); + } + } + + private void exitSoftware() { + ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(this, "glowAlpha", mGlowAlpha, 0f); + alphaAnimator.setInterpolator(ALPHA_OUT_INTERPOLATOR); + alphaAnimator.setDuration(ANIMATION_DURATION_FADE); + alphaAnimator.addListener(mAnimatorListener); + alphaAnimator.start(); + mRunningAnimations.add(alphaAnimator); + } + + private void setPressedHardware(boolean pressed) { + if (pressed) { + if (mDelayTouchFeedback) { + if (mRunningAnimations.isEmpty()) { + mHandler.removeCallbacksAndMessages(null); + mHandler.postDelayed(this::enterHardware, ViewConfiguration.getTapTimeout()); + } else if (mVisible) { + enterHardware(); + } + } else { + enterHardware(); + } + } else { + exitHardware(); + } + } + + /** + * Sets the left/top property for the round rect to {@code prop} depending on whether we are + * horizontal or vertical mode. + */ + private void setExtendStart(CanvasProperty prop) { + if (isHorizontal()) { + mLeftProp = prop; + } else { + mTopProp = prop; + } + } + + private CanvasProperty getExtendStart() { + return isHorizontal() ? mLeftProp : mTopProp; + } + + /** + * Sets the right/bottom property for the round rect to {@code prop} depending on whether we are + * horizontal or vertical mode. + */ + private void setExtendEnd(CanvasProperty prop) { + if (isHorizontal()) { + mRightProp = prop; + } else { + mBottomProp = prop; + } + } + + private CanvasProperty getExtendEnd() { + return isHorizontal() ? mRightProp : mBottomProp; + } + + private int getExtendSize() { + return isHorizontal() ? getBounds().width() : getBounds().height(); + } + + private int getRippleSize() { + int size = isHorizontal() ? getBounds().width() : getBounds().height(); + return Math.min(size, mMaxWidth); + } + + private void enterHardware() { + endAnimations("enterHardware", true /* cancel */); + mVisible = true; + mDrawingHardwareGlow = true; + setExtendStart(CanvasProperty.createFloat(getExtendSize() / 2)); + final RenderNodeAnimator startAnim = new RenderNodeAnimator(getExtendStart(), + getExtendSize()/2 - GLOW_MAX_SCALE_FACTOR * getRippleSize()/2); + startAnim.setDuration(ANIMATION_DURATION_SCALE); + startAnim.setInterpolator(mInterpolator); + startAnim.addListener(mAnimatorListener); + startAnim.setTarget(mTargetView); + + setExtendEnd(CanvasProperty.createFloat(getExtendSize() / 2)); + final RenderNodeAnimator endAnim = new RenderNodeAnimator(getExtendEnd(), + getExtendSize()/2 + GLOW_MAX_SCALE_FACTOR * getRippleSize()/2); + endAnim.setDuration(ANIMATION_DURATION_SCALE); + endAnim.setInterpolator(mInterpolator); + endAnim.addListener(mAnimatorListener); + endAnim.addListener(mEnterHwTraceAnimator); + endAnim.setTarget(mTargetView); + + if (isHorizontal()) { + mTopProp = CanvasProperty.createFloat(0f); + mBottomProp = CanvasProperty.createFloat(getBounds().height()); + mRxProp = CanvasProperty.createFloat(getBounds().height()/2); + mRyProp = CanvasProperty.createFloat(getBounds().height()/2); + } else { + mLeftProp = CanvasProperty.createFloat(0f); + mRightProp = CanvasProperty.createFloat(getBounds().width()); + mRxProp = CanvasProperty.createFloat(getBounds().width()/2); + mRyProp = CanvasProperty.createFloat(getBounds().width()/2); + } + + mGlowScale = GLOW_MAX_SCALE_FACTOR; + mGlowAlpha = getMaxGlowAlpha(); + mRipplePaint = getRipplePaint(); + mRipplePaint.setAlpha((int) (mGlowAlpha * 255)); + mPaintProp = CanvasProperty.createPaint(mRipplePaint); + + startAnim.start(); + endAnim.start(); + mRunningAnimations.add(startAnim); + mRunningAnimations.add(endAnim); + + invalidateSelf(); + + // With the delay, it could eventually animate the enter animation with no pressed state, + // then immediately show the exit animation. If this is skipped there will be no ripple. + if (mDelayTouchFeedback && !mPressed) { + exitHardware(); + } + } + + private void exitHardware() { + mPaintProp = CanvasProperty.createPaint(getRipplePaint()); + final RenderNodeAnimator opacityAnim = new RenderNodeAnimator(mPaintProp, + RenderNodeAnimator.PAINT_ALPHA, 0); + opacityAnim.setDuration(ANIMATION_DURATION_FADE); + opacityAnim.setInterpolator(ALPHA_OUT_INTERPOLATOR); + opacityAnim.addListener(mAnimatorListener); + opacityAnim.addListener(mExitHwTraceAnimator); + opacityAnim.setTarget(mTargetView); + + opacityAnim.start(); + mRunningAnimations.add(opacityAnim); + + invalidateSelf(); + } + + private final AnimatorListenerAdapter mAnimatorListener = + new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + mRunningAnimations.remove(animation); + if (mRunningAnimations.isEmpty() && !mPressed) { + mVisible = false; + mDrawingHardwareGlow = false; + invalidateSelf(); + } + } + }; + + private static final class TraceAnimatorListener extends AnimatorListenerAdapter { + private final String mName; + TraceAnimatorListener(String name) { + mName = name; + } + + @Override + public void onAnimationStart(Animator animation) { + Trace.beginSection("KeyButtonRipple.start." + mName); + Trace.endSection(); + } + + @Override + public void onAnimationCancel(Animator animation) { + Trace.beginSection("KeyButtonRipple.cancel." + mName); + Trace.endSection(); + } + + @Override + public void onAnimationEnd(Animator animation) { + Trace.beginSection("KeyButtonRipple.end." + mName); + Trace.endSection(); + } + } + + /** + * Interpolator with a smooth log deceleration + */ + private static final class LogInterpolator implements Interpolator { + @Override + public float getInterpolation(float input) { + return 1 - (float) Math.pow(400, -input * 1.4); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/animation/UnfoldMoveFromCenterAnimator.kt b/SystemUIShared/src/com/android/systemui/shared/animation/UnfoldMoveFromCenterAnimator.kt new file mode 100644 index 0000000000..9010d51541 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/animation/UnfoldMoveFromCenterAnimator.kt @@ -0,0 +1,175 @@ +/* + * Copyright (C) 2021 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.shared.animation + +import android.graphics.Point +import android.view.Surface +import android.view.View +import android.view.WindowManager +import com.android.systemui.unfold.UnfoldTransitionProgressProvider +import java.lang.ref.WeakReference + +/** + * Creates an animation where all registered views are moved into their final location + * by moving from the center of the screen to the sides + */ +class UnfoldMoveFromCenterAnimator @JvmOverloads constructor( + private val windowManager: WindowManager, + /** + * Allows to set custom translation applier + * Could be useful when a view could be translated from + * several sources and we want to set the translation + * using custom methods instead of [View.setTranslationX] or + * [View.setTranslationY] + */ + private val translationApplier: TranslationApplier = object : TranslationApplier {}, + /** + * Allows to set custom implementation for getting + * view location. Could be useful if logical view bounds + * are different than actual bounds (e.g. view container may + * have larger width than width of the items in the container) + */ + private val viewCenterProvider: ViewCenterProvider = object : ViewCenterProvider {} +) : UnfoldTransitionProgressProvider.TransitionProgressListener { + + private val screenSize = Point() + private var isVerticalFold = false + + private val animatedViews: MutableList = arrayListOf() + + private var lastAnimationProgress: Float = 0f + + /** + * Updates display properties in order to calculate the initial position for the views + * Must be called before [registerViewForAnimation] + */ + fun updateDisplayProperties() { + windowManager.defaultDisplay.getSize(screenSize) + + // Simple implementation to get current fold orientation, + // this might not be correct on all devices + // TODO: use JetPack WindowManager library to get the fold orientation + isVerticalFold = windowManager.defaultDisplay.rotation == Surface.ROTATION_0 || + windowManager.defaultDisplay.rotation == Surface.ROTATION_180 + } + + /** + * If target view positions have changed (e.g. because of layout changes) call this method + * to re-query view positions and update the translations + */ + fun updateViewPositions() { + animatedViews.forEach { animatedView -> + animatedView.view.get()?.let { + animatedView.updateAnimatedView(it) + } + } + onTransitionProgress(lastAnimationProgress) + } + + /** + * Registers a view to be animated, the view should be measured and layouted + * After finishing the animation it is necessary to clear + * the views using [clearRegisteredViews] + */ + fun registerViewForAnimation(view: View) { + val animatedView = createAnimatedView(view) + animatedViews.add(animatedView) + } + + /** + * Unregisters all registered views and resets their translation + */ + fun clearRegisteredViews() { + onTransitionProgress(1f) + animatedViews.clear() + } + + override fun onTransitionProgress(progress: Float) { + animatedViews.forEach { + it.view.get()?.let { view -> + translationApplier.apply( + view = view, + x = it.startTranslationX * (1 - progress), + y = it.startTranslationY * (1 - progress) + ) + } + } + lastAnimationProgress = progress + } + + private fun createAnimatedView(view: View): AnimatedView = + AnimatedView(view = WeakReference(view)).updateAnimatedView(view) + + private fun AnimatedView.updateAnimatedView(view: View): AnimatedView { + val viewCenter = Point() + viewCenterProvider.getViewCenter(view, viewCenter) + + val viewCenterX = viewCenter.x + val viewCenterY = viewCenter.y + + if (isVerticalFold) { + val distanceFromScreenCenterToViewCenter = screenSize.x / 2 - viewCenterX + startTranslationX = distanceFromScreenCenterToViewCenter * TRANSLATION_PERCENTAGE + startTranslationY = 0f + } else { + val distanceFromScreenCenterToViewCenter = screenSize.y / 2 - viewCenterY + startTranslationX = 0f + startTranslationY = distanceFromScreenCenterToViewCenter * TRANSLATION_PERCENTAGE + } + + return this + } + + /** + * Interface that allows to use custom logic to apply translation to view + */ + interface TranslationApplier { + /** + * Called when we need to apply [x] and [y] translation to [view] + */ + fun apply(view: View, x: Float, y: Float) { + view.translationX = x + view.translationY = y + } + } + + /** + * Interface that allows to use custom logic to get the center of the view + */ + interface ViewCenterProvider { + /** + * Called when we need to get the center of the view + */ + fun getViewCenter(view: View, outPoint: Point) { + val viewLocation = IntArray(2) + view.getLocationOnScreen(viewLocation) + + val viewX = viewLocation[0] + val viewY = viewLocation[1] + + outPoint.x = viewX + view.width / 2 + outPoint.y = viewY + view.height / 2 + } + } + + private class AnimatedView( + val view: WeakReference, + var startTranslationX: Float = 0f, + var startTranslationY: Float = 0f + ) +} + +private const val TRANSLATION_PERCENTAGE = 0.3f diff --git a/SystemUIShared/src/com/android/systemui/shared/navigationbar/RegionSamplingHelper.java b/SystemUIShared/src/com/android/systemui/shared/navigationbar/RegionSamplingHelper.java new file mode 100644 index 0000000000..98083742d7 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/navigationbar/RegionSamplingHelper.java @@ -0,0 +1,302 @@ +/* + * Copyright (C) 2020 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.shared.navigationbar; + +import static android.view.Display.DEFAULT_DISPLAY; + +import android.annotation.TargetApi; +import android.graphics.Rect; +import android.os.Build; +import android.os.Handler; +import android.view.CompositionSamplingListener; +import android.view.SurfaceControl; +import android.view.View; +import android.view.ViewRootImpl; +import android.view.ViewTreeObserver; + +import java.io.PrintWriter; +import java.util.concurrent.Executor; + +/** + * A helper class to sample regions on the screen and inspect its luminosity. + */ +@TargetApi(Build.VERSION_CODES.Q) +public class RegionSamplingHelper implements View.OnAttachStateChangeListener, + View.OnLayoutChangeListener { + + // Luminance threshold to determine black/white contrast for the navigation affordances. + // Passing the threshold of this luminance value will make the button black otherwise white + private static final float NAVIGATION_LUMINANCE_THRESHOLD = 0.5f; + // Luminance change threshold that allows applying new value if difference was exceeded + private static final float NAVIGATION_LUMINANCE_CHANGE_THRESHOLD = 0.05f; + + private final Handler mHandler = new Handler(); + private final View mSampledView; + + private final CompositionSamplingListener mSamplingListener; + + /** + * The requested sampling bounds that we want to sample from + */ + private final Rect mSamplingRequestBounds = new Rect(); + + /** + * The sampling bounds that are currently registered. + */ + private final Rect mRegisteredSamplingBounds = new Rect(); + private final SamplingCallback mCallback; + private final Executor mBackgroundExecutor; + private boolean mSamplingEnabled = false; + private boolean mSamplingListenerRegistered = false; + + private float mLastMedianLuma; + private float mCurrentMedianLuma; + private boolean mWaitingOnDraw; + private boolean mIsDestroyed; + + private boolean mFirstSamplingAfterStart; + private boolean mWindowVisible; + private boolean mWindowHasBlurs; + private SurfaceControl mRegisteredStopLayer = null; + // A copy of mRegisteredStopLayer where we own the life cycle and can access from a bg thread. + private SurfaceControl mWrappedStopLayer = null; + private ViewTreeObserver.OnDrawListener mUpdateOnDraw = new ViewTreeObserver.OnDrawListener() { + @Override + public void onDraw() { + // We need to post the remove runnable, since it's not allowed to remove in onDraw + mHandler.post(mRemoveDrawRunnable); + RegionSamplingHelper.this.onDraw(); + } + }; + private Runnable mRemoveDrawRunnable = new Runnable() { + @Override + public void run() { + mSampledView.getViewTreeObserver().removeOnDrawListener(mUpdateOnDraw); + } + }; + + public RegionSamplingHelper(View sampledView, SamplingCallback samplingCallback, + Executor backgroundExecutor) { + mBackgroundExecutor = backgroundExecutor; + mSamplingListener = new CompositionSamplingListener( + sampledView.getContext().getMainExecutor()) { + @Override + public void onSampleCollected(float medianLuma) { + if (mSamplingEnabled) { + updateMediaLuma(medianLuma); + } + } + }; + mSampledView = sampledView; + mSampledView.addOnAttachStateChangeListener(this); + mSampledView.addOnLayoutChangeListener(this); + + mCallback = samplingCallback; + } + + private void onDraw() { + if (mWaitingOnDraw) { + mWaitingOnDraw = false; + updateSamplingListener(); + } + } + + public void start(Rect initialSamplingBounds) { + if (!mCallback.isSamplingEnabled()) { + return; + } + if (initialSamplingBounds != null) { + mSamplingRequestBounds.set(initialSamplingBounds); + } + mSamplingEnabled = true; + // make sure we notify once + mLastMedianLuma = -1; + mFirstSamplingAfterStart = true; + updateSamplingListener(); + } + + public void stop() { + mSamplingEnabled = false; + updateSamplingListener(); + } + + public void stopAndDestroy() { + stop(); + mSamplingListener.destroy(); + mIsDestroyed = true; + } + + @Override + public void onViewAttachedToWindow(View view) { + updateSamplingListener(); + } + + @Override + public void onViewDetachedFromWindow(View view) { + stopAndDestroy(); + } + + @Override + public void onLayoutChange(View v, int left, int top, int right, int bottom, + int oldLeft, int oldTop, int oldRight, int oldBottom) { + updateSamplingRect(); + } + + private void updateSamplingListener() { + boolean isSamplingEnabled = mSamplingEnabled + && !mSamplingRequestBounds.isEmpty() + && mWindowVisible + && !mWindowHasBlurs + && (mSampledView.isAttachedToWindow() || mFirstSamplingAfterStart); + if (isSamplingEnabled) { + ViewRootImpl viewRootImpl = mSampledView.getViewRootImpl(); + SurfaceControl stopLayerControl = null; + if (viewRootImpl != null) { + stopLayerControl = viewRootImpl.getSurfaceControl(); + } + if (stopLayerControl == null || !stopLayerControl.isValid()) { + if (!mWaitingOnDraw) { + mWaitingOnDraw = true; + // The view might be attached but we haven't drawn yet, so wait until the + // next draw to update the listener again with the stop layer, such that our + // own drawing doesn't affect the sampling. + if (mHandler.hasCallbacks(mRemoveDrawRunnable)) { + mHandler.removeCallbacks(mRemoveDrawRunnable); + } else { + mSampledView.getViewTreeObserver().addOnDrawListener(mUpdateOnDraw); + } + } + // If there's no valid surface, let's just sample without a stop layer, so we + // don't have to delay + stopLayerControl = null; + } + if (!mSamplingRequestBounds.equals(mRegisteredSamplingBounds) + || mRegisteredStopLayer != stopLayerControl) { + // We only want to re-register if something actually changed + unregisterSamplingListener(); + mSamplingListenerRegistered = true; + SurfaceControl wrappedStopLayer = stopLayerControl == null + ? null : new SurfaceControl(stopLayerControl, "regionSampling"); + mBackgroundExecutor.execute(() -> { + if (wrappedStopLayer != null && !wrappedStopLayer.isValid()) { + return; + } + CompositionSamplingListener.register(mSamplingListener, DEFAULT_DISPLAY, + wrappedStopLayer, mSamplingRequestBounds); + }); + mRegisteredSamplingBounds.set(mSamplingRequestBounds); + mRegisteredStopLayer = stopLayerControl; + mWrappedStopLayer = wrappedStopLayer; + } + mFirstSamplingAfterStart = false; + } else { + unregisterSamplingListener(); + } + } + + private void unregisterSamplingListener() { + if (mSamplingListenerRegistered) { + mSamplingListenerRegistered = false; + SurfaceControl wrappedStopLayer = mWrappedStopLayer; + mRegisteredStopLayer = null; + mRegisteredSamplingBounds.setEmpty(); + mBackgroundExecutor.execute(() -> { + CompositionSamplingListener.unregister(mSamplingListener); + if (wrappedStopLayer != null && wrappedStopLayer.isValid()) { + wrappedStopLayer.release(); + } + }); + } + } + + private void updateMediaLuma(float medianLuma) { + mCurrentMedianLuma = medianLuma; + + // If the difference between the new luma and the current luma is larger than threshold + // then apply the current luma, this is to prevent small changes causing colors to flicker + if (Math.abs(mCurrentMedianLuma - mLastMedianLuma) + > NAVIGATION_LUMINANCE_CHANGE_THRESHOLD) { + mCallback.onRegionDarknessChanged( + medianLuma < NAVIGATION_LUMINANCE_THRESHOLD /* isRegionDark */); + mLastMedianLuma = medianLuma; + } + } + + public void updateSamplingRect() { + Rect sampledRegion = mCallback.getSampledRegion(mSampledView); + if (!mSamplingRequestBounds.equals(sampledRegion)) { + mSamplingRequestBounds.set(sampledRegion); + updateSamplingListener(); + } + } + + public void setWindowVisible(boolean visible) { + mWindowVisible = visible; + updateSamplingListener(); + } + + /** + * If we're blurring the shade window. + */ + public void setWindowHasBlurs(boolean hasBlurs) { + mWindowHasBlurs = hasBlurs; + updateSamplingListener(); + } + + public void dump(PrintWriter pw) { + pw.println("RegionSamplingHelper:"); + pw.println(" sampleView isAttached: " + mSampledView.isAttachedToWindow()); + pw.println(" sampleView isScValid: " + (mSampledView.isAttachedToWindow() + ? mSampledView.getViewRootImpl().getSurfaceControl().isValid() + : "notAttached")); + pw.println(" mSamplingEnabled: " + mSamplingEnabled); + pw.println(" mSamplingListenerRegistered: " + mSamplingListenerRegistered); + pw.println(" mSamplingRequestBounds: " + mSamplingRequestBounds); + pw.println(" mRegisteredSamplingBounds: " + mRegisteredSamplingBounds); + pw.println(" mLastMedianLuma: " + mLastMedianLuma); + pw.println(" mCurrentMedianLuma: " + mCurrentMedianLuma); + pw.println(" mWindowVisible: " + mWindowVisible); + pw.println(" mWindowHasBlurs: " + mWindowHasBlurs); + pw.println(" mWaitingOnDraw: " + mWaitingOnDraw); + pw.println(" mRegisteredStopLayer: " + mRegisteredStopLayer); + pw.println(" mWrappedStopLayer: " + mWrappedStopLayer); + pw.println(" mIsDestroyed: " + mIsDestroyed); + } + + public interface SamplingCallback { + /** + * Called when the darkness of the sampled region changes + * @param isRegionDark true if the sampled luminance is below the luminance threshold + */ + void onRegionDarknessChanged(boolean isRegionDark); + + /** + * Get the sampled region of interest from the sampled view + * @param sampledView The view that this helper is attached to for convenience + * @return the region to be sampled in sceen coordinates. Return {@code null} to avoid + * sampling in this frame + */ + Rect getSampledRegion(View sampledView); + + /** + * @return if sampling should be enabled in the current configuration + */ + default boolean isSamplingEnabled() { + return true; + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/pip/PipSurfaceTransactionHelper.java b/SystemUIShared/src/com/android/systemui/shared/pip/PipSurfaceTransactionHelper.java index 7d0fb5d388..567e7aa3d7 100644 --- a/SystemUIShared/src/com/android/systemui/shared/pip/PipSurfaceTransactionHelper.java +++ b/SystemUIShared/src/com/android/systemui/shared/pip/PipSurfaceTransactionHelper.java @@ -53,8 +53,8 @@ public class PipSurfaceTransactionHelper { tx.setMatrix(leash, mTmpTransform, mTmpFloat9) .setPosition(leash, positionX, positionY) .setCornerRadius(leash, cornerRadius); - return new PictureInPictureSurfaceTransaction( - positionX, positionY, mTmpFloat9, 0 /* rotation */, cornerRadius, sourceBounds); + return newPipSurfaceTransaction(positionX, positionY, + mTmpFloat9, 0 /* rotation */, cornerRadius, sourceBounds); } public PictureInPictureSurfaceTransaction scale( @@ -70,8 +70,8 @@ public class PipSurfaceTransactionHelper { tx.setMatrix(leash, mTmpTransform, mTmpFloat9) .setPosition(leash, positionX, positionY) .setCornerRadius(leash, cornerRadius); - return new PictureInPictureSurfaceTransaction( - positionX, positionY, mTmpFloat9, degree, cornerRadius, sourceBounds); + return newPipSurfaceTransaction(positionX, positionY, + mTmpFloat9, degree, cornerRadius, sourceBounds); } public PictureInPictureSurfaceTransaction scaleAndCrop( @@ -93,8 +93,8 @@ public class PipSurfaceTransactionHelper { .setWindowCrop(leash, mTmpDestinationRect) .setPosition(leash, left, top) .setCornerRadius(leash, cornerRadius); - return new PictureInPictureSurfaceTransaction( - left, top, mTmpFloat9, 0 /* rotation */, cornerRadius, mTmpDestinationRect); + return newPipSurfaceTransaction(left, top, + mTmpFloat9, 0 /* rotation */, cornerRadius, mTmpDestinationRect); } public PictureInPictureSurfaceTransaction scaleAndRotate( @@ -125,8 +125,7 @@ public class PipSurfaceTransactionHelper { .setWindowCrop(leash, mTmpDestinationRect) .setPosition(leash, adjustedPositionX, adjustedPositionY) .setCornerRadius(leash, cornerRadius); - return new PictureInPictureSurfaceTransaction( - adjustedPositionX, adjustedPositionY, + return newPipSurfaceTransaction(adjustedPositionX, adjustedPositionY, mTmpFloat9, degree, cornerRadius, mTmpDestinationRect); } @@ -137,6 +136,17 @@ public class PipSurfaceTransactionHelper { return mCornerRadius * scale; } + private static PictureInPictureSurfaceTransaction newPipSurfaceTransaction( + float posX, float posY, float[] float9, float rotation, float cornerRadius, + Rect windowCrop) { + return new PictureInPictureSurfaceTransaction.Builder() + .setPosition(posX, posY) + .setTransform(float9, rotation) + .setCornerRadius(cornerRadius) + .setWindowCrop(windowCrop) + .build(); + } + /** @return {@link SurfaceControl.Transaction} instance with vsync-id */ public static SurfaceControl.Transaction newSurfaceControlTransaction() { final SurfaceControl.Transaction tx = new SurfaceControl.Transaction(); diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginActionManager.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginActionManager.java new file mode 100644 index 0000000000..9ea4b578ad --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginActionManager.java @@ -0,0 +1,432 @@ +/* + * Copyright (C) 2016 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.shared.plugins; + +import android.app.Notification; +import android.app.Notification.Action; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.ComponentName; +import android.content.Context; +import android.content.ContextWrapper; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.pm.ResolveInfo; +import android.content.res.Resources; +import android.net.Uri; +import android.util.ArraySet; +import android.util.Log; +import android.view.LayoutInflater; + +import com.android.internal.annotations.VisibleForTesting; +import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; +import com.android.systemui.plugins.Plugin; +import com.android.systemui.plugins.PluginListener; +import com.android.systemui.shared.plugins.VersionInfo.InvalidVersionException; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executor; + +/** + * Coordinates all the available plugins for a given action. + * + * The available plugins are queried from the {@link PackageManager} via an an {@link Intent} + * action. + * + * @param The type of plugin that this contains. + */ +public class PluginActionManager { + + private static final boolean DEBUG = false; + + private static final String TAG = "PluginInstanceManager"; + public static final String PLUGIN_PERMISSION = "com.android.systemui.permission.PLUGIN"; + + private final Context mContext; + private final PluginListener mListener; + private final String mAction; + private final boolean mAllowMultiple; + private final NotificationManager mNotificationManager; + private final PluginEnabler mPluginEnabler; + private final PluginInstance.Factory mPluginInstanceFactory; + private final ArraySet mPrivilegedPlugins = new ArraySet<>(); + + @VisibleForTesting + private final ArrayList> mPluginInstances = new ArrayList<>(); + private final boolean mIsDebuggable; + private final PackageManager mPm; + private final Class mPluginClass; + private final Executor mMainExecutor; + private final Executor mBgExecutor; + + private PluginActionManager( + Context context, + PackageManager pm, + String action, + PluginListener listener, + Class pluginClass, + boolean allowMultiple, + Executor mainExecutor, + Executor bgExecutor, + boolean debuggable, + NotificationManager notificationManager, + PluginEnabler pluginEnabler, + List privilegedPlugins, + PluginInstance.Factory pluginInstanceFactory) { + mPluginClass = pluginClass; + mMainExecutor = mainExecutor; + mBgExecutor = bgExecutor; + mContext = context; + mPm = pm; + mAction = action; + mListener = listener; + mAllowMultiple = allowMultiple; + mNotificationManager = notificationManager; + mPluginEnabler = pluginEnabler; + mPluginInstanceFactory = pluginInstanceFactory; + mPrivilegedPlugins.addAll(privilegedPlugins); + mIsDebuggable = debuggable; + } + + /** Load all plugins matching this instance's action. */ + public void loadAll() { + if (DEBUG) Log.d(TAG, "startListening"); + mBgExecutor.execute(this::queryAll); + } + + /** Unload all plugins managed by this instance. */ + public void destroy() { + if (DEBUG) Log.d(TAG, "stopListening"); + ArrayList> plugins = new ArrayList<>(mPluginInstances); + for (PluginInstance plugInstance : plugins) { + mMainExecutor.execute(() -> onPluginDisconnected(plugInstance)); + } + } + + /** Unload all matching plugins managed by this instance. */ + public void onPackageRemoved(String pkg) { + mBgExecutor.execute(() -> removePkg(pkg)); + } + + /** Unload and then reload all matching plugins managed by this instance. */ + public void reloadPackage(String pkg) { + mBgExecutor.execute(() -> { + removePkg(pkg); + queryPkg(pkg); + }); + } + + /** Disable a specific plugin managed by this instance. */ + public boolean checkAndDisable(String className) { + boolean disableAny = false; + ArrayList> plugins = new ArrayList<>(mPluginInstances); + for (PluginInstance info : plugins) { + if (className.startsWith(info.getPackage())) { + disableAny |= disable(info, PluginEnabler.DISABLED_FROM_EXPLICIT_CRASH); + } + } + return disableAny; + } + + /** Disable all plugins managed by this instance. */ + public boolean disableAll() { + ArrayList> plugins = new ArrayList<>(mPluginInstances); + boolean disabledAny = false; + for (int i = 0; i < plugins.size(); i++) { + disabledAny |= disable(plugins.get(i), PluginEnabler.DISABLED_FROM_SYSTEM_CRASH); + } + return disabledAny; + } + + boolean isPluginPrivileged(ComponentName pluginName) { + for (String componentNameOrPackage : mPrivilegedPlugins) { + ComponentName componentName = ComponentName.unflattenFromString(componentNameOrPackage); + if (componentName == null) { + if (componentNameOrPackage.equals(pluginName.getPackageName())) { + return true; + } + } else { + if (componentName.equals(pluginName)) { + return true; + } + } + } + return false; + } + + private boolean disable( + PluginInstance pluginInstance, @PluginEnabler.DisableReason int reason) { + // Live by the sword, die by the sword. + // Misbehaving plugins get disabled and won't come back until uninstall/reinstall. + + ComponentName pluginComponent = pluginInstance.getComponentName(); + // If a plugin is detected in the stack of a crash then this will be called for that + // plugin, if the plugin causing a crash cannot be identified, they are all disabled + // assuming one of them must be bad. + if (isPluginPrivileged(pluginComponent)) { + // Don't disable privileged plugins as they are a part of the OS. + return false; + } + Log.w(TAG, "Disabling plugin " + pluginComponent.flattenToShortString()); + mPluginEnabler.setDisabled(pluginComponent, reason); + + return true; + } + + boolean dependsOn(Plugin p, Class cls) { + ArrayList> instances = new ArrayList<>(mPluginInstances); + for (PluginInstance instance : instances) { + if (instance.containsPluginClass(p.getClass())) { + return instance.getVersionInfo() != null && instance.getVersionInfo().hasClass(cls); + } + } + return false; + } + + @Override + public String toString() { + return String.format("%s@%s (action=%s)", + getClass().getSimpleName(), hashCode(), mAction); + } + + private void onPluginConnected(PluginInstance pluginInstance) { + if (DEBUG) Log.d(TAG, "onPluginConnected"); + PluginPrefs.setHasPlugins(mContext); + pluginInstance.onCreate(mContext, mListener); + } + + private void onPluginDisconnected(PluginInstance pluginInstance) { + if (DEBUG) Log.d(TAG, "onPluginDisconnected"); + pluginInstance.onDestroy(mListener); + } + + private void queryAll() { + if (DEBUG) Log.d(TAG, "queryAll " + mAction); + for (int i = mPluginInstances.size() - 1; i >= 0; i--) { + PluginInstance pluginInstance = mPluginInstances.get(i); + mMainExecutor.execute(() -> onPluginDisconnected(pluginInstance)); + } + mPluginInstances.clear(); + handleQueryPlugins(null); + } + + private void removePkg(String pkg) { + for (int i = mPluginInstances.size() - 1; i >= 0; i--) { + final PluginInstance pluginInstance = mPluginInstances.get(i); + if (pluginInstance.getPackage().equals(pkg)) { + mMainExecutor.execute(() -> onPluginDisconnected(pluginInstance)); + mPluginInstances.remove(i); + } + } + } + + private void queryPkg(String pkg) { + if (DEBUG) Log.d(TAG, "queryPkg " + pkg + " " + mAction); + if (mAllowMultiple || (mPluginInstances.size() == 0)) { + handleQueryPlugins(pkg); + } else { + if (DEBUG) Log.d(TAG, "Too many of " + mAction); + } + } + + private void handleQueryPlugins(String pkgName) { + // This isn't actually a service and shouldn't ever be started, but is + // a convenient PM based way to manage our plugins. + Intent intent = new Intent(mAction); + if (pkgName != null) { + intent.setPackage(pkgName); + } + List result = mPm.queryIntentServices(intent, 0); + if (DEBUG) Log.d(TAG, "Found " + result.size() + " plugins"); + if (result.size() > 1 && !mAllowMultiple) { + // TODO: Show warning. + Log.w(TAG, "Multiple plugins found for " + mAction); + if (DEBUG) { + for (ResolveInfo info : result) { + ComponentName name = new ComponentName(info.serviceInfo.packageName, + info.serviceInfo.name); + Log.w(TAG, " " + name); + } + } + return; + } + for (ResolveInfo info : result) { + ComponentName name = new ComponentName(info.serviceInfo.packageName, + info.serviceInfo.name); + PluginInstance pluginInstance = loadPluginComponent(name); + if (pluginInstance != null) { + // add plugin before sending PLUGIN_CONNECTED message + mPluginInstances.add(pluginInstance); + mMainExecutor.execute(() -> onPluginConnected(pluginInstance)); + } + } + } + + private PluginInstance loadPluginComponent(ComponentName component) { + // This was already checked, but do it again here to make extra extra sure, we don't + // use these on production builds. + if (!mIsDebuggable && !isPluginPrivileged(component)) { + // Never ever ever allow these on production builds, they are only for prototyping. + Log.w(TAG, "Plugin cannot be loaded on production build: " + component); + return null; + } + if (!mPluginEnabler.isEnabled(component)) { + if (DEBUG) { + Log.d(TAG, "Plugin is not enabled, aborting load: " + component); + } + return null; + } + String packageName = component.getPackageName(); + try { + // TODO: This probably isn't needed given that we don't have IGNORE_SECURITY on + if (mPm.checkPermission(PLUGIN_PERMISSION, packageName) + != PackageManager.PERMISSION_GRANTED) { + Log.d(TAG, "Plugin doesn't have permission: " + packageName); + return null; + } + + ApplicationInfo appInfo = mPm.getApplicationInfo(packageName, 0); + // TODO: Only create the plugin before version check if we need it for + // legacy version check. + if (DEBUG) { + Log.d(TAG, "createPlugin"); + } + try { + return mPluginInstanceFactory.create( + mContext, appInfo, component, + mPluginClass); + } catch (InvalidVersionException e) { + reportInvalidVersion(component, component.getClassName(), e); + } + } catch (Throwable e) { + Log.w(TAG, "Couldn't load plugin: " + packageName, e); + return null; + } + + return null; + } + + private void reportInvalidVersion( + ComponentName component, String className, InvalidVersionException e) { + final int icon = Resources.getSystem().getIdentifier( + "stat_sys_warning", "drawable", "android"); + final int color = Resources.getSystem().getIdentifier( + "system_notification_accent_color", "color", "android"); + final Notification.Builder nb = new Notification.Builder(mContext, + PluginManager.NOTIFICATION_CHANNEL_ID) + .setStyle(new Notification.BigTextStyle()) + .setSmallIcon(icon) + .setWhen(0) + .setShowWhen(false) + .setVisibility(Notification.VISIBILITY_PUBLIC) + .setColor(mContext.getColor(color)); + String label = className; + try { + label = mPm.getServiceInfo(component, 0).loadLabel(mPm).toString(); + } catch (NameNotFoundException e2) { + // no-op + } + if (!e.isTooNew()) { + // Localization not required as this will never ever appear in a user build. + nb.setContentTitle("Plugin \"" + label + "\" is too old") + .setContentText("Contact plugin developer to get an updated" + + " version.\n" + e.getMessage()); + } else { + // Localization not required as this will never ever appear in a user build. + nb.setContentTitle("Plugin \"" + label + "\" is too new") + .setContentText("Check to see if an OTA is available.\n" + + e.getMessage()); + } + Intent i = new Intent(PluginManagerImpl.DISABLE_PLUGIN).setData( + Uri.parse("package://" + component.flattenToString())); + PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, + PendingIntent.FLAG_IMMUTABLE); + nb.addAction(new Action.Builder(null, "Disable plugin", pi).build()); + mNotificationManager.notify(SystemMessage.NOTE_PLUGIN, nb.build()); + // TODO: Warn user. + Log.w(TAG, "Plugin has invalid interface version " + e.getActualVersion() + + ", expected " + e.getExpectedVersion()); + } + + /** + * Construct a {@link PluginActionManager} + */ + public static class Factory { + private final Context mContext; + private final PackageManager mPackageManager; + private final Executor mMainExecutor; + private final Executor mBgExecutor; + private final NotificationManager mNotificationManager; + private final PluginEnabler mPluginEnabler; + private final List mPrivilegedPlugins; + private final PluginInstance.Factory mPluginInstanceFactory; + + public Factory(Context context, PackageManager packageManager, + Executor mainExecutor, Executor bgExecutor, + NotificationManager notificationManager, PluginEnabler pluginEnabler, + List privilegedPlugins, PluginInstance.Factory pluginInstanceFactory) { + mContext = context; + mPackageManager = packageManager; + mMainExecutor = mainExecutor; + mBgExecutor = bgExecutor; + mNotificationManager = notificationManager; + mPluginEnabler = pluginEnabler; + mPrivilegedPlugins = privilegedPlugins; + mPluginInstanceFactory = pluginInstanceFactory; + } + + PluginActionManager create( + String action, PluginListener listener, Class pluginClass, + boolean allowMultiple, boolean debuggable) { + return new PluginActionManager<>(mContext, mPackageManager, action, listener, + pluginClass, allowMultiple, mMainExecutor, mBgExecutor, + debuggable, mNotificationManager, mPluginEnabler, + mPrivilegedPlugins, mPluginInstanceFactory); + } + } + + /** */ + public static class PluginContextWrapper extends ContextWrapper { + private final ClassLoader mClassLoader; + private LayoutInflater mInflater; + + public PluginContextWrapper(Context base, ClassLoader classLoader) { + super(base); + mClassLoader = classLoader; + } + + @Override + public ClassLoader getClassLoader() { + return mClassLoader; + } + + @Override + public Object getSystemService(String name) { + if (LAYOUT_INFLATER_SERVICE.equals(name)) { + if (mInflater == null) { + mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); + } + return mInflater; + } + return getBaseContext().getSystemService(name); + } + } + +} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java deleted file mode 100644 index 42bc1d0ea0..0000000000 --- a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInitializer.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2018 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.shared.plugins; - -import android.content.Context; -import android.os.Looper; - -/** - * Provides necessary components for initializing {@link PluginManagerImpl}. - */ -public interface PluginInitializer { - - Looper getBgLooper(); - - /** - * Called from the bg looper during initialization of {@link PluginManagerImpl}. - */ - void onPluginManagerInit(); - - String[] getWhitelistedPlugins(Context context); - - PluginEnabler getPluginEnabler(Context context); - - /** - * Called from {@link PluginManagerImpl#handleWtfs()}. - */ - void handleWtfs(); - - /** - * Returns if pluging manager should run in debug mode. - */ - boolean isDebuggable(); -} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstance.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstance.java new file mode 100644 index 0000000000..2f84602089 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstance.java @@ -0,0 +1,228 @@ +/* + * Copyright (C) 2021 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.shared.plugins; + +import android.app.LoadedApk; +import android.content.ComponentName; +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.text.TextUtils; +import android.util.ArrayMap; +import android.util.Log; + +import com.android.internal.annotations.VisibleForTesting; +import com.android.systemui.plugins.Plugin; +import com.android.systemui.plugins.PluginFragment; +import com.android.systemui.plugins.PluginListener; + +import dalvik.system.PathClassLoader; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Contains a single instantiation of a Plugin. + * + * This class and its related Factory are in charge of actually instantiating a plugin and + * managing any state related to it. + * + * @param The type of plugin that this contains. + */ +public class PluginInstance { + private static final String TAG = "PluginInstance"; + private static final Map sClassLoaders = new ArrayMap<>(); + + private final Context mPluginContext; + private final VersionInfo mVersionInfo; + private final ComponentName mComponentName; + private final T mPlugin; + + /** */ + public PluginInstance(ComponentName componentName, T plugin, Context pluginContext, + VersionInfo versionInfo) { + mComponentName = componentName; + mPlugin = plugin; + mPluginContext = pluginContext; + mVersionInfo = versionInfo; + } + + /** Alerts listener and plugin that the plugin has been created. */ + public void onCreate(Context appContext, PluginListener listener) { + if (!(mPlugin instanceof PluginFragment)) { + // Only call onCreate for plugins that aren't fragments, as fragments + // will get the onCreate as part of the fragment lifecycle. + mPlugin.onCreate(appContext, mPluginContext); + } + listener.onPluginConnected(mPlugin, mPluginContext); + } + + /** Alerts listener and plugin that the plugin is being shutdown. */ + public void onDestroy(PluginListener listener) { + listener.onPluginDisconnected(mPlugin); + if (!(mPlugin instanceof PluginFragment)) { + // Only call onDestroy for plugins that aren't fragments, as fragments + // will get the onDestroy as part of the fragment lifecycle. + mPlugin.onDestroy(); + } + } + + /** + * Returns if the contained plugin matches the passed in class name. + * + * It does this by string comparison of the class names. + **/ + public boolean containsPluginClass(Class pluginClass) { + return mPlugin.getClass().getName().equals(pluginClass.getName()); + } + + public ComponentName getComponentName() { + return mComponentName; + } + + public String getPackage() { + return mComponentName.getPackageName(); + } + + public VersionInfo getVersionInfo() { + return mVersionInfo; + } + + @VisibleForTesting + Context getPluginContext() { + return mPluginContext; + } + + /** Used to create new {@link PluginInstance}s. */ + public static class Factory { + private final ClassLoader mBaseClassLoader; + private final InstanceFactory mInstanceFactory; + private final VersionChecker mVersionChecker; + private final boolean mIsDebug; + private final List mPrivilegedPlugins; + + /** Factory used to construct {@link PluginInstance}s. */ + public Factory(ClassLoader classLoader, InstanceFactory instanceFactory, + VersionChecker versionChecker, + List privilegedPlugins, + boolean isDebug) { + mPrivilegedPlugins = privilegedPlugins; + mBaseClassLoader = classLoader; + mInstanceFactory = instanceFactory; + mVersionChecker = versionChecker; + mIsDebug = isDebug; + } + + /** Construct a new PluginInstance. */ + public PluginInstance create( + Context context, + ApplicationInfo appInfo, + ComponentName componentName, + Class pluginClass) + throws PackageManager.NameNotFoundException, ClassNotFoundException, + InstantiationException, IllegalAccessException { + + ClassLoader classLoader = getClassLoader(appInfo, mBaseClassLoader); + Context pluginContext = new PluginActionManager.PluginContextWrapper( + context.createApplicationContext(appInfo, 0), classLoader); + Class instanceClass = (Class) Class.forName( + componentName.getClassName(), true, classLoader); + // TODO: Only create the plugin before version check if we need it for + // legacy version check. + T instance = (T) mInstanceFactory.create(instanceClass); + VersionInfo version = mVersionChecker.checkVersion( + instanceClass, pluginClass, instance); + return new PluginInstance(componentName, instance, pluginContext, version); + } + + private boolean isPluginPackagePrivileged(String packageName) { + for (String componentNameOrPackage : mPrivilegedPlugins) { + ComponentName componentName = ComponentName.unflattenFromString( + componentNameOrPackage); + if (componentName != null) { + if (componentName.getPackageName().equals(packageName)) { + return true; + } + } else if (componentNameOrPackage.equals(packageName)) { + return true; + } + } + return false; + } + + private ClassLoader getParentClassLoader(ClassLoader baseClassLoader) { + return new PluginManagerImpl.ClassLoaderFilter( + baseClassLoader, "com.android.systemui.plugin"); + } + + /** Returns class loader specific for the given plugin. */ + private ClassLoader getClassLoader(ApplicationInfo appInfo, + ClassLoader baseClassLoader) { + if (!mIsDebug && !isPluginPackagePrivileged(appInfo.packageName)) { + Log.w(TAG, "Cannot get class loader for non-privileged plugin. Src:" + + appInfo.sourceDir + ", pkg: " + appInfo.packageName); + return null; + } + if (sClassLoaders.containsKey(appInfo.packageName)) { + return sClassLoaders.get(appInfo.packageName); + } + + List zipPaths = new ArrayList<>(); + List libPaths = new ArrayList<>(); + LoadedApk.makePaths(null, true, appInfo, zipPaths, libPaths); + ClassLoader classLoader = new PathClassLoader( + TextUtils.join(File.pathSeparator, zipPaths), + TextUtils.join(File.pathSeparator, libPaths), + getParentClassLoader(baseClassLoader)); + sClassLoaders.put(appInfo.packageName, classLoader); + return classLoader; + } + } + + /** Class that compares a plugin class against an implementation for version matching. */ + public static class VersionChecker { + /** Compares two plugin classes. */ + public VersionInfo checkVersion( + Class instanceClass, Class pluginClass, Plugin plugin) { + VersionInfo pluginVersion = new VersionInfo().addClass(pluginClass); + VersionInfo instanceVersion = new VersionInfo().addClass(instanceClass); + if (instanceVersion.hasVersionInfo()) { + pluginVersion.checkVersion(instanceVersion); + } else { + int fallbackVersion = plugin.getVersion(); + if (fallbackVersion != pluginVersion.getDefaultVersion()) { + throw new VersionInfo.InvalidVersionException("Invalid legacy version", false); + } + return null; + } + return instanceVersion; + } + } + + /** + * Simple class to create a new instance. Useful for testing. + * + * @param The type of plugin this create. + **/ + public static class InstanceFactory { + T create(Class cls) throws IllegalAccessException, InstantiationException { + return (T) cls.newInstance(); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java deleted file mode 100644 index 2b35bcd9a3..0000000000 --- a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Copyright (C) 2016 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.shared.plugins; - -import android.app.Notification; -import android.app.Notification.Action; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.ContextWrapper; -import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.content.pm.ResolveInfo; -import android.content.res.Resources; -import android.net.Uri; -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.util.ArraySet; -import android.util.Log; -import android.view.LayoutInflater; - -import com.android.internal.annotations.VisibleForTesting; -import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; -import com.android.systemui.plugins.Plugin; -import com.android.systemui.plugins.PluginFragment; -import com.android.systemui.plugins.PluginListener; -import com.android.systemui.shared.plugins.VersionInfo.InvalidVersionException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class PluginInstanceManager { - - private static final boolean DEBUG = false; - - private static final String TAG = "PluginInstanceManager"; - public static final String PLUGIN_PERMISSION = "com.android.systemui.permission.PLUGIN"; - - private final Context mContext; - private final PluginListener mListener; - private final String mAction; - private final boolean mAllowMultiple; - private final VersionInfo mVersion; - - @VisibleForTesting - final MainHandler mMainHandler; - @VisibleForTesting - final PluginHandler mPluginHandler; - private final boolean isDebuggable; - private final PackageManager mPm; - private final PluginManagerImpl mManager; - private final ArraySet mWhitelistedPlugins = new ArraySet<>(); - - PluginInstanceManager(Context context, String action, PluginListener listener, - boolean allowMultiple, Looper looper, VersionInfo version, PluginManagerImpl manager) { - this(context, context.getPackageManager(), action, listener, allowMultiple, looper, version, - manager, manager.isDebuggable(), manager.getWhitelistedPlugins()); - } - - @VisibleForTesting - PluginInstanceManager(Context context, PackageManager pm, String action, - PluginListener listener, boolean allowMultiple, Looper looper, VersionInfo version, - PluginManagerImpl manager, boolean debuggable, String[] pluginWhitelist) { - mMainHandler = new MainHandler(Looper.getMainLooper()); - mPluginHandler = new PluginHandler(looper); - mManager = manager; - mContext = context; - mPm = pm; - mAction = action; - mListener = listener; - mAllowMultiple = allowMultiple; - mVersion = version; - mWhitelistedPlugins.addAll(Arrays.asList(pluginWhitelist)); - isDebuggable = debuggable; - } - - public PluginInfo getPlugin() { - if (Looper.myLooper() != Looper.getMainLooper()) { - throw new RuntimeException("Must be called from UI thread"); - } - mPluginHandler.handleQueryPlugins(null /* All packages */); - if (mPluginHandler.mPlugins.size() > 0) { - mMainHandler.removeMessages(MainHandler.PLUGIN_CONNECTED); - PluginInfo info = mPluginHandler.mPlugins.get(0); - PluginPrefs.setHasPlugins(mContext); - info.mPlugin.onCreate(mContext, info.mPluginContext); - return info; - } - return null; - } - - public void loadAll() { - if (DEBUG) Log.d(TAG, "startListening"); - mPluginHandler.sendEmptyMessage(PluginHandler.QUERY_ALL); - } - - public void destroy() { - if (DEBUG) Log.d(TAG, "stopListening"); - ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); - for (PluginInfo plugin : plugins) { - mMainHandler.obtainMessage(MainHandler.PLUGIN_DISCONNECTED, - plugin.mPlugin).sendToTarget(); - } - } - - public void onPackageRemoved(String pkg) { - mPluginHandler.obtainMessage(PluginHandler.REMOVE_PKG, pkg).sendToTarget(); - } - - public void onPackageChange(String pkg) { - mPluginHandler.obtainMessage(PluginHandler.REMOVE_PKG, pkg).sendToTarget(); - mPluginHandler.obtainMessage(PluginHandler.QUERY_PKG, pkg).sendToTarget(); - } - - public boolean checkAndDisable(String className) { - boolean disableAny = false; - ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); - for (PluginInfo info : plugins) { - if (className.startsWith(info.mPackage)) { - disableAny |= disable(info, PluginEnabler.DISABLED_FROM_EXPLICIT_CRASH); - } - } - return disableAny; - } - - public boolean disableAll() { - ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); - boolean disabledAny = false; - for (int i = 0; i < plugins.size(); i++) { - disabledAny |= disable(plugins.get(i), PluginEnabler.DISABLED_FROM_SYSTEM_CRASH); - } - return disabledAny; - } - - private boolean isPluginWhitelisted(ComponentName pluginName) { - for (String componentNameOrPackage : mWhitelistedPlugins) { - ComponentName componentName = ComponentName.unflattenFromString(componentNameOrPackage); - if (componentName == null) { - if (componentNameOrPackage.equals(pluginName.getPackageName())) { - return true; - } - } else { - if (componentName.equals(pluginName)) { - return true; - } - } - } - return false; - } - - private boolean disable(PluginInfo info, @PluginEnabler.DisableReason int reason) { - // Live by the sword, die by the sword. - // Misbehaving plugins get disabled and won't come back until uninstall/reinstall. - - ComponentName pluginComponent = new ComponentName(info.mPackage, info.mClass); - // If a plugin is detected in the stack of a crash then this will be called for that - // plugin, if the plugin causing a crash cannot be identified, they are all disabled - // assuming one of them must be bad. - if (isPluginWhitelisted(pluginComponent)) { - // Don't disable whitelisted plugins as they are a part of the OS. - return false; - } - Log.w(TAG, "Disabling plugin " + pluginComponent.flattenToShortString()); - mManager.getPluginEnabler().setDisabled(pluginComponent, reason); - - return true; - } - - public boolean dependsOn(Plugin p, Class cls) { - ArrayList plugins = new ArrayList(mPluginHandler.mPlugins); - for (PluginInfo info : plugins) { - if (info.mPlugin.getClass().getName().equals(p.getClass().getName())) { - return info.mVersion != null && info.mVersion.hasClass(cls); - } - } - return false; - } - - @Override - public String toString() { - return String.format("%s@%s (action=%s)", - getClass().getSimpleName(), hashCode(), mAction); - } - - private class MainHandler extends Handler { - private static final int PLUGIN_CONNECTED = 1; - private static final int PLUGIN_DISCONNECTED = 2; - - public MainHandler(Looper looper) { - super(looper); - } - - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case PLUGIN_CONNECTED: - if (DEBUG) Log.d(TAG, "onPluginConnected"); - PluginPrefs.setHasPlugins(mContext); - PluginInfo info = (PluginInfo) msg.obj; - mManager.handleWtfs(); - if (!(msg.obj instanceof PluginFragment)) { - // Only call onDestroy for plugins that aren't fragments, as fragments - // will get the onCreate as part of the fragment lifecycle. - info.mPlugin.onCreate(mContext, info.mPluginContext); - } - mListener.onPluginConnected(info.mPlugin, info.mPluginContext); - break; - case PLUGIN_DISCONNECTED: - if (DEBUG) Log.d(TAG, "onPluginDisconnected"); - mListener.onPluginDisconnected((T) msg.obj); - if (!(msg.obj instanceof PluginFragment)) { - // Only call onDestroy for plugins that aren't fragments, as fragments - // will get the onDestroy as part of the fragment lifecycle. - ((T) msg.obj).onDestroy(); - } - break; - default: - super.handleMessage(msg); - break; - } - } - } - - private class PluginHandler extends Handler { - private static final int QUERY_ALL = 1; - private static final int QUERY_PKG = 2; - private static final int REMOVE_PKG = 3; - - private final ArrayList> mPlugins = new ArrayList<>(); - - public PluginHandler(Looper looper) { - super(looper); - } - - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case QUERY_ALL: - if (DEBUG) Log.d(TAG, "queryAll " + mAction); - for (int i = mPlugins.size() - 1; i >= 0; i--) { - PluginInfo pluginInfo = mPlugins.get(i); - mMainHandler.obtainMessage( - MainHandler.PLUGIN_DISCONNECTED, pluginInfo.mPlugin).sendToTarget(); - } - mPlugins.clear(); - handleQueryPlugins(null); - break; - case REMOVE_PKG: - String pkg = (String) msg.obj; - for (int i = mPlugins.size() - 1; i >= 0; i--) { - final PluginInfo plugin = mPlugins.get(i); - if (plugin.mPackage.equals(pkg)) { - mMainHandler.obtainMessage(MainHandler.PLUGIN_DISCONNECTED, - plugin.mPlugin).sendToTarget(); - mPlugins.remove(i); - } - } - break; - case QUERY_PKG: - String p = (String) msg.obj; - if (DEBUG) Log.d(TAG, "queryPkg " + p + " " + mAction); - if (mAllowMultiple || (mPlugins.size() == 0)) { - handleQueryPlugins(p); - } else { - if (DEBUG) Log.d(TAG, "Too many of " + mAction); - } - break; - default: - super.handleMessage(msg); - } - } - - private void handleQueryPlugins(String pkgName) { - // This isn't actually a service and shouldn't ever be started, but is - // a convenient PM based way to manage our plugins. - Intent intent = new Intent(mAction); - if (pkgName != null) { - intent.setPackage(pkgName); - } - List result = mPm.queryIntentServices(intent, 0); - if (DEBUG) Log.d(TAG, "Found " + result.size() + " plugins"); - if (result.size() > 1 && !mAllowMultiple) { - // TODO: Show warning. - Log.w(TAG, "Multiple plugins found for " + mAction); - if (DEBUG) { - for (ResolveInfo info : result) { - ComponentName name = new ComponentName(info.serviceInfo.packageName, - info.serviceInfo.name); - Log.w(TAG, " " + name); - } - } - return; - } - for (ResolveInfo info : result) { - ComponentName name = new ComponentName(info.serviceInfo.packageName, - info.serviceInfo.name); - PluginInfo t = handleLoadPlugin(name); - if (t == null) continue; - - // add plugin before sending PLUGIN_CONNECTED message - mPlugins.add(t); - mMainHandler.obtainMessage(mMainHandler.PLUGIN_CONNECTED, t).sendToTarget(); - } - } - - protected PluginInfo handleLoadPlugin(ComponentName component) { - // This was already checked, but do it again here to make extra extra sure, we don't - // use these on production builds. - if (!isDebuggable && !isPluginWhitelisted(component)) { - // Never ever ever allow these on production builds, they are only for prototyping. - Log.w(TAG, "Plugin cannot be loaded on production build: " + component); - return null; - } - if (!mManager.getPluginEnabler().isEnabled(component)) { - if (DEBUG) Log.d(TAG, "Plugin is not enabled, aborting load: " + component); - return null; - } - String pkg = component.getPackageName(); - String cls = component.getClassName(); - try { - ApplicationInfo info = mPm.getApplicationInfo(pkg, 0); - // TODO: This probably isn't needed given that we don't have IGNORE_SECURITY on - if (mPm.checkPermission(PLUGIN_PERMISSION, pkg) - != PackageManager.PERMISSION_GRANTED) { - Log.d(TAG, "Plugin doesn't have permission: " + pkg); - return null; - } - // Create our own ClassLoader so we can use our own code as the parent. - ClassLoader classLoader = mManager.getClassLoader(info); - Context pluginContext = new PluginContextWrapper( - mContext.createApplicationContext(info, 0), classLoader); - Class pluginClass = Class.forName(cls, true, classLoader); - // TODO: Only create the plugin before version check if we need it for - // legacy version check. - T plugin = (T) pluginClass.newInstance(); - try { - VersionInfo version = checkVersion(pluginClass, plugin, mVersion); - if (DEBUG) Log.d(TAG, "createPlugin"); - return new PluginInfo(pkg, cls, plugin, pluginContext, version); - } catch (InvalidVersionException e) { - final int icon = Resources.getSystem().getIdentifier( - "stat_sys_warning", "drawable", "android"); - final int color = Resources.getSystem().getIdentifier( - "system_notification_accent_color", "color", "android"); - final Notification.Builder nb = new Notification.Builder(mContext, - PluginManager.NOTIFICATION_CHANNEL_ID) - .setStyle(new Notification.BigTextStyle()) - .setSmallIcon(icon) - .setWhen(0) - .setShowWhen(false) - .setVisibility(Notification.VISIBILITY_PUBLIC) - .setColor(mContext.getColor(color)); - String label = cls; - try { - label = mPm.getServiceInfo(component, 0).loadLabel(mPm).toString(); - } catch (NameNotFoundException e2) { - } - if (!e.isTooNew()) { - // Localization not required as this will never ever appear in a user build. - nb.setContentTitle("Plugin \"" + label + "\" is too old") - .setContentText("Contact plugin developer to get an updated" - + " version.\n" + e.getMessage()); - } else { - // Localization not required as this will never ever appear in a user build. - nb.setContentTitle("Plugin \"" + label + "\" is too new") - .setContentText("Check to see if an OTA is available.\n" - + e.getMessage()); - } - Intent i = new Intent(PluginManagerImpl.DISABLE_PLUGIN).setData( - Uri.parse("package://" + component.flattenToString())); - PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, - PendingIntent.FLAG_IMMUTABLE); - nb.addAction(new Action.Builder(null, "Disable plugin", pi).build()); - mContext.getSystemService(NotificationManager.class) - .notify(SystemMessage.NOTE_PLUGIN, nb.build()); - // TODO: Warn user. - Log.w(TAG, "Plugin has invalid interface version " + plugin.getVersion() - + ", expected " + mVersion); - return null; - } - } catch (Throwable e) { - Log.w(TAG, "Couldn't load plugin: " + pkg, e); - return null; - } - } - - private VersionInfo checkVersion(Class pluginClass, T plugin, VersionInfo version) - throws InvalidVersionException { - VersionInfo pv = new VersionInfo().addClass(pluginClass); - if (pv.hasVersionInfo()) { - version.checkVersion(pv); - } else { - int fallbackVersion = plugin.getVersion(); - if (fallbackVersion != version.getDefaultVersion()) { - throw new InvalidVersionException("Invalid legacy version", false); - } - return null; - } - return pv; - } - } - - public static class PluginContextWrapper extends ContextWrapper { - private final ClassLoader mClassLoader; - private LayoutInflater mInflater; - - public PluginContextWrapper(Context base, ClassLoader classLoader) { - super(base); - mClassLoader = classLoader; - } - - @Override - public ClassLoader getClassLoader() { - return mClassLoader; - } - - @Override - public Object getSystemService(String name) { - if (LAYOUT_INFLATER_SERVICE.equals(name)) { - if (mInflater == null) { - mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); - } - return mInflater; - } - return getBaseContext().getSystemService(name); - } - } - - static class PluginInfo { - private final Context mPluginContext; - private final VersionInfo mVersion; - private String mClass; - T mPlugin; - String mPackage; - - public PluginInfo(String pkg, String cls, T plugin, Context pluginContext, - VersionInfo info) { - mPlugin = plugin; - mClass = cls; - mPackage = pkg; - mPluginContext = pluginContext; - mVersion = info; - } - } -} diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java index 3f907a8aa3..c89be86911 100644 --- a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManager.java @@ -27,18 +27,18 @@ public interface PluginManager { // must be one of the channels created in NotificationChannels.java String NOTIFICATION_CHANNEL_ID = "ALR"; - String[] getWhitelistedPlugins(); + /** Returns plugins that don't get disabled when an exceptoin occurs. */ + String[] getPrivilegedPlugins(); - T getOneShotPlugin(Class cls); - T getOneShotPlugin(String action, Class cls); - - void addPluginListener(PluginListener listener, Class cls); - void addPluginListener(PluginListener listener, Class cls, + /** */ + void addPluginListener(PluginListener listener, Class cls); + /** */ + void addPluginListener(PluginListener listener, Class cls, boolean allowMultiple); void addPluginListener(String action, PluginListener listener, - Class cls); + Class cls); void addPluginListener(String action, PluginListener listener, - Class cls, boolean allowMultiple); + Class cls, boolean allowMultiple); void removePluginListener(PluginListener listener); diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java index c89aa00d5e..06506ffdbf 100644 --- a/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java @@ -14,50 +14,33 @@ package com.android.systemui.shared.plugins; -import android.app.LoadedApk; -import android.app.Notification; -import android.app.Notification.Action; import android.app.NotificationManager; -import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.content.res.Resources; import android.net.Uri; import android.os.Build; -import android.os.Handler; -import android.os.Looper; import android.os.SystemProperties; -import android.text.TextUtils; import android.util.ArrayMap; import android.util.ArraySet; import android.util.Log; import android.widget.Toast; -import com.android.internal.annotations.VisibleForTesting; import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; import com.android.systemui.plugins.Plugin; import com.android.systemui.plugins.PluginListener; -import com.android.systemui.plugins.annotations.ProvidesInterface; -import com.android.systemui.shared.plugins.PluginInstanceManager.PluginInfo; -import dalvik.system.PathClassLoader; - -import java.io.File; import java.io.FileDescriptor; import java.io.PrintWriter; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Optional; + /** * @see Plugin */ @@ -66,113 +49,65 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage private static final String TAG = PluginManagerImpl.class.getSimpleName(); static final String DISABLE_PLUGIN = "com.android.systemui.action.DISABLE_PLUGIN"; - private final ArrayMap, PluginInstanceManager> mPluginMap + private final ArrayMap, PluginActionManager> mPluginMap = new ArrayMap<>(); private final Map mClassLoaders = new ArrayMap<>(); - private final ArraySet mOneShotPackages = new ArraySet<>(); - private final ArraySet mWhitelistedPlugins = new ArraySet<>(); + private final ArraySet mPrivilegedPlugins = new ArraySet<>(); private final Context mContext; - private final PluginInstanceManagerFactory mFactory; + private final PluginActionManager.Factory mActionManagerFactory; private final boolean mIsDebuggable; private final PluginPrefs mPluginPrefs; private final PluginEnabler mPluginEnabler; - private final PluginInitializer mPluginInitializer; - private ClassLoaderFilter mParentClassLoader; private boolean mListening; - private boolean mHasOneShot; - private Looper mLooper; - public PluginManagerImpl(Context context, PluginInitializer initializer) { - this(context, new PluginInstanceManagerFactory(), initializer.isDebuggable(), - (UncaughtExceptionHandler) invoke(sGetUncaughtExceptionPreHandler, null), initializer); - } - - @VisibleForTesting - PluginManagerImpl(Context context, PluginInstanceManagerFactory factory, boolean debuggable, - UncaughtExceptionHandler defaultHandler, final PluginInitializer initializer) { + public PluginManagerImpl(Context context, + PluginActionManager.Factory actionManagerFactory, + boolean debuggable, + Optional defaultHandlerOptional, + PluginEnabler pluginEnabler, + PluginPrefs pluginPrefs, + List privilegedPlugins) { mContext = context; - mFactory = factory; - mLooper = initializer.getBgLooper(); + mActionManagerFactory = actionManagerFactory; mIsDebuggable = debuggable; - mWhitelistedPlugins.addAll(Arrays.asList(initializer.getWhitelistedPlugins(mContext))); - mPluginPrefs = new PluginPrefs(mContext); - mPluginEnabler = initializer.getPluginEnabler(mContext); - mPluginInitializer = initializer; + mPrivilegedPlugins.addAll(privilegedPlugins); + mPluginPrefs = pluginPrefs; + mPluginEnabler = pluginEnabler; PluginExceptionHandler uncaughtExceptionHandler = new PluginExceptionHandler( - defaultHandler); - invoke(sSetUncaughtExceptionPreHandler, null, uncaughtExceptionHandler); - - new Handler(mLooper).post(new Runnable() { - @Override - public void run() { - initializer.onPluginManagerInit(); - } - }); + defaultHandlerOptional); + invoke(sSetUncaughtExceptionPreHandler, uncaughtExceptionHandler); } public boolean isDebuggable() { return mIsDebuggable; } - public String[] getWhitelistedPlugins() { - return mWhitelistedPlugins.toArray(new String[0]); + public String[] getPrivilegedPlugins() { + return mPrivilegedPlugins.toArray(new String[0]); } - public PluginEnabler getPluginEnabler() { - return mPluginEnabler; - } - - // TODO(mankoff): This appears to be only called from tests. Remove? - public T getOneShotPlugin(Class cls) { - ProvidesInterface info = cls.getDeclaredAnnotation(ProvidesInterface.class); - if (info == null) { - throw new RuntimeException(cls + " doesn't provide an interface"); - } - if (TextUtils.isEmpty(info.action())) { - throw new RuntimeException(cls + " doesn't provide an action"); - } - return getOneShotPlugin(info.action(), cls); - } - - public T getOneShotPlugin(String action, Class cls) { - if (Looper.myLooper() != Looper.getMainLooper()) { - throw new RuntimeException("Must be called from UI thread"); - } - // Passing null causes compiler to complain about incompatible (generic) types. - PluginListener dummy = null; - PluginInstanceManager p = mFactory.createPluginInstanceManager(mContext, action, dummy, - false, mLooper, cls, this); - mPluginPrefs.addAction(action); - PluginInfo info = p.getPlugin(); - if (info != null) { - mOneShotPackages.add(info.mPackage); - mHasOneShot = true; - startListening(); - return info.mPlugin; - } - return null; - } - - public void addPluginListener(PluginListener listener, Class cls) { + /** */ + public void addPluginListener(PluginListener listener, Class cls) { addPluginListener(listener, cls, false); } - public void addPluginListener(PluginListener listener, Class cls, + /** */ + public void addPluginListener(PluginListener listener, Class cls, boolean allowMultiple) { addPluginListener(PluginManager.Helper.getAction(cls), listener, cls, allowMultiple); } public void addPluginListener(String action, PluginListener listener, - Class cls) { + Class cls) { addPluginListener(action, listener, cls, false); } public void addPluginListener(String action, PluginListener listener, - Class cls, boolean allowMultiple) { + Class cls, boolean allowMultiple) { mPluginPrefs.addAction(action); - PluginInstanceManager p = mFactory.createPluginInstanceManager(mContext, action, listener, - allowMultiple, mLooper, cls, this); + PluginActionManager p = mActionManagerFactory.create(action, listener, cls, + allowMultiple, isDebuggable()); p.loadAll(); synchronized (this) { mPluginMap.put(listener, p); @@ -204,14 +139,13 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage filter.addAction(PLUGIN_CHANGED); filter.addAction(DISABLE_PLUGIN); filter.addDataScheme("package"); - mContext.registerReceiver(this, filter, PluginInstanceManager.PLUGIN_PERMISSION, null); + mContext.registerReceiver(this, filter, PluginActionManager.PLUGIN_PERMISSION, null); filter = new IntentFilter(Intent.ACTION_USER_UNLOCKED); mContext.registerReceiver(this, filter); } private void stopListening() { - // Never stop listening if a one-shot is present. - if (!mListening || mHasOneShot) return; + if (!mListening) return; mListening = false; mContext.unregisterReceiver(this); } @@ -220,7 +154,7 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage public void onReceive(Context context, Intent intent) { if (Intent.ACTION_USER_UNLOCKED.equals(intent.getAction())) { synchronized (this) { - for (PluginInstanceManager manager : mPluginMap.values()) { + for (PluginActionManager manager : mPluginMap.values()) { manager.loadAll(); } } @@ -228,46 +162,17 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage Uri uri = intent.getData(); ComponentName component = ComponentName.unflattenFromString( uri.toString().substring(10)); - if (isPluginWhitelisted(component)) { - // Don't disable whitelisted plugins as they are a part of the OS. + if (isPluginPrivileged(component)) { + // Don't disable privileged plugins as they are a part of the OS. return; } - getPluginEnabler().setDisabled(component, PluginEnabler.DISABLED_INVALID_VERSION); + mPluginEnabler.setDisabled(component, PluginEnabler.DISABLED_INVALID_VERSION); mContext.getSystemService(NotificationManager.class).cancel(component.getClassName(), SystemMessage.NOTE_PLUGIN); } else { Uri data = intent.getData(); String pkg = data.getEncodedSchemeSpecificPart(); ComponentName componentName = ComponentName.unflattenFromString(pkg); - if (mOneShotPackages.contains(pkg)) { - int icon = Resources.getSystem().getIdentifier( - "stat_sys_warning", "drawable", "android"); - int color = Resources.getSystem().getIdentifier( - "system_notification_accent_color", "color", "android"); - String label = pkg; - try { - PackageManager pm = mContext.getPackageManager(); - label = pm.getApplicationInfo(pkg, 0).loadLabel(pm).toString(); - } catch (NameNotFoundException e) { - } - // Localization not required as this will never ever appear in a user build. - final Notification.Builder nb = - new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID) - .setSmallIcon(icon) - .setWhen(0) - .setShowWhen(false) - .setPriority(Notification.PRIORITY_MAX) - .setVisibility(Notification.VISIBILITY_PUBLIC) - .setColor(mContext.getColor(color)) - .setContentTitle("Plugin \"" + label + "\" has updated") - .setContentText("Restart SysUI for changes to take effect."); - Intent i = new Intent("com.android.systemui.action.RESTART").setData( - Uri.parse("package://" + pkg)); - PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_MUTABLE_UNAUDITED); - nb.addAction(new Action.Builder(null, "Restart SysUI", pi).build()); - mContext.getSystemService(NotificationManager.class) - .notify(SystemMessage.NOTE_PLUGIN, nb.build()); - } if (clearClassLoader(pkg)) { if (Build.IS_ENG) { Toast.makeText(mContext, "Reloading " + pkg, Toast.LENGTH_LONG).show(); @@ -278,22 +183,24 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction()) && componentName != null) { @PluginEnabler.DisableReason int disableReason = - getPluginEnabler().getDisableReason(componentName); + mPluginEnabler.getDisableReason(componentName); if (disableReason == PluginEnabler.DISABLED_FROM_EXPLICIT_CRASH || disableReason == PluginEnabler.DISABLED_FROM_SYSTEM_CRASH || disableReason == PluginEnabler.DISABLED_INVALID_VERSION) { Log.i(TAG, "Re-enabling previously disabled plugin that has been " + "updated: " + componentName.flattenToShortString()); - getPluginEnabler().setEnabled(componentName); + mPluginEnabler.setEnabled(componentName); } } synchronized (this) { - if (!Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) { - for (PluginInstanceManager manager : mPluginMap.values()) { - manager.onPackageChange(pkg); + if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) + || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction()) + || Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) { + for (PluginActionManager actionManager : mPluginMap.values()) { + actionManager.reloadPackage(pkg); } } else { - for (PluginInstanceManager manager : mPluginMap.values()) { + for (PluginActionManager manager : mPluginMap.values()) { manager.onPackageRemoved(pkg); } } @@ -301,41 +208,10 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage } } - /** Returns class loader specific for the given plugin. */ - public ClassLoader getClassLoader(ApplicationInfo appInfo) { - if (!mIsDebuggable && !isPluginPackageWhitelisted(appInfo.packageName)) { - Log.w(TAG, "Cannot get class loader for non-whitelisted plugin. Src:" - + appInfo.sourceDir + ", pkg: " + appInfo.packageName); - return null; - } - if (mClassLoaders.containsKey(appInfo.packageName)) { - return mClassLoaders.get(appInfo.packageName); - } - - List zipPaths = new ArrayList<>(); - List libPaths = new ArrayList<>(); - LoadedApk.makePaths(null, true, appInfo, zipPaths, libPaths); - ClassLoader classLoader = new PathClassLoader( - TextUtils.join(File.pathSeparator, zipPaths), - TextUtils.join(File.pathSeparator, libPaths), - getParentClassLoader()); - mClassLoaders.put(appInfo.packageName, classLoader); - return classLoader; - } - private boolean clearClassLoader(String pkg) { return mClassLoaders.remove(pkg) != null; } - ClassLoader getParentClassLoader() { - if (mParentClassLoader == null) { - // Lazily load this so it doesn't have any effect on devices without plugins. - mParentClassLoader = new ClassLoaderFilter(getClass().getClassLoader(), - "com.android.systemui.plugin"); - } - return mParentClassLoader; - } - public boolean dependsOn(Plugin p, Class cls) { synchronized (this) { for (int i = 0; i < mPluginMap.size(); i++) { @@ -347,46 +223,18 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage return false; } - public void handleWtfs() { - mPluginInitializer.handleWtfs(); - } - public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { synchronized (this) { pw.println(String.format(" plugin map (%d):", mPluginMap.size())); - for (PluginListener listener : mPluginMap.keySet()) { + for (PluginListener listener : mPluginMap.keySet()) { pw.println(String.format(" %s -> %s", listener, mPluginMap.get(listener))); } } } - @VisibleForTesting - public static class PluginInstanceManagerFactory { - public PluginInstanceManager createPluginInstanceManager(Context context, - String action, PluginListener listener, boolean allowMultiple, Looper looper, - Class cls, PluginManagerImpl manager) { - return new PluginInstanceManager(context, action, listener, allowMultiple, looper, - new VersionInfo().addClass(cls), manager); - } - } - - private boolean isPluginPackageWhitelisted(String packageName) { - for (String componentNameOrPackage : mWhitelistedPlugins) { - ComponentName componentName = ComponentName.unflattenFromString(componentNameOrPackage); - if (componentName != null) { - if (componentName.getPackageName().equals(packageName)) { - return true; - } - } else if (componentNameOrPackage.equals(packageName)) { - return true; - } - } - return false; - } - - private boolean isPluginWhitelisted(ComponentName pluginName) { - for (String componentNameOrPackage : mWhitelistedPlugins) { + private boolean isPluginPrivileged(ComponentName pluginName) { + for (String componentNameOrPackage : mPrivilegedPlugins) { ComponentName componentName = ComponentName.unflattenFromString(componentNameOrPackage); if (componentName != null) { if (componentName.equals(pluginName)) { @@ -401,7 +249,7 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage // This allows plugins to include any libraries or copied code they want by only including // classes from the plugin library. - private static class ClassLoaderFilter extends ClassLoader { + static class ClassLoaderFilter extends ClassLoader { private final String mPackage; private final ClassLoader mBase; @@ -419,16 +267,20 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage } private class PluginExceptionHandler implements UncaughtExceptionHandler { - private final UncaughtExceptionHandler mHandler; + private final Optional mExceptionHandlerOptional; - private PluginExceptionHandler(UncaughtExceptionHandler handler) { - mHandler = handler; + private PluginExceptionHandler( + Optional exceptionHandlerOptional) { + mExceptionHandlerOptional = exceptionHandlerOptional; } @Override public void uncaughtException(Thread thread, Throwable throwable) { if (SystemProperties.getBoolean("plugin.debugging", false)) { - mHandler.uncaughtException(thread, throwable); + Throwable finalThrowable = throwable; + mExceptionHandlerOptional.ifPresent( + handler -> handler.uncaughtException(thread, finalThrowable)); + return; } // Search for and disable plugins that may have been involved in this crash. @@ -438,7 +290,7 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage // disable all the plugins, so we can be sure that SysUI is running as // best as possible. synchronized (this) { - for (PluginInstanceManager manager : mPluginMap.values()) { + for (PluginActionManager manager : mPluginMap.values()) { disabledAny |= manager.disableAll(); } } @@ -448,7 +300,9 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage } // Run the normal exception handler so we can crash and cleanup our state. - mHandler.uncaughtException(thread, throwable); + Throwable finalThrowable = throwable; + mExceptionHandlerOptional.ifPresent( + handler -> handler.uncaughtException(thread, finalThrowable)); } private boolean checkStack(Throwable throwable) { @@ -456,7 +310,7 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage boolean disabledAny = false; synchronized (this) { for (StackTraceElement element : throwable.getStackTrace()) { - for (PluginInstanceManager manager : mPluginMap.values()) { + for (PluginActionManager manager : mPluginMap.values()) { disabledAny |= manager.checkAndDisable(element.getClassName()); } } @@ -471,13 +325,11 @@ public class PluginManagerImpl extends BroadcastReceiver implements PluginManage } } - private static Method sGetUncaughtExceptionPreHandler; private static Method sSetUncaughtExceptionPreHandler; static { try { Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class); - sGetUncaughtExceptionPreHandler = (Method) getDeclaredMethod.invoke(Thread.class, "getUncaughtExceptionPreHandler", new Class[]{}); sSetUncaughtExceptionPreHandler = (Method) getDeclaredMethod.invoke(Thread.class, "setUncaughtExceptionPreHandler", new Class[]{UncaughtExceptionHandler.class}); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); diff --git a/SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java b/SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java index bb845cd879..6be3243879 100644 --- a/SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java +++ b/SystemUIShared/src/com/android/systemui/shared/plugins/VersionInfo.java @@ -119,6 +119,8 @@ public class VersionInfo { public static class InvalidVersionException extends RuntimeException { private final boolean mTooNew; + private int mExpected; + private int mActual; public InvalidVersionException(String str, boolean tooNew) { super(str); @@ -128,11 +130,21 @@ public class VersionInfo { public InvalidVersionException(Class cls, boolean tooNew, int expected, int actual) { super(cls.getSimpleName() + " expected version " + expected + " but had " + actual); mTooNew = tooNew; + mExpected = expected; + mActual = actual; } public boolean isTooNew() { return mTooNew; } + + public int getExpectedVersion() { + return mExpected; + } + + public int getActualVersion() { + return mActual; + } } private static class Version { diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl b/SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl index 277b2e31f7..01497516e0 100644 --- a/SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl +++ b/SystemUIShared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl @@ -77,8 +77,27 @@ oneway interface IOverviewProxy { void onSplitScreenSecondaryBoundsChanged(in Rect bounds, in Rect insets) = 17; /** - * Sent IME status changes + * Sent when suggested rotation button could be shown */ - void onImeWindowStatusChanged(int displayId, IBinder token, int vis, int backDisposition, - boolean showImeSwitcher) = 18; + void onRotationProposal(int rotation, boolean isValid) = 18; + + /** + * Sent when disable flags change + */ + void disable(int displayId, int state1, int state2, boolean animate) = 19; + + /** + * Sent when behavior changes. See WindowInsetsController#@Behavior + */ + void onSystemBarAttributesChanged(int displayId, int behavior) = 20; + + /** + * Sent when screen turned on and ready to use (blocker scrim is hidden) + */ + void onScreenTurnedOn() = 21; + + /** + * Sent when the desired dark intensity of the nav buttons has changed + */ + void onNavButtonsDarkIntensityChanged(float darkIntensity) = 22; } diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl b/SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl index d5fe7d07fe..773a7d7012 100644 --- a/SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl +++ b/SystemUIShared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl @@ -151,5 +151,20 @@ interface ISystemUiProxy { /** Notifies that a swipe-up gesture has started */ oneway void notifySwipeUpGestureStarted() = 46; - // Next id = 47 + /** Notifies when taskbar status updated */ + oneway void notifyTaskbarStatus(boolean visible, boolean stashed) = 47; + + /** + * Notifies sysui when taskbar requests autoHide to stop auto-hiding + * If called to suspend, caller is also responsible for calling this method to un-suspend + * @param suspend should be true to stop auto-hide, false to resume normal behavior + */ + oneway void notifyTaskbarAutohideSuspend(boolean suspend) = 48; + + /** + * Notifies SystemUI to invoke IME Switcher. + */ + void onImeSwitcherPressed() = 49; + + // Next id = 50 } diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java b/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java index e9e9b2421d..675dc9b533 100644 --- a/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java +++ b/SystemUIShared/src/com/android/systemui/shared/recents/model/Task.java @@ -23,21 +23,20 @@ import android.app.ActivityManager.TaskDescription; import android.app.TaskInfo; import android.content.ComponentName; import android.content.Intent; -import android.content.pm.ActivityInfo; -import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.view.ViewDebug; -import com.android.systemui.shared.recents.utilities.Utilities; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import java.io.PrintWriter; -import java.util.ArrayList; import java.util.Objects; /** * A task in the recent tasks list. + * TODO: Move this into Launcher or see if we can remove now */ public class Task { @@ -52,6 +51,7 @@ public class Task { @ViewDebug.ExportedProperty(category="recents") public int windowingMode; @ViewDebug.ExportedProperty(category="recents") + @NonNull public final Intent baseIntent; @ViewDebug.ExportedProperty(category="recents") public final int userId; @@ -85,7 +85,7 @@ public class Task { updateHashCode(); } - public TaskKey(int id, int windowingMode, Intent intent, + public TaskKey(int id, int windowingMode, @NonNull Intent intent, ComponentName sourceComponent, int userId, long lastActiveTime) { this.id = id; this.windowingMode = windowingMode; @@ -97,7 +97,7 @@ public class Task { updateHashCode(); } - public TaskKey(int id, int windowingMode, Intent intent, + public TaskKey(int id, int windowingMode, @NonNull Intent intent, ComponentName sourceComponent, int userId, long lastActiveTime, int displayId) { this.id = id; this.windowingMode = windowingMode; @@ -201,8 +201,8 @@ public class Task { * The icon is the task description icon (if provided), which falls back to the activity icon, * which can then fall back to the application icon. */ - public Drawable icon; - public ThumbnailData thumbnail; + @Nullable public Drawable icon; + @Nullable public ThumbnailData thumbnail; @ViewDebug.ExportedProperty(category="recents") @Deprecated public String title; diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java b/SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java index 6594d5f51a..1142e05f46 100644 --- a/SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java +++ b/SystemUIShared/src/com/android/systemui/shared/recents/model/ThumbnailData.java @@ -22,7 +22,6 @@ import static android.graphics.Bitmap.Config.ARGB_8888; import static com.android.systemui.shared.system.WindowManagerWrapper.WINDOWING_MODE_UNDEFINED; -import android.window.TaskSnapshot; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Point; @@ -30,6 +29,9 @@ import android.graphics.Rect; import android.hardware.HardwareBuffer; import android.util.Log; import android.view.WindowInsetsController.Appearance; +import android.window.TaskSnapshot; + +import java.util.HashMap; /** * Data for a single thumbnail. @@ -40,6 +42,7 @@ public class ThumbnailData { public int orientation; public int rotation; public Rect insets; + public Rect letterboxInsets; public boolean reducedResolution; public boolean isRealSnapshot; public boolean isTranslucent; @@ -53,6 +56,7 @@ public class ThumbnailData { orientation = ORIENTATION_UNDEFINED; rotation = ROTATION_UNDEFINED; insets = new Rect(); + letterboxInsets = new Rect(); reducedResolution = false; scale = 1f; isRealSnapshot = true; @@ -80,9 +84,22 @@ public class ThumbnailData { return thumbnail; } + public static HashMap wrap(int[] taskIds, TaskSnapshot[] snapshots) { + HashMap temp = new HashMap<>(); + if (taskIds == null || snapshots == null || taskIds.length != snapshots.length) { + return temp; + } + + for (int i = snapshots.length - 1; i >= 0; i--) { + temp.put(taskIds[i], new ThumbnailData(snapshots[i])); + } + return temp; + } + public ThumbnailData(TaskSnapshot snapshot) { thumbnail = makeThumbnail(snapshot); insets = new Rect(snapshot.getContentInsets()); + letterboxInsets = new Rect(snapshot.getLetterboxInsets()); orientation = snapshot.getOrientation(); rotation = snapshot.getRotation(); reducedResolution = snapshot.isLowResolution(); diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java index 7dffc26139..8d98a7540a 100644 --- a/SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java +++ b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/Utilities.java @@ -16,13 +16,26 @@ package com.android.systemui.shared.recents.utilities; +import static android.app.StatusBarManager.NAVIGATION_HINT_BACK_ALT; +import static android.app.StatusBarManager.NAVIGATION_HINT_IME_SHOWN; + +import android.annotation.TargetApi; +import android.content.Context; import android.graphics.Color; +import android.graphics.Rect; +import android.inputmethodservice.InputMethodService; +import android.os.Build; import android.os.Handler; import android.os.Message; +import android.util.DisplayMetrics; +import android.view.Surface; +import android.view.WindowManager; /* Common code */ public class Utilities { + private static final float TABLET_MIN_DPS = 600; + /** * Posts a runnable on a handler at the front of the queue ignoring any sync barriers. */ @@ -31,6 +44,23 @@ public class Utilities { h.sendMessageAtFrontOfQueue(msg); } + public static boolean isRotationAnimationCCW(int from, int to) { + // All 180deg WM rotation animations are CCW, match that + if (from == Surface.ROTATION_0 && to == Surface.ROTATION_90) return false; + if (from == Surface.ROTATION_0 && to == Surface.ROTATION_180) return true; //180d so CCW + if (from == Surface.ROTATION_0 && to == Surface.ROTATION_270) return true; + if (from == Surface.ROTATION_90 && to == Surface.ROTATION_0) return true; + if (from == Surface.ROTATION_90 && to == Surface.ROTATION_180) return false; + if (from == Surface.ROTATION_90 && to == Surface.ROTATION_270) return true; //180d so CCW + if (from == Surface.ROTATION_180 && to == Surface.ROTATION_0) return true; //180d so CCW + if (from == Surface.ROTATION_180 && to == Surface.ROTATION_90) return true; + if (from == Surface.ROTATION_180 && to == Surface.ROTATION_270) return false; + if (from == Surface.ROTATION_270 && to == Surface.ROTATION_0) return false; + if (from == Surface.ROTATION_270 && to == Surface.ROTATION_90) return true; //180d so CCW + if (from == Surface.ROTATION_270 && to == Surface.ROTATION_180) return true; + return false; // Default + } + /** Calculates the constrast between two colors, using the algorithm provided by the WCAG v2. */ public static float computeContrastBetweenColors(int bg, int fg) { float bgR = Color.red(bg) / 255f; @@ -58,4 +88,50 @@ public class Utilities { public static float clamp(float value, float min, float max) { return Math.max(min, Math.min(max, value)); } + + /** + * @return updated set of flags from InputMethodService based off {@param oldHints} + * Leaves original hints unmodified + */ + public static int calculateBackDispositionHints(int oldHints, int backDisposition, + boolean imeShown, boolean showImeSwitcher) { + int hints = oldHints; + switch (backDisposition) { + case InputMethodService.BACK_DISPOSITION_DEFAULT: + case InputMethodService.BACK_DISPOSITION_WILL_NOT_DISMISS: + case InputMethodService.BACK_DISPOSITION_WILL_DISMISS: + if (imeShown) { + hints |= NAVIGATION_HINT_BACK_ALT; + } else { + hints &= ~NAVIGATION_HINT_BACK_ALT; + } + break; + case InputMethodService.BACK_DISPOSITION_ADJUST_NOTHING: + hints &= ~NAVIGATION_HINT_BACK_ALT; + break; + } + if (showImeSwitcher) { + hints |= NAVIGATION_HINT_IME_SHOWN; + } else { + hints &= ~NAVIGATION_HINT_IME_SHOWN; + } + + return hints; + } + + /** @return whether or not {@param context} represents that of a large screen device or not */ + @TargetApi(Build.VERSION_CODES.R) + public static boolean isTablet(Context context) { + final WindowManager windowManager = context.getSystemService(WindowManager.class); + final Rect bounds = windowManager.getCurrentWindowMetrics().getBounds(); + + float smallestWidth = dpiFromPx(Math.min(bounds.width(), bounds.height()), + context.getResources().getConfiguration().densityDpi); + return smallestWidth >= TABLET_MIN_DPS; + } + + public static float dpiFromPx(float size, int densityDpi) { + float densityRatio = (float) densityDpi / DisplayMetrics.DENSITY_DEFAULT; + return (size / densityRatio); + } } diff --git a/SystemUIShared/src/com/android/systemui/shared/recents/utilities/ViewRippler.java b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/ViewRippler.java new file mode 100644 index 0000000000..5581a1c905 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/recents/utilities/ViewRippler.java @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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.shared.recents.utilities; + +import android.view.View; + +/** + * Shows view ripples by toggling the provided Views "pressed" state. + * Ripples 4 times. + */ +public class ViewRippler { + private static final int RIPPLE_OFFSET_MS = 50; + private static final int RIPPLE_INTERVAL_MS = 2000; + private View mRoot; + + public void start(View root) { + stop(); // Stop any pending ripple animations + + mRoot = root; + + // Schedule pending ripples, offset the 1st to avoid problems with visibility change + mRoot.postOnAnimationDelayed(mRipple, RIPPLE_OFFSET_MS); + mRoot.postOnAnimationDelayed(mRipple, RIPPLE_INTERVAL_MS); + mRoot.postOnAnimationDelayed(mRipple, 2 * RIPPLE_INTERVAL_MS); + mRoot.postOnAnimationDelayed(mRipple, 3 * RIPPLE_INTERVAL_MS); + mRoot.postOnAnimationDelayed(mRipple, 4 * RIPPLE_INTERVAL_MS); + } + + public void stop() { + if (mRoot != null) mRoot.removeCallbacks(mRipple); + } + + private final Runnable mRipple = new Runnable() { + @Override + public void run() { // Cause the ripple to fire via false presses + if (!mRoot.isAttachedToWindow()) return; + mRoot.setPressed(true /* pressed */); + mRoot.setPressed(false /* pressed */); + } + }; +} \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButton.java b/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButton.java new file mode 100644 index 0000000000..857cc4620e --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButton.java @@ -0,0 +1,311 @@ +/* + * Copyright (C) 2020 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.shared.rotation; + +import android.annotation.DimenRes; +import android.annotation.IdRes; +import android.annotation.LayoutRes; +import android.annotation.StringRes; +import android.content.Context; +import android.content.pm.ActivityInfo; +import android.content.pm.ActivityInfo.Config; +import android.content.res.Resources; +import android.graphics.PixelFormat; +import android.graphics.drawable.AnimatedVectorDrawable; +import android.graphics.drawable.Drawable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.WindowManager.LayoutParams; +import android.view.animation.AccelerateDecelerateInterpolator; +import android.widget.FrameLayout; + +import androidx.core.view.OneShotPreDrawListener; + +import com.android.systemui.shared.rotation.FloatingRotationButtonPositionCalculator.Position; + +/** + * Containing logic for the rotation button on the physical left bottom corner of the screen. + */ +public class FloatingRotationButton implements RotationButton { + + private static final int MARGIN_ANIMATION_DURATION_MILLIS = 300; + + private final WindowManager mWindowManager; + private final ViewGroup mKeyButtonContainer; + private final FloatingRotationButtonView mKeyButtonView; + + private int mContainerSize; + private final Context mContext; + + @StringRes + private final int mContentDescriptionResource; + @DimenRes + private final int mMinMarginResource; + @DimenRes + private final int mRoundedContentPaddingResource; + @DimenRes + private final int mTaskbarLeftMarginResource; + @DimenRes + private final int mTaskbarBottomMarginResource; + @DimenRes + private final int mButtonDiameterResource; + + private AnimatedVectorDrawable mAnimatedDrawable; + private boolean mIsShowing; + private boolean mCanShow = true; + private int mDisplayRotation; + + private boolean mIsTaskbarVisible = false; + private boolean mIsTaskbarStashed = false; + + private FloatingRotationButtonPositionCalculator mPositionCalculator; + + private RotationButtonController mRotationButtonController; + private RotationButtonUpdatesCallback mUpdatesCallback; + private Position mPosition; + + public FloatingRotationButton(Context context, @StringRes int contentDescriptionResource, + @LayoutRes int layout, @IdRes int keyButtonId, @DimenRes int minMargin, + @DimenRes int roundedContentPadding, @DimenRes int taskbarLeftMargin, + @DimenRes int taskbarBottomMargin, @DimenRes int buttonDiameter, + @DimenRes int rippleMaxWidth) { + mWindowManager = context.getSystemService(WindowManager.class); + mKeyButtonContainer = (ViewGroup) LayoutInflater.from(context).inflate(layout, null); + mKeyButtonView = mKeyButtonContainer.findViewById(keyButtonId); + mKeyButtonView.setVisibility(View.VISIBLE); + mKeyButtonView.setContentDescription(context.getString(contentDescriptionResource)); + mKeyButtonView.setRipple(rippleMaxWidth); + + mContext = context; + + mContentDescriptionResource = contentDescriptionResource; + mMinMarginResource = minMargin; + mRoundedContentPaddingResource = roundedContentPadding; + mTaskbarLeftMarginResource = taskbarLeftMargin; + mTaskbarBottomMarginResource = taskbarBottomMargin; + mButtonDiameterResource = buttonDiameter; + + updateDimensionResources(); + } + + private void updateDimensionResources() { + Resources res = mContext.getResources(); + + int defaultMargin = Math.max( + res.getDimensionPixelSize(mMinMarginResource), + res.getDimensionPixelSize(mRoundedContentPaddingResource)); + + int taskbarMarginLeft = + res.getDimensionPixelSize(mTaskbarLeftMarginResource); + int taskbarMarginBottom = + res.getDimensionPixelSize(mTaskbarBottomMarginResource); + + mPositionCalculator = new FloatingRotationButtonPositionCalculator(defaultMargin, + taskbarMarginLeft, taskbarMarginBottom); + + final int diameter = res.getDimensionPixelSize(mButtonDiameterResource); + mContainerSize = diameter + Math.max(defaultMargin, Math.max(taskbarMarginLeft, + taskbarMarginBottom)); + } + + @Override + public void setRotationButtonController(RotationButtonController rotationButtonController) { + mRotationButtonController = rotationButtonController; + updateIcon(mRotationButtonController.getLightIconColor(), + mRotationButtonController.getDarkIconColor()); + } + + @Override + public void setUpdatesCallback(RotationButtonUpdatesCallback updatesCallback) { + mUpdatesCallback = updatesCallback; + } + + @Override + public View getCurrentView() { + return mKeyButtonView; + } + + @Override + public boolean show() { + if (!mCanShow || mIsShowing) { + return false; + } + + mIsShowing = true; + + final LayoutParams layoutParams = adjustViewPositionAndCreateLayoutParams(); + mWindowManager.addView(mKeyButtonContainer, layoutParams); + + if (mAnimatedDrawable != null) { + mAnimatedDrawable.reset(); + mAnimatedDrawable.start(); + } + + // Notify about visibility only after first traversal so we can properly calculate + // the touch region for the button + OneShotPreDrawListener.add(mKeyButtonView, () -> { + if (mIsShowing && mUpdatesCallback != null) { + mUpdatesCallback.onVisibilityChanged(true); + } + }); + + return true; + } + + @Override + public boolean hide() { + if (!mIsShowing) { + return false; + } + mWindowManager.removeViewImmediate(mKeyButtonContainer); + mIsShowing = false; + if (mUpdatesCallback != null) { + mUpdatesCallback.onVisibilityChanged(false); + } + return true; + } + + @Override + public boolean isVisible() { + return mIsShowing; + } + + @Override + public void updateIcon(int lightIconColor, int darkIconColor) { + mAnimatedDrawable = (AnimatedVectorDrawable) mKeyButtonView.getContext() + .getDrawable(mRotationButtonController.getIconResId()); + mKeyButtonView.setImageDrawable(mAnimatedDrawable); + mKeyButtonView.setColors(lightIconColor, darkIconColor); + } + + @Override + public void setOnClickListener(View.OnClickListener onClickListener) { + mKeyButtonView.setOnClickListener(onClickListener); + } + + @Override + public void setOnHoverListener(View.OnHoverListener onHoverListener) { + mKeyButtonView.setOnHoverListener(onHoverListener); + } + + @Override + public Drawable getImageDrawable() { + return mAnimatedDrawable; + } + + @Override + public void setDarkIntensity(float darkIntensity) { + mKeyButtonView.setDarkIntensity(darkIntensity); + } + + @Override + public void setCanShowRotationButton(boolean canShow) { + mCanShow = canShow; + if (!mCanShow) { + hide(); + } + } + + @Override + public void onTaskbarStateChanged(boolean taskbarVisible, boolean taskbarStashed) { + mIsTaskbarVisible = taskbarVisible; + mIsTaskbarStashed = taskbarStashed; + + if (!mIsShowing) return; + + final Position newPosition = mPositionCalculator + .calculatePosition(mDisplayRotation, mIsTaskbarVisible, mIsTaskbarStashed); + + if (newPosition.getTranslationX() != mPosition.getTranslationX() + || newPosition.getTranslationY() != mPosition.getTranslationY()) { + updateTranslation(newPosition, /* animate */ true); + mPosition = newPosition; + } + } + + /** + * Updates resources that could be changed in runtime, should be called on configuration + * change with changes diff integer mask + * @param configurationChanges - configuration changes with flags from ActivityInfo e.g. + * {@link android.content.pm.ActivityInfo#CONFIG_DENSITY} + */ + public void onConfigurationChanged(@Config int configurationChanges) { + if ((configurationChanges & ActivityInfo.CONFIG_DENSITY) != 0 + || (configurationChanges & ActivityInfo.CONFIG_SCREEN_SIZE) != 0) { + updateDimensionResources(); + + if (mIsShowing) { + final LayoutParams layoutParams = adjustViewPositionAndCreateLayoutParams(); + mWindowManager.updateViewLayout(mKeyButtonContainer, layoutParams); + } + } + + if ((configurationChanges & ActivityInfo.CONFIG_LOCALE) != 0) { + mKeyButtonView.setContentDescription(mContext.getString(mContentDescriptionResource)); + } + } + + private LayoutParams adjustViewPositionAndCreateLayoutParams() { + final LayoutParams lp = new LayoutParams( + mContainerSize, + mContainerSize, + /* xpos */ 0, /* ypos */ 0, LayoutParams.TYPE_NAVIGATION_BAR_PANEL, + LayoutParams.FLAG_NOT_FOCUSABLE, + PixelFormat.TRANSLUCENT); + + lp.privateFlags |= LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS; + lp.setTitle("FloatingRotationButton"); + lp.setFitInsetsTypes(/* types */ 0); + + mDisplayRotation = mWindowManager.getDefaultDisplay().getRotation(); + mPosition = mPositionCalculator + .calculatePosition(mDisplayRotation, mIsTaskbarVisible, mIsTaskbarStashed); + + lp.gravity = mPosition.getGravity(); + ((FrameLayout.LayoutParams) mKeyButtonView.getLayoutParams()).gravity = + mPosition.getGravity(); + + updateTranslation(mPosition, /* animate */ false); + + return lp; + } + + private void updateTranslation(Position position, boolean animate) { + final int translationX = position.getTranslationX(); + final int translationY = position.getTranslationY(); + + if (animate) { + mKeyButtonView + .animate() + .translationX(translationX) + .translationY(translationY) + .setDuration(MARGIN_ANIMATION_DURATION_MILLIS) + .setInterpolator(new AccelerateDecelerateInterpolator()) + .withEndAction(() -> { + if (mUpdatesCallback != null && mIsShowing) { + mUpdatesCallback.onPositionChanged(); + } + }) + .start(); + } else { + mKeyButtonView.setTranslationX(translationX); + mKeyButtonView.setTranslationY(translationY); + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonPositionCalculator.kt b/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonPositionCalculator.kt new file mode 100644 index 0000000000..ec3c073dc6 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonPositionCalculator.kt @@ -0,0 +1,65 @@ +package com.android.systemui.shared.rotation + +import android.view.Gravity +import android.view.Surface + +/** + * Calculates gravity and translation that is necessary to display + * the button in the correct position based on the current state + */ +class FloatingRotationButtonPositionCalculator( + private val defaultMargin: Int, + private val taskbarMarginLeft: Int, + private val taskbarMarginBottom: Int +) { + + fun calculatePosition( + currentRotation: Int, + taskbarVisible: Boolean, + taskbarStashed: Boolean + ): Position { + + val isTaskbarSide = currentRotation == Surface.ROTATION_0 + || currentRotation == Surface.ROTATION_90 + val useTaskbarMargin = isTaskbarSide && taskbarVisible && !taskbarStashed + + val gravity = resolveGravity(currentRotation) + + val marginLeft = if (useTaskbarMargin) taskbarMarginLeft else defaultMargin + val marginBottom = if (useTaskbarMargin) taskbarMarginBottom else defaultMargin + + val translationX = + if (gravity and Gravity.RIGHT == Gravity.RIGHT) { + -marginLeft + } else { + marginLeft + } + val translationY = + if (gravity and Gravity.BOTTOM == Gravity.BOTTOM) { + -marginBottom + } else { + marginBottom + } + + return Position( + gravity = gravity, + translationX = translationX, + translationY = translationY + ) + } + + data class Position( + val gravity: Int, + val translationX: Int, + val translationY: Int + ) + + private fun resolveGravity(rotation: Int): Int = + when (rotation) { + Surface.ROTATION_0 -> Gravity.BOTTOM or Gravity.LEFT + Surface.ROTATION_90 -> Gravity.BOTTOM or Gravity.RIGHT + Surface.ROTATION_180 -> Gravity.TOP or Gravity.RIGHT + Surface.ROTATION_270 -> Gravity.TOP or Gravity.LEFT + else -> throw IllegalArgumentException("Invalid rotation $rotation") + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonView.java b/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonView.java new file mode 100644 index 0000000000..a4b6451caa --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/rotation/FloatingRotationButtonView.java @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2021 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.shared.rotation; + +import android.content.Context; +import android.content.pm.ActivityInfo; +import android.content.res.Configuration; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffColorFilter; +import android.util.AttributeSet; +import android.view.View; +import android.widget.ImageView; + +import androidx.annotation.DimenRes; + +import com.android.systemui.navigationbar.buttons.KeyButtonRipple; + +public class FloatingRotationButtonView extends ImageView { + + private static final float BACKGROUND_ALPHA = 0.92f; + + private KeyButtonRipple mRipple; + private final Paint mOvalBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); + + private final Configuration mLastConfiguration; + + public FloatingRotationButtonView(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public FloatingRotationButtonView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + mLastConfiguration = getResources().getConfiguration(); + + setClickable(true); + + setWillNotDraw(false); + forceHasOverlappingRendering(false); + } + + public void setRipple(@DimenRes int rippleMaxWidthResource) { + mRipple = new KeyButtonRipple(getContext(), this, rippleMaxWidthResource); + setBackground(mRipple); + } + + @Override + protected void onWindowVisibilityChanged(int visibility) { + super.onWindowVisibilityChanged(visibility); + if (visibility != View.VISIBLE) { + jumpDrawablesToCurrentState(); + } + } + + @Override + protected void onConfigurationChanged(Configuration newConfig) { + final int changes = mLastConfiguration.updateFrom(newConfig); + if ((changes & ActivityInfo.CONFIG_SCREEN_SIZE) != 0 + || ((changes & ActivityInfo.CONFIG_DENSITY) != 0)) { + if (mRipple != null) { + mRipple.updateResources(); + } + } + } + + public void setColors(int lightColor, int darkColor) { + getDrawable().setColorFilter(new PorterDuffColorFilter(lightColor, PorterDuff.Mode.SRC_IN)); + + final int ovalBackgroundColor = Color.valueOf(Color.red(darkColor), + Color.green(darkColor), Color.blue(darkColor), BACKGROUND_ALPHA).toArgb(); + + mOvalBgPaint.setColor(ovalBackgroundColor); + mRipple.setType(KeyButtonRipple.Type.OVAL); + } + + public void setDarkIntensity(float darkIntensity) { + mRipple.setDarkIntensity(darkIntensity); + } + + @Override + public void draw(Canvas canvas) { + int d = Math.min(getWidth(), getHeight()); + canvas.drawOval(0, 0, d, d, mOvalBgPaint); + super.draw(canvas); + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/rotation/RotationButton.java b/SystemUIShared/src/com/android/systemui/shared/rotation/RotationButton.java new file mode 100644 index 0000000000..89f71ebf3d --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/rotation/RotationButton.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2021 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.shared.rotation; + +import android.graphics.drawable.Drawable; +import android.view.View; + +/** + * Interface of a rotation button that interacts {@link RotationButtonController}. + * This interface exists because of the two different styles of rotation button in Sysui, + * one in contextual for 3 button nav and a floating rotation button for gestural. + */ +public interface RotationButton { + default void setRotationButtonController(RotationButtonController rotationButtonController) { } + default void setUpdatesCallback(RotationButtonUpdatesCallback updatesCallback) { } + + default View getCurrentView() { + return null; + } + default boolean show() { return false; } + default boolean hide() { return false; } + default boolean isVisible() { + return false; + } + default void setCanShowRotationButton(boolean canShow) {} + default void onTaskbarStateChanged(boolean taskbarVisible, boolean taskbarStashed) {} + default void updateIcon(int lightIconColor, int darkIconColor) { } + default void setOnClickListener(View.OnClickListener onClickListener) { } + default void setOnHoverListener(View.OnHoverListener onHoverListener) { } + default Drawable getImageDrawable() { + return null; + } + default void setDarkIntensity(float darkIntensity) { } + default boolean acceptRotationProposal() { + return getCurrentView() != null; + } + + /** + * Callback for updates provided by a rotation button + */ + interface RotationButtonUpdatesCallback { + default void onVisibilityChanged(boolean isVisible) {}; + default void onPositionChanged() {}; + } +} diff --git a/SystemUIShared/src/com/android/systemui/shared/rotation/RotationButtonController.java b/SystemUIShared/src/com/android/systemui/shared/rotation/RotationButtonController.java new file mode 100644 index 0000000000..605d37628e --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/shared/rotation/RotationButtonController.java @@ -0,0 +1,591 @@ +/* + * Copyright 2021 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.shared.rotation; + +import static android.view.Display.DEFAULT_DISPLAY; + +import static com.android.internal.view.RotationPolicy.NATURAL_ROTATION; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ObjectAnimator; +import android.annotation.ColorInt; +import android.annotation.DrawableRes; +import android.annotation.SuppressLint; +import android.app.StatusBarManager; +import android.content.ContentResolver; +import android.content.Context; +import android.graphics.drawable.AnimatedVectorDrawable; +import android.graphics.drawable.Drawable; +import android.os.Handler; +import android.os.Looper; +import android.os.RemoteException; +import android.provider.Settings; +import android.util.Log; +import android.view.HapticFeedbackConstants; +import android.view.IRotationWatcher; +import android.view.MotionEvent; +import android.view.Surface; +import android.view.View; +import android.view.WindowInsetsController; +import android.view.WindowManagerGlobal; +import android.view.accessibility.AccessibilityManager; +import android.view.animation.Interpolator; +import android.view.animation.LinearInterpolator; + +import com.android.internal.logging.UiEvent; +import com.android.internal.logging.UiEventLogger; +import com.android.internal.logging.UiEventLoggerImpl; +import com.android.internal.view.RotationPolicy; +import com.android.systemui.shared.rotation.RotationButton.RotationButtonUpdatesCallback; +import com.android.systemui.shared.recents.utilities.Utilities; +import com.android.systemui.shared.recents.utilities.ViewRippler; +import com.android.systemui.shared.system.ActivityManagerWrapper; +import com.android.systemui.shared.system.TaskStackChangeListener; +import com.android.systemui.shared.system.TaskStackChangeListeners; + +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Contains logic that deals with showing a rotate suggestion button with animation. + */ +public class RotationButtonController { + + private static final String TAG = "StatusBar/RotationButtonController"; + private static final int BUTTON_FADE_IN_OUT_DURATION_MS = 100; + private static final int NAVBAR_HIDDEN_PENDING_ICON_TIMEOUT_MS = 20000; + private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator(); + + private static final int NUM_ACCEPTED_ROTATION_SUGGESTIONS_FOR_INTRODUCTION = 3; + + private final Context mContext; + private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper()); + private final UiEventLogger mUiEventLogger = new UiEventLoggerImpl(); + private final ViewRippler mViewRippler = new ViewRippler(); + private final Supplier mWindowRotationProvider; + private RotationButton mRotationButton; + + private boolean mIsRecentsAnimationRunning; + private boolean mHomeRotationEnabled; + private int mLastRotationSuggestion; + private boolean mPendingRotationSuggestion; + private boolean mHoveringRotationSuggestion; + private final AccessibilityManager mAccessibilityManager; + private final TaskStackListenerImpl mTaskStackListener; + private Consumer mRotWatcherListener; + + private boolean mListenersRegistered = false; + private boolean mIsNavigationBarShowing; + @SuppressLint("InlinedApi") + private @WindowInsetsController.Behavior + int mBehavior = WindowInsetsController.BEHAVIOR_DEFAULT; + private boolean mSkipOverrideUserLockPrefsOnce; + private final int mLightIconColor; + private final int mDarkIconColor; + + @DrawableRes + private final int mIconCcwStart0ResId; + @DrawableRes + private final int mIconCcwStart90ResId; + @DrawableRes + private final int mIconCwStart0ResId; + @DrawableRes + private final int mIconCwStart90ResId; + + @DrawableRes + private int mIconResId; + + private final Runnable mRemoveRotationProposal = + () -> setRotateSuggestionButtonState(false /* visible */); + private final Runnable mCancelPendingRotationProposal = + () -> mPendingRotationSuggestion = false; + private Animator mRotateHideAnimator; + + + private final IRotationWatcher.Stub mRotationWatcher = new IRotationWatcher.Stub() { + @Override + public void onRotationChanged(final int rotation) { + // We need this to be scheduled as early as possible to beat the redrawing of + // window in response to the orientation change. + mMainThreadHandler.postAtFrontOfQueue(() -> { + // If the screen rotation changes while locked, potentially update lock to flow with + // new screen rotation and hide any showing suggestions. + if (isRotationLocked()) { + if (shouldOverrideUserLockPrefs(rotation)) { + setRotationLockedAtAngle(rotation); + } + setRotateSuggestionButtonState(false /* visible */, true /* forced */); + } + + if (mRotWatcherListener != null) { + mRotWatcherListener.accept(rotation); + } + }); + } + }; + + /** + * Determines if rotation suggestions disabled2 flag exists in flag + * + * @param disable2Flags see if rotation suggestion flag exists in this flag + * @return whether flag exists + */ + public static boolean hasDisable2RotateSuggestionFlag(int disable2Flags) { + return (disable2Flags & StatusBarManager.DISABLE2_ROTATE_SUGGESTIONS) != 0; + } + + public RotationButtonController(Context context, + @ColorInt int lightIconColor, @ColorInt int darkIconColor, + @DrawableRes int iconCcwStart0ResId, + @DrawableRes int iconCcwStart90ResId, + @DrawableRes int iconCwStart0ResId, + @DrawableRes int iconCwStart90ResId, + Supplier windowRotationProvider) { + + mContext = context; + mLightIconColor = lightIconColor; + mDarkIconColor = darkIconColor; + + mIconCcwStart0ResId = iconCcwStart0ResId; + mIconCcwStart90ResId = iconCcwStart90ResId; + mIconCwStart0ResId = iconCwStart0ResId; + mIconCwStart90ResId = iconCwStart90ResId; + mIconResId = mIconCcwStart90ResId; + + mAccessibilityManager = AccessibilityManager.getInstance(context); + mTaskStackListener = new TaskStackListenerImpl(); + mWindowRotationProvider = windowRotationProvider; + } + + public void setRotationButton(RotationButton rotationButton, + RotationButtonUpdatesCallback updatesCallback) { + mRotationButton = rotationButton; + mRotationButton.setRotationButtonController(this); + mRotationButton.setOnClickListener(this::onRotateSuggestionClick); + mRotationButton.setOnHoverListener(this::onRotateSuggestionHover); + mRotationButton.setUpdatesCallback(updatesCallback); + } + + public Context getContext() { + return mContext; + } + + public void init() { + registerListeners(); + if (mContext.getDisplay().getDisplayId() != DEFAULT_DISPLAY) { + // Currently there is no accelerometer sensor on non-default display, disable fixed + // rotation for non-default display + onDisable2FlagChanged(StatusBarManager.DISABLE2_ROTATE_SUGGESTIONS); + } + } + + public void onDestroy() { + unregisterListeners(); + } + + public void registerListeners() { + if (mListenersRegistered) { + return; + } + + mListenersRegistered = true; + try { + WindowManagerGlobal.getWindowManagerService() + .watchRotation(mRotationWatcher, DEFAULT_DISPLAY); + } catch (IllegalArgumentException e) { + mListenersRegistered = false; + Log.w(TAG, "RegisterListeners for the display failed"); + } catch (RemoteException e) { + Log.e(TAG, "RegisterListeners caught a RemoteException", e); + return; + } + + TaskStackChangeListeners.getInstance().registerTaskStackListener(mTaskStackListener); + } + + public void unregisterListeners() { + if (!mListenersRegistered) { + return; + } + + mListenersRegistered = false; + try { + WindowManagerGlobal.getWindowManagerService().removeRotationWatcher(mRotationWatcher); + } catch (RemoteException e) { + Log.e(TAG, "UnregisterListeners caught a RemoteException", e); + return; + } + + TaskStackChangeListeners.getInstance().unregisterTaskStackListener(mTaskStackListener); + } + + public void setRotationCallback(Consumer watcher) { + mRotWatcherListener = watcher; + } + + public void setRotationLockedAtAngle(int rotationSuggestion) { + RotationPolicy.setRotationLockAtAngle(mContext, true, rotationSuggestion); + } + + public boolean isRotationLocked() { + return RotationPolicy.isRotationLocked(mContext); + } + + public void setRotateSuggestionButtonState(boolean visible) { + setRotateSuggestionButtonState(visible, false /* force */); + } + + void setRotateSuggestionButtonState(final boolean visible, final boolean force) { + // At any point the button can become invisible because an a11y service became active. + // Similarly, a call to make the button visible may be rejected because an a11y service is + // active. Must account for this. + // Rerun a show animation to indicate change but don't rerun a hide animation + if (!visible && !mRotationButton.isVisible()) return; + + final View view = mRotationButton.getCurrentView(); + if (view == null) return; + + final Drawable currentDrawable = mRotationButton.getImageDrawable(); + if (currentDrawable == null) return; + + // Clear any pending suggestion flag as it has either been nullified or is being shown + mPendingRotationSuggestion = false; + mMainThreadHandler.removeCallbacks(mCancelPendingRotationProposal); + + // Handle the visibility change and animation + if (visible) { // Appear and change (cannot force) + // Stop and clear any currently running hide animations + if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) { + mRotateHideAnimator.cancel(); + } + mRotateHideAnimator = null; + + // Reset the alpha if any has changed due to hide animation + view.setAlpha(1f); + + // Run the rotate icon's animation if it has one + if (currentDrawable instanceof AnimatedVectorDrawable) { + ((AnimatedVectorDrawable) currentDrawable).reset(); + ((AnimatedVectorDrawable) currentDrawable).start(); + } + + // TODO(b/187754252): No idea why this doesn't work. If we remove the "false" + // we see the animation show the pressed state... but it only shows the first time. + if (!isRotateSuggestionIntroduced()) mViewRippler.start(view); + + // Set visibility unless a11y service is active. + mRotationButton.show(); + } else { // Hide + mViewRippler.stop(); // Prevent any pending ripples, force hide or not + + if (force) { + // If a hide animator is running stop it and make invisible + if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) { + mRotateHideAnimator.pause(); + } + mRotationButton.hide(); + return; + } + + // Don't start any new hide animations if one is running + if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) return; + + ObjectAnimator fadeOut = ObjectAnimator.ofFloat(view, "alpha", 0f); + fadeOut.setDuration(BUTTON_FADE_IN_OUT_DURATION_MS); + fadeOut.setInterpolator(LINEAR_INTERPOLATOR); + fadeOut.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + mRotationButton.hide(); + } + }); + + mRotateHideAnimator = fadeOut; + fadeOut.start(); + } + } + + public void setDarkIntensity(float darkIntensity) { + mRotationButton.setDarkIntensity(darkIntensity); + } + + public void setRecentsAnimationRunning(boolean running) { + mIsRecentsAnimationRunning = running; + updateRotationButtonStateInOverview(); + } + + public void setHomeRotationEnabled(boolean enabled) { + mHomeRotationEnabled = enabled; + updateRotationButtonStateInOverview(); + } + + private void updateRotationButtonStateInOverview() { + if (mIsRecentsAnimationRunning && !mHomeRotationEnabled) { + setRotateSuggestionButtonState(false, true /* hideImmediately */); + } + } + + public void onRotationProposal(int rotation, boolean isValid) { + int windowRotation = mWindowRotationProvider.get(); + + if (!mRotationButton.acceptRotationProposal()) { + return; + } + + if (!mHomeRotationEnabled && mIsRecentsAnimationRunning) { + return; + } + + // This method will be called on rotation suggestion changes even if the proposed rotation + // is not valid for the top app. Use invalid rotation choices as a signal to remove the + // rotate button if shown. + if (!isValid) { + setRotateSuggestionButtonState(false /* visible */); + return; + } + + // If window rotation matches suggested rotation, remove any current suggestions + if (rotation == windowRotation) { + mMainThreadHandler.removeCallbacks(mRemoveRotationProposal); + setRotateSuggestionButtonState(false /* visible */); + return; + } + + // Prepare to show the navbar icon by updating the icon style to change anim params + mLastRotationSuggestion = rotation; // Remember rotation for click + final boolean rotationCCW = Utilities.isRotationAnimationCCW(windowRotation, rotation); + if (windowRotation == Surface.ROTATION_0 || windowRotation == Surface.ROTATION_180) { + mIconResId = rotationCCW ? mIconCcwStart0ResId : mIconCwStart0ResId; + } else { // 90 or 270 + mIconResId = rotationCCW ? mIconCcwStart90ResId : mIconCwStart90ResId; + } + mRotationButton.updateIcon(mLightIconColor, mDarkIconColor); + + if (canShowRotationButton()) { + // The navbar is visible / it's in visual immersive mode, so show the icon right away + showAndLogRotationSuggestion(); + } else { + // If the navbar isn't shown, flag the rotate icon to be shown should the navbar become + // visible given some time limit. + mPendingRotationSuggestion = true; + mMainThreadHandler.removeCallbacks(mCancelPendingRotationProposal); + mMainThreadHandler.postDelayed(mCancelPendingRotationProposal, + NAVBAR_HIDDEN_PENDING_ICON_TIMEOUT_MS); + } + } + + public void onDisable2FlagChanged(int state2) { + final boolean rotateSuggestionsDisabled = hasDisable2RotateSuggestionFlag(state2); + if (rotateSuggestionsDisabled) onRotationSuggestionsDisabled(); + } + + public void onBehaviorChanged(int displayId, @WindowInsetsController.Behavior int behavior) { + if (DEFAULT_DISPLAY != displayId) { + return; + } + + if (mBehavior != behavior) { + mBehavior = behavior; + showPendingRotationButtonIfNeeded(); + } + } + + public void onNavigationBarWindowVisibilityChange(boolean showing) { + if (mIsNavigationBarShowing != showing) { + mIsNavigationBarShowing = showing; + showPendingRotationButtonIfNeeded(); + } + } + + public void onTaskbarStateChange(boolean visible, boolean stashed) { + getRotationButton().onTaskbarStateChanged(visible, stashed); + } + + private void showPendingRotationButtonIfNeeded() { + if (canShowRotationButton() && mPendingRotationSuggestion) { + showAndLogRotationSuggestion(); + } + } + + /** + * Return true when either the task bar is visible or it's in visual immersive mode. + */ + @SuppressLint("InlinedApi") + private boolean canShowRotationButton() { + return mIsNavigationBarShowing || mBehavior == WindowInsetsController.BEHAVIOR_DEFAULT; + } + + @DrawableRes + public int getIconResId() { + return mIconResId; + } + + @ColorInt + public int getLightIconColor() { + return mLightIconColor; + } + + @ColorInt + public int getDarkIconColor() { + return mDarkIconColor; + } + + public RotationButton getRotationButton() { + return mRotationButton; + } + + private void onRotateSuggestionClick(View v) { + mUiEventLogger.log(RotationButtonEvent.ROTATION_SUGGESTION_ACCEPTED); + incrementNumAcceptedRotationSuggestionsIfNeeded(); + setRotationLockedAtAngle(mLastRotationSuggestion); + v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); + } + + private boolean onRotateSuggestionHover(View v, MotionEvent event) { + final int action = event.getActionMasked(); + mHoveringRotationSuggestion = (action == MotionEvent.ACTION_HOVER_ENTER) + || (action == MotionEvent.ACTION_HOVER_MOVE); + rescheduleRotationTimeout(true /* reasonHover */); + return false; // Must return false so a11y hover events are dispatched correctly. + } + + private void onRotationSuggestionsDisabled() { + // Immediately hide the rotate button and clear any planned removal + setRotateSuggestionButtonState(false /* visible */, true /* force */); + mMainThreadHandler.removeCallbacks(mRemoveRotationProposal); + } + + private void showAndLogRotationSuggestion() { + setRotateSuggestionButtonState(true /* visible */); + rescheduleRotationTimeout(false /* reasonHover */); + mUiEventLogger.log(RotationButtonEvent.ROTATION_SUGGESTION_SHOWN); + } + + /** + * Makes {@link #shouldOverrideUserLockPrefs} always return {@code false} once. It is used to + * avoid losing original user rotation when display rotation is changed by entering the fixed + * orientation overview. + */ + public void setSkipOverrideUserLockPrefsOnce() { + // If live-tile is enabled (recents animation keeps running in overview), there is no + // activity switch so the display rotation is not changed, then it is no need to skip. + mSkipOverrideUserLockPrefsOnce = !mIsRecentsAnimationRunning; + } + + private boolean shouldOverrideUserLockPrefs(final int rotation) { + if (mSkipOverrideUserLockPrefsOnce) { + mSkipOverrideUserLockPrefsOnce = false; + return false; + } + // Only override user prefs when returning to the natural rotation (normally portrait). + // Don't let apps that force landscape or 180 alter user lock. + return rotation == NATURAL_ROTATION; + } + + private void rescheduleRotationTimeout(final boolean reasonHover) { + // May be called due to a new rotation proposal or a change in hover state + if (reasonHover) { + // Don't reschedule if a hide animator is running + if (mRotateHideAnimator != null && mRotateHideAnimator.isRunning()) return; + // Don't reschedule if not visible + if (!mRotationButton.isVisible()) return; + } + + // Stop any pending removal + mMainThreadHandler.removeCallbacks(mRemoveRotationProposal); + // Schedule timeout + mMainThreadHandler.postDelayed(mRemoveRotationProposal, + computeRotationProposalTimeout()); + } + + private int computeRotationProposalTimeout() { + return mAccessibilityManager.getRecommendedTimeoutMillis( + mHoveringRotationSuggestion ? 16000 : 5000, + AccessibilityManager.FLAG_CONTENT_CONTROLS); + } + + private boolean isRotateSuggestionIntroduced() { + ContentResolver cr = mContext.getContentResolver(); + return Settings.Secure.getInt(cr, Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED, 0) + >= NUM_ACCEPTED_ROTATION_SUGGESTIONS_FOR_INTRODUCTION; + } + + private void incrementNumAcceptedRotationSuggestionsIfNeeded() { + // Get the number of accepted suggestions + ContentResolver cr = mContext.getContentResolver(); + final int numSuggestions = Settings.Secure.getInt(cr, + Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED, 0); + + // Increment the number of accepted suggestions only if it would change intro mode + if (numSuggestions < NUM_ACCEPTED_ROTATION_SUGGESTIONS_FOR_INTRODUCTION) { + Settings.Secure.putInt(cr, Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED, + numSuggestions + 1); + } + } + + private class TaskStackListenerImpl extends TaskStackChangeListener { + // Invalidate any rotation suggestion on task change or activity orientation change + // Note: all callbacks happen on main thread + + @Override + public void onTaskStackChanged() { + setRotateSuggestionButtonState(false /* visible */); + } + + @Override + public void onTaskRemoved(int taskId) { + setRotateSuggestionButtonState(false /* visible */); + } + + @Override + public void onTaskMovedToFront(int taskId) { + setRotateSuggestionButtonState(false /* visible */); + } + + @Override + public void onActivityRequestedOrientationChanged(int taskId, int requestedOrientation) { + // Only hide the icon if the top task changes its requestedOrientation + // Launcher can alter its requestedOrientation while it's not on top, don't hide on this + Optional.ofNullable(ActivityManagerWrapper.getInstance()) + .map(ActivityManagerWrapper::getRunningTask) + .ifPresent(a -> { + if (a.id == taskId) setRotateSuggestionButtonState(false /* visible */); + }); + } + } + + enum RotationButtonEvent implements UiEventLogger.UiEventEnum { + @UiEvent(doc = "The rotation button was shown") + ROTATION_SUGGESTION_SHOWN(206), + @UiEvent(doc = "The rotation button was clicked") + ROTATION_SUGGESTION_ACCEPTED(207); + + private final int mId; + + RotationButtonEvent(int id) { + mId = id; + } + + @Override + public int getId() { + return mId; + } + } +} + diff --git a/SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java b/SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java index 9164137feb..48fcbbda7e 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java @@ -28,7 +28,6 @@ import android.app.ActivityClient; import android.app.ActivityManager; import android.app.ActivityManager.RecentTaskInfo; import android.app.ActivityManager.RunningTaskInfo; -import android.window.TaskSnapshot; import android.app.ActivityOptions; import android.app.ActivityTaskManager; import android.app.AppGlobals; @@ -50,6 +49,7 @@ import android.util.Log; import android.view.IRecentsAnimationController; import android.view.IRecentsAnimationRunner; import android.view.RemoteAnimationTarget; +import android.window.TaskSnapshot; import com.android.internal.app.IVoiceInteractionManagerService; import com.android.systemui.shared.recents.model.Task; @@ -61,7 +61,7 @@ import java.util.function.Consumer; public class ActivityManagerWrapper { private static final String TAG = "ActivityManagerWrapper"; - + private static final int NUM_RECENT_ACTIVITIES_REQUEST = 3; private static final ActivityManagerWrapper sInstance = new ActivityManagerWrapper(); // Should match the values in PhoneWindowManager @@ -112,6 +112,22 @@ public class ActivityManagerWrapper { return tasks.get(0); } + /** + * We ask for {@link #NUM_RECENT_ACTIVITIES_REQUEST} activities because when in split screen, + * we'll get back 2 activities for each split app and one for launcher. Launcher might be more + * "recently" used than one of the split apps so if we only request 2 tasks, then we might miss + * out on one of the split apps + * + * @return an array of up to {@link #NUM_RECENT_ACTIVITIES_REQUEST} running tasks + * filtering only for tasks that can be visible in the recent tasks list. + */ + public ActivityManager.RunningTaskInfo[] getRunningTasks(boolean filterOnlyVisibleRecents) { + // Note: The set of running tasks from the system is ordered by recency + List tasks = + mAtm.getTasks(NUM_RECENT_ACTIVITIES_REQUEST, filterOnlyVisibleRecents); + return tasks.toArray(new RunningTaskInfo[tasks.size()]); + } + /** * @return a list of the recents tasks. */ @@ -189,14 +205,19 @@ public class ActivityManagerWrapper { } @Override - public void onAnimationCanceled(TaskSnapshot taskSnapshot) { + public void onAnimationCanceled(int[] taskIds, TaskSnapshot[] taskSnapshots) { animationHandler.onAnimationCanceled( - taskSnapshot != null ? new ThumbnailData(taskSnapshot) : null); + ThumbnailData.wrap(taskIds, taskSnapshots)); } @Override - public void onTaskAppeared(RemoteAnimationTarget app) { - animationHandler.onTaskAppeared(new RemoteAnimationTargetCompat(app)); + public void onTasksAppeared(RemoteAnimationTarget[] apps) { + final RemoteAnimationTargetCompat[] compats = + new RemoteAnimationTargetCompat[apps.length]; + for (int i = 0; i < apps.length; ++i) { + compats[i] = new RemoteAnimationTargetCompat(apps[i]); + } + animationHandler.onTasksAppeared(compats); } }; } diff --git a/SystemUIShared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java b/SystemUIShared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java index 32469b841f..f63b8b3099 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/InteractionJankMonitorWrapper.java @@ -71,8 +71,7 @@ public final class InteractionJankMonitorWrapper { public static void begin(View v, @CujType int cujType, long timeout) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return; Configuration.Builder builder = - new Configuration.Builder(cujType) - .setView(v) + Configuration.Builder.withView(cujType, v) .setTimeout(timeout); InteractionJankMonitor.getInstance().begin(builder); } diff --git a/SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java b/SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java index 4580242259..5754a67776 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/QuickStepContract.java @@ -58,6 +58,8 @@ public class QuickStepContract { "extra_shell_starting_window"; // See ISmartspaceTransitionController.aidl public static final String KEY_EXTRA_SMARTSPACE_TRANSITION_CONTROLLER = "smartspace_transition"; + // See IRecentTasks.aidl + public static final String KEY_EXTRA_RECENT_TASKS = "recent_tasks"; public static final String NAV_BAR_MODE_2BUTTON_OVERLAY = WindowManagerPolicyConstants.NAV_BAR_MODE_2BUTTON_OVERLAY; @@ -113,6 +115,14 @@ public class QuickStepContract { public static final int SYSUI_STATE_IME_SHOWING = 1 << 18; // The window magnification is overlapped with system gesture insets at the bottom. public static final int SYSUI_STATE_MAGNIFICATION_OVERLAP = 1 << 19; + // ImeSwitcher is showing + public static final int SYSUI_STATE_IME_SWITCHER_SHOWING = 1 << 20; + // Device dozing/AOD state + public static final int SYSUI_STATE_DEVICE_DOZING = 1 << 21; + // The home feature is disabled (either by SUW/SysUI/device policy) + public static final int SYSUI_STATE_BACK_DISABLED = 1 << 22; + // The bubble stack is expanded AND the mange menu for bubbles is expanded on top of it. + public static final int SYSUI_STATE_BUBBLES_MANAGE_MENU_EXPANDED = 1 << 23; @Retention(RetentionPolicy.SOURCE) @IntDef({SYSUI_STATE_SCREEN_PINNING, @@ -134,7 +144,11 @@ public class QuickStepContract { SYSUI_STATE_ONE_HANDED_ACTIVE, SYSUI_STATE_ALLOW_GESTURE_IGNORING_BAR_VISIBILITY, SYSUI_STATE_IME_SHOWING, - SYSUI_STATE_MAGNIFICATION_OVERLAP + SYSUI_STATE_MAGNIFICATION_OVERLAP, + SYSUI_STATE_IME_SWITCHER_SHOWING, + SYSUI_STATE_DEVICE_DOZING, + SYSUI_STATE_BACK_DISABLED, + SYSUI_STATE_BUBBLES_MANAGE_MENU_EXPANDED }) public @interface SystemUiStateFlags {} @@ -163,6 +177,11 @@ public class QuickStepContract { ? "allow_gesture" : ""); str.add((flags & SYSUI_STATE_IME_SHOWING) != 0 ? "ime_visible" : ""); str.add((flags & SYSUI_STATE_MAGNIFICATION_OVERLAP) != 0 ? "magnification_overlap" : ""); + str.add((flags & SYSUI_STATE_IME_SWITCHER_SHOWING) != 0 ? "ime_switcher_showing" : ""); + str.add((flags & SYSUI_STATE_DEVICE_DOZING) != 0 ? "device_dozing" : ""); + str.add((flags & SYSUI_STATE_BACK_DISABLED) != 0 ? "back_disabled" : ""); + str.add((flags & SYSUI_STATE_BUBBLES_MANAGE_MENU_EXPANDED) != 0 + ? "bubbles_mange_menu_expanded" : ""); return str.toString(); } diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java index 8e65560f7c..13f1db4a08 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationControllerCompat.java @@ -39,12 +39,14 @@ public class RecentsAnimationControllerCompat { public ThumbnailData screenshotTask(int taskId) { try { - TaskSnapshot snapshot = mAnimationController.screenshotTask(taskId); - return snapshot != null ? new ThumbnailData(snapshot) : new ThumbnailData(); + final TaskSnapshot snapshot = mAnimationController.screenshotTask(taskId); + if (snapshot != null) { + return new ThumbnailData(snapshot); + } } catch (RemoteException e) { Log.e(TAG, "Failed to screenshot task", e); - return new ThumbnailData(); } + return new ThumbnailData(); } public void setInputConsumerEnabled(boolean enabled) { diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.java b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.java index c4cd192212..48f1b76c1d 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/RecentsAnimationListener.java @@ -20,6 +20,8 @@ import android.graphics.Rect; import com.android.systemui.shared.recents.model.ThumbnailData; +import java.util.HashMap; + public interface RecentsAnimationListener { /** * Called when the animation into Recents can start. This call is made on the binder thread. @@ -31,11 +33,11 @@ public interface RecentsAnimationListener { /** * Called when the animation into Recents was canceled. This call is made on the binder thread. */ - void onAnimationCanceled(ThumbnailData thumbnailData); + void onAnimationCanceled(HashMap thumbnailDatas); /** * Called when the task of an activity that has been started while the recents animation * was running becomes ready for control. */ - void onTaskAppeared(RemoteAnimationTargetCompat app); + void onTasksAppeared(RemoteAnimationTargetCompat[] app); } diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java index ee55bf0aa8..7729a7532f 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationAdapterCompat.java @@ -26,6 +26,7 @@ import static android.view.WindowManager.TransitionOldType; import static android.window.TransitionInfo.FLAG_IS_WALLPAPER; import android.annotation.SuppressLint; +import android.app.IApplicationThread; import android.os.IBinder; import android.os.RemoteException; import android.util.ArrayMap; @@ -37,9 +38,10 @@ import android.view.RemoteAnimationTarget; import android.view.SurfaceControl; import android.window.IRemoteTransition; import android.window.IRemoteTransitionFinishedCallback; +import android.window.RemoteTransition; import android.window.TransitionInfo; -import java.util.ArrayList; +import com.android.wm.shell.util.CounterRotator; /** * @see RemoteAnimationAdapter @@ -50,10 +52,10 @@ public class RemoteAnimationAdapterCompat { private final RemoteTransitionCompat mRemoteTransition; public RemoteAnimationAdapterCompat(RemoteAnimationRunnerCompat runner, long duration, - long statusBarTransitionDelay) { + long statusBarTransitionDelay, IApplicationThread appThread) { mWrapped = new RemoteAnimationAdapter(wrapRemoteAnimationRunner(runner), duration, statusBarTransitionDelay); - mRemoteTransition = buildRemoteTransition(runner); + mRemoteTransition = buildRemoteTransition(runner, appThread); } RemoteAnimationAdapter getWrapped() { @@ -61,15 +63,18 @@ public class RemoteAnimationAdapterCompat { } /** Helper to just build a remote transition. Use this if the legacy adapter isn't needed. */ - public static RemoteTransitionCompat buildRemoteTransition(RemoteAnimationRunnerCompat runner) { - return new RemoteTransitionCompat(wrapRemoteTransition(runner)); + public static RemoteTransitionCompat buildRemoteTransition(RemoteAnimationRunnerCompat runner, + IApplicationThread appThread) { + return new RemoteTransitionCompat( + new RemoteTransition(wrapRemoteTransition(runner), appThread)); } public RemoteTransitionCompat getRemoteTransition() { return mRemoteTransition; } - private static IRemoteAnimationRunner.Stub wrapRemoteAnimationRunner( + /** Wraps a RemoteAnimationRunnerCompat in an IRemoteAnimationRunner. */ + public static IRemoteAnimationRunner.Stub wrapRemoteAnimationRunner( final RemoteAnimationRunnerCompat remoteAnimationAdapter) { return new IRemoteAnimationRunner.Stub() { @Override @@ -106,52 +111,6 @@ public class RemoteAnimationAdapterCompat { }; } - private static class CounterRotator { - SurfaceControl mSurface = null; - ArrayList mRotateChildren = null; - - void setup(SurfaceControl.Transaction t, SurfaceControl parent, int rotateDelta, - float displayW, float displayH) { - if (rotateDelta == 0) return; - mRotateChildren = new ArrayList<>(); - // We want to counter-rotate, so subtract from 4 - rotateDelta = 4 - (rotateDelta + 4) % 4; - mSurface = new SurfaceControl.Builder() - .setName("Transition Unrotate") - .setContainerLayer() - .setParent(parent) - .build(); - // column-major - if (rotateDelta == 1) { - t.setMatrix(mSurface, 0, 1, -1, 0); - t.setPosition(mSurface, displayW, 0); - } else if (rotateDelta == 2) { - t.setMatrix(mSurface, -1, 0, 0, -1); - t.setPosition(mSurface, displayW, displayH); - } else if (rotateDelta == 3) { - t.setMatrix(mSurface, 0, -1, 1, 0); - t.setPosition(mSurface, 0, displayH); - } - t.show(mSurface); - } - - void addChild(SurfaceControl.Transaction t, SurfaceControl child) { - if (mSurface == null) return; - t.reparent(child, mSurface); - mRotateChildren.add(child); - } - - void cleanUp(SurfaceControl rootLeash) { - if (mSurface == null) return; - SurfaceControl.Transaction t = new SurfaceControl.Transaction(); - for (int i = mRotateChildren.size() - 1; i >= 0; --i) { - t.reparent(mRotateChildren.get(i), rootLeash); - } - t.remove(mSurface); - t.apply(); - } - } - private static IRemoteTransition.Stub wrapRemoteTransition( final RemoteAnimationRunnerCompat remoteAnimationAdapter) { return new IRemoteTransition.Stub() { @@ -201,14 +160,14 @@ public class RemoteAnimationAdapterCompat { if (launcherTask != null && rotateDelta != 0 && launcherTask.getParent() != null) { counterLauncher.setup(t, info.getChange(launcherTask.getParent()).getLeash(), rotateDelta, displayW, displayH); - if (counterLauncher.mSurface != null) { - t.setLayer(counterLauncher.mSurface, launcherLayer); + if (counterLauncher.getSurface() != null) { + t.setLayer(counterLauncher.getSurface(), launcherLayer); } } if (isReturnToHome) { - if (counterLauncher.mSurface != null) { - t.setLayer(counterLauncher.mSurface, info.getChanges().size() * 3); + if (counterLauncher.getSurface() != null) { + t.setLayer(counterLauncher.getSurface(), info.getChanges().size() * 3); } // Need to "boost" the closing things since that's what launcher expects. for (int i = info.getChanges().size() - 1; i >= 0; --i) { @@ -234,8 +193,8 @@ public class RemoteAnimationAdapterCompat { if (wallpaper != null && rotateDelta != 0 && wallpaper.getParent() != null) { counterWallpaper.setup(t, info.getChange(wallpaper.getParent()).getLeash(), rotateDelta, displayW, displayH); - if (counterWallpaper.mSurface != null) { - t.setLayer(counterWallpaper.mSurface, -1); + if (counterWallpaper.getSurface() != null) { + t.setLayer(counterWallpaper.getSurface(), -1); counterWallpaper.addChild(t, leashMap.get(wallpaper.getLeash())); } } @@ -260,7 +219,7 @@ public class RemoteAnimationAdapterCompat { t.remove(leashMap.valueAt(i)); } t.apply(); - finishCallback.onTransitionFinished(null /* wct */); + finishCallback.onTransitionFinished(null /* wct */, null /* sct */); } catch (RemoteException e) { Log.e("ActivityOptionsCompat", "Failed to call app controlled animation" + " finished callback", e); diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java index 2407d216b4..2583e096e3 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java @@ -68,11 +68,16 @@ public class RemoteAnimationTargetCompat { public final boolean isNotInRecents; public final Rect contentInsets; public final ActivityManager.RunningTaskInfo taskInfo; + public final boolean allowEnterPip; public final int rotationChange; public final int windowType; + public final WindowConfiguration windowConfiguration; private final SurfaceControl mStartLeash; + // Fields used only to unrap into RemoteAnimationTarget + private final Rect startBounds; + public RemoteAnimationTargetCompat(RemoteAnimationTarget app) { taskId = app.taskId; mode = app.mode; @@ -88,10 +93,13 @@ public class RemoteAnimationTargetCompat { contentInsets = app.contentInsets; activityType = app.windowConfiguration.getActivityType(); taskInfo = app.taskInfo; + allowEnterPip = app.allowEnterPip; rotationChange = 0; mStartLeash = app.startLeash; windowType = app.windowType; + windowConfiguration = app.windowConfiguration; + startBounds = app.startBounds; } private static int newModeToLegacyMode(int newMode) { @@ -107,6 +115,14 @@ public class RemoteAnimationTargetCompat { } } + public RemoteAnimationTarget unwrap() { + return new RemoteAnimationTarget( + taskId, mode, leash.getSurfaceControl(), isTranslucent, clipRect, contentInsets, + prefixOrderIndex, position, localBounds, screenSpaceBounds, windowConfiguration, + isNotInRecents, mStartLeash, startBounds, taskInfo, allowEnterPip, windowType + ); + } + /** * Almost a copy of Transitions#setupStartState. @@ -214,9 +230,15 @@ public class RemoteAnimationTargetCompat { activityType = ACTIVITY_TYPE_UNDEFINED; } taskInfo = change.getTaskInfo(); + allowEnterPip = change.getAllowEnterPip(); mStartLeash = null; rotationChange = change.getEndRotation() - change.getStartRotation(); windowType = INVALID_WINDOW_TYPE; + + windowConfiguration = change.getTaskInfo() != null + ? change.getTaskInfo().configuration.windowConfiguration + : new WindowConfiguration(); + startBounds = change.getStartAbsBounds(); } public static RemoteAnimationTargetCompat[] wrap(RemoteAnimationTarget[] apps) { @@ -256,7 +278,9 @@ public class RemoteAnimationTargetCompat { * @see SurfaceControl#release() */ public void release() { - leash.mSurfaceControl.release(); + if (leash.mSurfaceControl != null) { + leash.mSurfaceControl.release(); + } if (mStartLeash != null) { mStartLeash.release(); } diff --git a/SystemUIShared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java b/SystemUIShared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java index 653d73020c..954cf9fd81 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java @@ -17,14 +17,21 @@ package com.android.systemui.shared.system; import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME; +import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; import static android.view.WindowManager.TRANSIT_CLOSE; +import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY; import static android.view.WindowManager.TRANSIT_OPEN; import static android.view.WindowManager.TRANSIT_TO_BACK; import static android.view.WindowManager.TRANSIT_TO_FRONT; +import static android.window.TransitionFilter.CONTAINER_ORDER_TOP; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SuppressLint; +import android.app.ActivityManager; +import android.app.ActivityTaskManager; +import android.app.IApplicationThread; +import android.content.ComponentName; import android.graphics.Rect; import android.os.IBinder; import android.os.Parcelable; @@ -36,6 +43,7 @@ import android.view.SurfaceControl; import android.window.IRemoteTransition; import android.window.IRemoteTransitionFinishedCallback; import android.window.PictureInPictureSurfaceTransaction; +import android.window.RemoteTransition; import android.window.TransitionFilter; import android.window.TransitionInfo; import android.window.WindowContainerToken; @@ -45,6 +53,7 @@ import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.DataClass; import com.android.systemui.shared.recents.model.ThumbnailData; +import java.util.ArrayList; import java.util.concurrent.Executor; /** @@ -57,23 +66,23 @@ import java.util.concurrent.Executor; public class RemoteTransitionCompat implements Parcelable { private static final String TAG = "RemoteTransitionCompat"; - @NonNull final IRemoteTransition mTransition; + @NonNull final RemoteTransition mTransition; @Nullable TransitionFilter mFilter = null; - RemoteTransitionCompat(IRemoteTransition transition) { + RemoteTransitionCompat(RemoteTransition transition) { mTransition = transition; } public RemoteTransitionCompat(@NonNull RemoteTransitionRunner runner, - @NonNull Executor executor) { - mTransition = new IRemoteTransition.Stub() { + @NonNull Executor executor, @Nullable IApplicationThread appThread) { + IRemoteTransition remote = new IRemoteTransition.Stub() { @Override public void startAnimation(IBinder transition, TransitionInfo info, SurfaceControl.Transaction t, IRemoteTransitionFinishedCallback finishedCallback) { final Runnable finishAdapter = () -> { try { - finishedCallback.onTransitionFinished(null /* wct */); + finishedCallback.onTransitionFinished(null /* wct */, null /* sct */); } catch (RemoteException e) { Log.e(TAG, "Failed to call transition finished callback", e); } @@ -87,7 +96,7 @@ public class RemoteTransitionCompat implements Parcelable { IRemoteTransitionFinishedCallback finishedCallback) { final Runnable finishAdapter = () -> { try { - finishedCallback.onTransitionFinished(null /* wct */); + finishedCallback.onTransitionFinished(null /* wct */, null /* sct */); } catch (RemoteException e) { Log.e(TAG, "Failed to call transition finished callback", e); } @@ -96,12 +105,13 @@ public class RemoteTransitionCompat implements Parcelable { finishAdapter)); } }; + mTransition = new RemoteTransition(remote, appThread); } /** Constructor specifically for recents animation */ public RemoteTransitionCompat(RecentsAnimationListener recents, - RecentsAnimationControllerCompat controller) { - mTransition = new IRemoteTransition.Stub() { + RecentsAnimationControllerCompat controller, IApplicationThread appThread) { + IRemoteTransition remote = new IRemoteTransition.Stub() { final RecentsControllerWrap mRecentsSession = new RecentsControllerWrap(); IBinder mToken = null; @@ -118,14 +128,22 @@ public class RemoteTransitionCompat implements Parcelable { mToken = transition; // This transition is for opening recents, so recents is on-top. We want to draw // the current going-away task on top of recents, though, so move it to front - WindowContainerToken pausingTask = null; + final ArrayList pausingTasks = new ArrayList<>(); + WindowContainerToken pipTask = null; for (int i = info.getChanges().size() - 1; i >= 0; --i) { final TransitionInfo.Change change = info.getChanges().get(i); if (change.getMode() == TRANSIT_CLOSE || change.getMode() == TRANSIT_TO_BACK) { t.setLayer(leashMap.get(change.getLeash()), info.getChanges().size() * 3 - i); - if (change.getTaskInfo() != null) { - pausingTask = change.getTaskInfo().token; + final ActivityManager.RunningTaskInfo taskInfo = change.getTaskInfo(); + if (taskInfo == null) { + continue; + } + // Add to front since we are iterating backwards. + pausingTasks.add(0, taskInfo.token); + if (taskInfo.pictureInPictureParams != null + && taskInfo.pictureInPictureParams.isAutoEnterEnabled()) { + pipTask = taskInfo.token; } } } @@ -134,8 +152,8 @@ public class RemoteTransitionCompat implements Parcelable { t.setAlpha(wallpapers[i].leash.mSurfaceControl, 1); } t.apply(); - mRecentsSession.setup(controller, info, finishedCallback, pausingTask, - leashMap); + mRecentsSession.setup(controller, info, finishedCallback, pausingTasks, pipTask, + leashMap, mToken); recents.onAnimationStart(mRecentsSession, apps, wallpapers, new Rect(0, 0, 0, 0), new Rect()); } @@ -147,23 +165,31 @@ public class RemoteTransitionCompat implements Parcelable { if (!mergeTarget.equals(mToken)) return; if (!mRecentsSession.merge(info, t, recents)) return; try { - finishedCallback.onTransitionFinished(null /* wct */); + finishedCallback.onTransitionFinished(null /* wct */, null /* sct */); } catch (RemoteException e) { Log.e(TAG, "Error merging transition.", e); } } }; + mTransition = new RemoteTransition(remote, appThread); } /** Adds a filter check that restricts this remote transition to home open transitions. */ - public void addHomeOpenCheck() { + public void addHomeOpenCheck(ComponentName homeActivity) { if (mFilter == null) { mFilter = new TransitionFilter(); } + // No need to handle the transition that also dismisses keyguard. + mFilter.mNotFlags = TRANSIT_FLAG_KEYGUARD_GOING_AWAY; mFilter.mRequirements = - new TransitionFilter.Requirement[]{new TransitionFilter.Requirement()}; + new TransitionFilter.Requirement[]{new TransitionFilter.Requirement(), + new TransitionFilter.Requirement()}; mFilter.mRequirements[0].mActivityType = ACTIVITY_TYPE_HOME; + mFilter.mRequirements[0].mTopActivity = homeActivity; mFilter.mRequirements[0].mModes = new int[]{TRANSIT_OPEN, TRANSIT_TO_FRONT}; + mFilter.mRequirements[0].mOrder = CONTAINER_ORDER_TOP; + mFilter.mRequirements[1].mActivityType = ACTIVITY_TYPE_STANDARD; + mFilter.mRequirements[1].mModes = new int[]{TRANSIT_CLOSE, TRANSIT_TO_BACK}; } /** @@ -174,14 +200,18 @@ public class RemoteTransitionCompat implements Parcelable { static class RecentsControllerWrap extends RecentsAnimationControllerCompat { private RecentsAnimationControllerCompat mWrapped = null; private IRemoteTransitionFinishedCallback mFinishCB = null; - private WindowContainerToken mPausingTask = null; + private ArrayList mPausingTasks = null; + private WindowContainerToken mPipTask = null; private TransitionInfo mInfo = null; - private SurfaceControl mOpeningLeash = null; + private ArrayList mOpeningLeashes = null; private ArrayMap mLeashMap = null; + private PictureInPictureSurfaceTransaction mPipTransaction = null; + private IBinder mTransition = null; void setup(RecentsAnimationControllerCompat wrapped, TransitionInfo info, - IRemoteTransitionFinishedCallback finishCB, WindowContainerToken pausingTask, - ArrayMap leashMap) { + IRemoteTransitionFinishedCallback finishCB, + ArrayList pausingTasks, WindowContainerToken pipTask, + ArrayMap leashMap, IBinder transition) { if (mInfo != null) { throw new IllegalStateException("Trying to run a new recents animation while" + " recents is already active."); @@ -189,43 +219,66 @@ public class RemoteTransitionCompat implements Parcelable { mWrapped = wrapped; mInfo = info; mFinishCB = finishCB; - mPausingTask = pausingTask; + mPausingTasks = pausingTasks; + mPipTask = pipTask; mLeashMap = leashMap; + mTransition = transition; } @SuppressLint("NewApi") boolean merge(TransitionInfo info, SurfaceControl.Transaction t, RecentsAnimationListener recents) { - TransitionInfo.Change openingTask = null; + ArrayList openingTasks = null; for (int i = info.getChanges().size() - 1; i >= 0; --i) { final TransitionInfo.Change change = info.getChanges().get(i); if (change.getMode() == TRANSIT_OPEN || change.getMode() == TRANSIT_TO_FRONT) { if (change.getTaskInfo() != null) { - if (openingTask != null) { - Log.w(TAG, " Expecting to merge a task-open, but got >1 opening " - + "tasks"); + if (openingTasks == null) { + openingTasks = new ArrayList<>(); } - openingTask = change; + openingTasks.add(change); } } } - if (openingTask == null) return false; - mOpeningLeash = openingTask.getLeash(); - if (openingTask.getContainer().equals(mPausingTask)) { - // In this case, we are "returning" to the already running app, so just consume + if (openingTasks == null) return false; + int pauseMatches = 0; + for (int i = 0; i < openingTasks.size(); ++i) { + if (mPausingTasks.contains(openingTasks.get(i).getContainer())) { + ++pauseMatches; + } + if (openingTasks.get(i).getContainer().equals(mPausingTasks.get(i))) { + // In this case, we are "returning" to an already running app, so just consume + // the merge and do nothing. + } + } + if (pauseMatches > 0) { + if (pauseMatches != mPausingTasks.size()) { + // We are not really "returning" properly... something went wrong. + throw new IllegalStateException("\"Concelling\" a recents transitions by " + + "unpausing " + pauseMatches + " apps after pausing " + + mPausingTasks.size() + " apps."); + } + // In this case, we are "returning" to an already running app, so just consume // the merge and do nothing. return true; } - // We are receiving a new opening task, so convert to onTaskAppeared. final int layer = mInfo.getChanges().size() * 3; - final RemoteAnimationTargetCompat target = new RemoteAnimationTargetCompat( - openingTask, layer, mInfo, t); - mLeashMap.put(mOpeningLeash, target.leash.mSurfaceControl); - t.reparent(target.leash.mSurfaceControl, mInfo.getRootLeash()); - t.setLayer(target.leash.mSurfaceControl, layer); - t.hide(target.leash.mSurfaceControl); - t.apply(); - recents.onTaskAppeared(target); + mOpeningLeashes = new ArrayList<>(); + final RemoteAnimationTargetCompat[] targets = + new RemoteAnimationTargetCompat[openingTasks.size()]; + for (int i = 0; i < openingTasks.size(); ++i) { + mOpeningLeashes.add(openingTasks.get(i).getLeash()); + // We are receiving new opening tasks, so convert to onTasksAppeared. + final RemoteAnimationTargetCompat target = new RemoteAnimationTargetCompat( + openingTasks.get(i), layer, mInfo, t); + mLeashMap.put(mOpeningLeashes.get(i), target.leash.mSurfaceControl); + t.reparent(target.leash.mSurfaceControl, mInfo.getRootLeash()); + t.setLayer(target.leash.mSurfaceControl, layer); + t.hide(target.leash.mSurfaceControl); + t.apply(); + targets[i] = target; + } + recents.onTasksAppeared(targets); return true; } @@ -247,6 +300,7 @@ public class RemoteTransitionCompat implements Parcelable { @Override public void setFinishTaskTransaction(int taskId, PictureInPictureSurfaceTransaction finishTransaction, SurfaceControl overlay) { + mPipTransaction = finishTransaction; if (mWrapped != null) { mWrapped.setFinishTaskTransaction(taskId, finishTransaction, overlay); } @@ -261,21 +315,40 @@ public class RemoteTransitionCompat implements Parcelable { } if (mWrapped != null) mWrapped.finish(toHome, sendUserLeaveHint); try { - if (!toHome && mPausingTask != null && mOpeningLeash == null) { + if (!toHome && mPausingTasks != null && mOpeningLeashes == null) { // The gesture went back to opening the app rather than continuing with - // recents, so end the transition by moving the app back to the top. + // recents, so end the transition by moving the app back to the top (and also + // re-showing it's task). final WindowContainerTransaction wct = new WindowContainerTransaction(); - wct.reorder(mPausingTask, true /* onTop */); - mFinishCB.onTransitionFinished(wct); + final SurfaceControl.Transaction t = new SurfaceControl.Transaction(); + for (int i = mPausingTasks.size() - 1; i >= 0; ++i) { + // reverse order so that index 0 ends up on top + wct.reorder(mPausingTasks.get(i), true /* onTop */); + t.show(mInfo.getChange(mPausingTasks.get(i)).getLeash()); + } + mFinishCB.onTransitionFinished(wct, t); } else { - if (mOpeningLeash != null) { + if (mOpeningLeashes != null) { // TODO: the launcher animation should handle this final SurfaceControl.Transaction t = new SurfaceControl.Transaction(); - t.show(mOpeningLeash); - t.setAlpha(mOpeningLeash, 1.f); + for (int i = 0; i < mOpeningLeashes.size(); ++i) { + t.show(mOpeningLeashes.get(i)); + t.setAlpha(mOpeningLeashes.get(i), 1.f); + } t.apply(); } - mFinishCB.onTransitionFinished(null /* wct */); + if (mPipTask != null && mPipTransaction != null) { + final SurfaceControl.Transaction t = new SurfaceControl.Transaction(); + t.show(mInfo.getChange(mPipTask).getLeash()); + PictureInPictureSurfaceTransaction.apply(mPipTransaction, + mInfo.getChange(mPipTask).getLeash(), t); + mPipTask = null; + mPipTransaction = null; + mFinishCB.onTransitionFinished(null /* wct */, t); + } else { + mFinishCB.onTransitionFinished(null /* wct */, null /* sct */); + } + } } catch (RemoteException e) { Log.e("RemoteTransitionCompat", "Failed to call animation finish callback", e); @@ -294,10 +367,11 @@ public class RemoteTransitionCompat implements Parcelable { // Reset all members. mWrapped = null; mFinishCB = null; - mPausingTask = null; + mPausingTasks = null; mInfo = null; - mOpeningLeash = null; + mOpeningLeashes = null; mLeashMap = null; + mTransition = null; } @Override public void setDeferCancelUntilNextTransition(boolean defer, boolean screenshot) { @@ -318,11 +392,28 @@ public class RemoteTransitionCompat implements Parcelable { @Override public boolean removeTask(int taskId) { return mWrapped != null ? mWrapped.removeTask(taskId) : false; } + + /** + * @see IRecentsAnimationController#detachNavigationBarFromApp + */ + @Override public void detachNavigationBarFromApp(boolean moveHomeToTop) { + try { + ActivityTaskManager.getService().detachNavigationBarFromApp(mTransition); + } catch (RemoteException e) { + Log.e(TAG, "Failed to detach the navigation bar from app", e); + } + } + + /** + * @see IRecentsAnimationController#animateNavigationBarToApp(long) + */ + @Override public void animateNavigationBarToApp(long duration) { + } } - // Code below generated by codegen v1.0.21. + // Code below generated by codegen v1.0.23. // // DO NOT MODIFY! // CHECKSTYLE:OFF Generated code @@ -334,8 +425,21 @@ public class RemoteTransitionCompat implements Parcelable { // Settings > Editor > Code Style > Formatter Control //@formatter:off + @DataClass.Generated.Member - public @NonNull IRemoteTransition getTransition() { + /* package-private */ RemoteTransitionCompat( + @NonNull RemoteTransition transition, + @Nullable TransitionFilter filter) { + this.mTransition = transition; + com.android.internal.util.AnnotationValidations.validate( + NonNull.class, null, mTransition); + this.mFilter = filter; + + // onConstructed(); // You can define this method to get a callback + } + + @DataClass.Generated.Member + public @NonNull RemoteTransition getTransition() { return mTransition; } @@ -353,7 +457,7 @@ public class RemoteTransitionCompat implements Parcelable { byte flg = 0; if (mFilter != null) flg |= 0x2; dest.writeByte(flg); - dest.writeStrongInterface(mTransition); + dest.writeTypedObject(mTransition, flags); if (mFilter != null) dest.writeTypedObject(mFilter, flags); } @@ -369,7 +473,7 @@ public class RemoteTransitionCompat implements Parcelable { // static FieldType unparcelFieldName(Parcel in) { ... } byte flg = in.readByte(); - IRemoteTransition transition = IRemoteTransition.Stub.asInterface(in.readStrongBinder()); + RemoteTransition transition = (RemoteTransition) in.readTypedObject(RemoteTransition.CREATOR); TransitionFilter filter = (flg & 0x2) == 0 ? null : (TransitionFilter) in.readTypedObject(TransitionFilter.CREATOR); this.mTransition = transition; @@ -401,20 +505,20 @@ public class RemoteTransitionCompat implements Parcelable { @DataClass.Generated.Member public static class Builder { - private @NonNull IRemoteTransition mTransition; + private @NonNull RemoteTransition mTransition; private @Nullable TransitionFilter mFilter; private long mBuilderFieldsSet = 0L; public Builder( - @NonNull IRemoteTransition transition) { + @NonNull RemoteTransition transition) { mTransition = transition; com.android.internal.util.AnnotationValidations.validate( NonNull.class, null, mTransition); } @DataClass.Generated.Member - public @NonNull Builder setTransition(@NonNull IRemoteTransition value) { + public @NonNull Builder setTransition(@NonNull RemoteTransition value) { checkNotUsed(); mBuilderFieldsSet |= 0x1; mTransition = value; @@ -437,8 +541,9 @@ public class RemoteTransitionCompat implements Parcelable { if ((mBuilderFieldsSet & 0x2) == 0) { mFilter = null; } - RemoteTransitionCompat o = new RemoteTransitionCompat(mTransition); - o.mFilter = this.mFilter; + RemoteTransitionCompat o = new RemoteTransitionCompat( + mTransition, + mFilter); return o; } @@ -451,10 +556,10 @@ public class RemoteTransitionCompat implements Parcelable { } @DataClass.Generated( - time = 1606862689344L, - codegenVersion = "1.0.21", + time = 1629321609807L, + codegenVersion = "1.0.23", sourceFile = "frameworks/base/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java", - inputSignatures = "final @android.annotation.NonNull com.android.systemui.shared.system.IRemoteTransition mTransition\n @android.annotation.Nullable android.window.TransitionFilter mFilter\npublic void addHomeOpenCheck()\nclass RemoteTransitionCompat extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass") + inputSignatures = "private static final java.lang.String TAG\nfinal @android.annotation.NonNull android.window.RemoteTransition mTransition\n @android.annotation.Nullable android.window.TransitionFilter mFilter\npublic void addHomeOpenCheck(android.content.ComponentName)\nclass RemoteTransitionCompat extends java.lang.Object implements [android.os.Parcelable]\nprivate com.android.systemui.shared.system.RecentsAnimationControllerCompat mWrapped\nprivate android.window.IRemoteTransitionFinishedCallback mFinishCB\nprivate android.window.WindowContainerToken mPausingTask\nprivate android.window.WindowContainerToken mPipTask\nprivate android.window.TransitionInfo mInfo\nprivate android.view.SurfaceControl mOpeningLeash\nprivate android.util.ArrayMap mLeashMap\nprivate android.window.PictureInPictureSurfaceTransaction mPipTransaction\nprivate android.os.IBinder mTransition\n void setup(com.android.systemui.shared.system.RecentsAnimationControllerCompat,android.window.TransitionInfo,android.window.IRemoteTransitionFinishedCallback,android.window.WindowContainerToken,android.window.WindowContainerToken,android.util.ArrayMap,android.os.IBinder)\n @android.annotation.SuppressLint boolean merge(android.window.TransitionInfo,android.view.SurfaceControl.Transaction,com.android.systemui.shared.system.RecentsAnimationListener)\npublic @java.lang.Override com.android.systemui.shared.recents.model.ThumbnailData screenshotTask(int)\npublic @java.lang.Override void setInputConsumerEnabled(boolean)\npublic @java.lang.Override void setAnimationTargetsBehindSystemBars(boolean)\npublic @java.lang.Override void hideCurrentInputMethod()\npublic @java.lang.Override void setFinishTaskTransaction(int,android.window.PictureInPictureSurfaceTransaction,android.view.SurfaceControl)\npublic @java.lang.Override @android.annotation.SuppressLint void finish(boolean,boolean)\npublic @java.lang.Override void setDeferCancelUntilNextTransition(boolean,boolean)\npublic @java.lang.Override void cleanupScreenshot()\npublic @java.lang.Override void setWillFinishToHome(boolean)\npublic @java.lang.Override boolean removeTask(int)\npublic @java.lang.Override void detachNavigationBarFromApp(boolean)\npublic @java.lang.Override void animateNavigationBarToApp(long)\nclass RecentsControllerWrap extends com.android.systemui.shared.system.RecentsAnimationControllerCompat implements []\n@com.android.internal.util.DataClass") @Deprecated private void __metadata() {} diff --git a/SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java b/SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java index b38270cb86..85d5de0ea4 100644 --- a/SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java +++ b/SystemUIShared/src/com/android/systemui/shared/system/WindowManagerWrapper.java @@ -27,10 +27,12 @@ import android.graphics.Rect; import android.os.Handler; import android.os.RemoteException; import android.util.Log; +import android.view.InsetsController; import android.view.InsetsState; import android.view.SurfaceControl; import android.view.WindowManager; import android.view.WindowManagerGlobal; +import android.view.animation.Interpolator; import com.android.systemui.shared.recents.view.AppTransitionAnimationSpecsFuture; import com.android.systemui.shared.recents.view.RecentsTransition; @@ -89,6 +91,9 @@ public class WindowManagerWrapper { public static final int ITYPE_BOTTOM_TAPPABLE_ELEMENT = InsetsState.ITYPE_BOTTOM_TAPPABLE_ELEMENT; + public static final int ANIMATION_DURATION_RESIZE = InsetsController.ANIMATION_DURATION_RESIZE; + public static final Interpolator RESIZE_INTERPOLATOR = InsetsController.RESIZE_INTERPOLATOR; + private static final WindowManagerWrapper sInstance = new WindowManagerWrapper(); public static WindowManagerWrapper getInstance() { diff --git a/SystemUIShared/src/com/android/systemui/statusbar/policy/CallbackController.java b/SystemUIShared/src/com/android/systemui/statusbar/policy/CallbackController.java new file mode 100644 index 0000000000..047ff75468 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/statusbar/policy/CallbackController.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2016 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.policy; + +import androidx.annotation.NonNull; +import androidx.lifecycle.Lifecycle; +import androidx.lifecycle.Lifecycle.Event; +import androidx.lifecycle.LifecycleEventObserver; +import androidx.lifecycle.LifecycleOwner; + +public interface CallbackController { + + /** Add a callback */ + void addCallback(@NonNull T listener); + + /** Remove a callback */ + void removeCallback(@NonNull T listener); + + /** + * Wrapper to {@link #addCallback(Object)} when a lifecycle is in the resumed state + * and {@link #removeCallback(Object)} when not resumed automatically. + */ + default T observe(LifecycleOwner owner, T listener) { + return observe(owner.getLifecycle(), listener); + } + + /** + * Wrapper to {@link #addCallback(Object)} when a lifecycle is in the resumed state + * and {@link #removeCallback(Object)} when not resumed automatically. + */ + default T observe(Lifecycle lifecycle, T listener) { + lifecycle.addObserver((LifecycleEventObserver) (lifecycleOwner, event) -> { + if (event == Event.ON_RESUME) { + addCallback(listener); + } else if (event == Event.ON_PAUSE) { + removeCallback(listener); + } + }); + return listener; + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt b/SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt new file mode 100644 index 0000000000..ea93a3b937 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionFactory.kt @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2021 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. + */ +@file:JvmName("UnfoldTransitionFactory") + +package com.android.systemui.unfold + +import android.content.Context +import android.hardware.SensorManager +import android.hardware.devicestate.DeviceStateManager +import android.os.Handler +import com.android.systemui.unfold.updates.screen.ScreenStatusProvider +import com.android.systemui.unfold.config.ResourceUnfoldTransitionConfig +import com.android.systemui.unfold.config.UnfoldTransitionConfig +import com.android.systemui.unfold.progress.FixedTimingTransitionProgressProvider +import com.android.systemui.unfold.progress.PhysicsBasedUnfoldTransitionProgressProvider +import com.android.systemui.unfold.util.ScaleAwareTransitionProgressProvider +import com.android.systemui.unfold.updates.DeviceFoldStateProvider +import com.android.systemui.unfold.updates.hinge.EmptyHingeAngleProvider +import com.android.systemui.unfold.updates.hinge.HingeSensorAngleProvider +import java.lang.IllegalStateException +import java.util.concurrent.Executor + +fun createUnfoldTransitionProgressProvider( + context: Context, + config: UnfoldTransitionConfig, + screenStatusProvider: ScreenStatusProvider, + deviceStateManager: DeviceStateManager, + sensorManager: SensorManager, + mainHandler: Handler, + mainExecutor: Executor +): UnfoldTransitionProgressProvider { + + if (!config.isEnabled) { + throw IllegalStateException("Trying to create " + + "UnfoldTransitionProgressProvider when the transition is disabled") + } + + val hingeAngleProvider = + if (config.isHingeAngleEnabled) { + HingeSensorAngleProvider(sensorManager) + } else { + EmptyHingeAngleProvider() + } + + val foldStateProvider = DeviceFoldStateProvider( + context, + hingeAngleProvider, + screenStatusProvider, + deviceStateManager, + mainExecutor, + mainHandler + ) + + val unfoldTransitionProgressProvider = if (config.isHingeAngleEnabled) { + PhysicsBasedUnfoldTransitionProgressProvider(foldStateProvider) + } else { + FixedTimingTransitionProgressProvider(foldStateProvider) + } + return ScaleAwareTransitionProgressProvider( + unfoldTransitionProgressProvider, + context.contentResolver + ) +} + +fun createConfig(context: Context): UnfoldTransitionConfig = + ResourceUnfoldTransitionConfig(context) diff --git a/SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt new file mode 100644 index 0000000000..e17f43e64b --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2021 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.unfold + +import android.annotation.FloatRange +import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener +import com.android.systemui.statusbar.policy.CallbackController + +/** + * Interface that allows to receive unfold transition progress updates. + * It can be used to update view properties based on the current animation progress. + * onTransitionProgress callback could be called on each frame. + * + * Use [createUnfoldTransitionProgressProvider] to create instances of this interface + */ +interface UnfoldTransitionProgressProvider : CallbackController { + + fun destroy() + + interface TransitionProgressListener { + fun onTransitionStarted() {} + fun onTransitionFinished() {} + fun onTransitionProgress(@FloatRange(from = 0.0, to = 1.0) progress: Float) {} + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt b/SystemUIShared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt new file mode 100644 index 0000000000..3f027e30b4 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/config/ResourceUnfoldTransitionConfig.kt @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2021 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.unfold.config + +import android.content.Context +import android.os.SystemProperties + +internal class ResourceUnfoldTransitionConfig( + private val context: Context +) : UnfoldTransitionConfig { + + override val isEnabled: Boolean + get() = readIsEnabledResource() && isPropertyEnabled + + override val isHingeAngleEnabled: Boolean + get() = readIsHingeAngleEnabled() + + private val isPropertyEnabled: Boolean + get() = SystemProperties.getInt(UNFOLD_TRANSITION_MODE_PROPERTY_NAME, + UNFOLD_TRANSITION_PROPERTY_ENABLED) == UNFOLD_TRANSITION_PROPERTY_ENABLED + + private fun readIsEnabledResource(): Boolean = context.resources + .getBoolean(com.android.internal.R.bool.config_unfoldTransitionEnabled) + + private fun readIsHingeAngleEnabled(): Boolean = context.resources + .getBoolean(com.android.internal.R.bool.config_unfoldTransitionHingeAngle) +} + +/** + * Temporary persistent property to control unfold transition mode + * See [com.android.unfold.config.AnimationMode] + */ +private const val UNFOLD_TRANSITION_MODE_PROPERTY_NAME = "persist.unfold.transition_enabled" +private const val UNFOLD_TRANSITION_PROPERTY_ENABLED = 1 diff --git a/SystemUIShared/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt b/SystemUIShared/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt new file mode 100644 index 0000000000..5b187b3486 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/config/UnfoldTransitionConfig.kt @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 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.unfold.config + +interface UnfoldTransitionConfig { + val isEnabled: Boolean + val isHingeAngleEnabled: Boolean +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt new file mode 100644 index 0000000000..732882e990 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2021 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.unfold.progress + +import android.animation.Animator +import android.animation.ObjectAnimator +import android.util.FloatProperty +import com.android.systemui.unfold.UnfoldTransitionProgressProvider +import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener +import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_CLOSED +import com.android.systemui.unfold.updates.FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE +import com.android.systemui.unfold.updates.FoldStateProvider +import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate + +/** + * Emits animation progress with fixed timing after unfolding + */ +internal class FixedTimingTransitionProgressProvider( + private val foldStateProvider: FoldStateProvider +) : UnfoldTransitionProgressProvider, FoldStateProvider.FoldUpdatesListener { + + private val animatorListener = AnimatorListener() + private val animator = + ObjectAnimator.ofFloat(this, AnimationProgressProperty, 0f, 1f) + .apply { + duration = TRANSITION_TIME_MILLIS + addListener(animatorListener) + } + + + private var transitionProgress: Float = 0.0f + set(value) { + listeners.forEach { it.onTransitionProgress(value) } + field = value + } + + private val listeners: MutableList = mutableListOf() + + init { + foldStateProvider.addCallback(this) + foldStateProvider.start() + } + + override fun destroy() { + animator.cancel() + foldStateProvider.removeCallback(this) + foldStateProvider.stop() + } + + override fun onFoldUpdate(@FoldUpdate update: Int) { + when (update) { + FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE -> + animator.start() + FOLD_UPDATE_FINISH_CLOSED -> + animator.cancel() + } + } + + override fun addCallback(listener: TransitionProgressListener) { + listeners.add(listener) + } + + override fun removeCallback(listener: TransitionProgressListener) { + listeners.remove(listener) + } + + override fun onHingeAngleUpdate(angle: Float) { + } + + private object AnimationProgressProperty : + FloatProperty("animation_progress") { + + override fun setValue( + provider: FixedTimingTransitionProgressProvider, + value: Float + ) { + provider.transitionProgress = value + } + + override fun get(provider: FixedTimingTransitionProgressProvider): Float = + provider.transitionProgress + } + + private inner class AnimatorListener : Animator.AnimatorListener { + + override fun onAnimationStart(animator: Animator) { + listeners.forEach { it.onTransitionStarted() } + } + + override fun onAnimationEnd(animator: Animator) { + listeners.forEach { it.onTransitionFinished() } + } + + override fun onAnimationRepeat(animator: Animator) { + } + + override fun onAnimationCancel(animator: Animator) { + } + } + + private companion object { + private const val TRANSITION_TIME_MILLIS = 400L + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt new file mode 100644 index 0000000000..51eae573f0 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt @@ -0,0 +1,207 @@ +/* + * Copyright (C) 2021 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.unfold.progress + +import android.util.Log +import android.util.MathUtils.saturate +import androidx.dynamicanimation.animation.DynamicAnimation +import androidx.dynamicanimation.animation.FloatPropertyCompat +import androidx.dynamicanimation.animation.SpringAnimation +import androidx.dynamicanimation.animation.SpringForce +import com.android.systemui.unfold.UnfoldTransitionProgressProvider +import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener +import com.android.systemui.unfold.updates.FOLD_UPDATE_ABORTED +import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_CLOSED +import com.android.systemui.unfold.updates.FOLD_UPDATE_START_CLOSING +import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_FULL_OPEN +import com.android.systemui.unfold.updates.FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE +import com.android.systemui.unfold.updates.FoldStateProvider +import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate +import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener + +/** + * Maps fold updates to unfold transition progress using DynamicAnimation. + * + * TODO(b/193793338) Current limitations: + * - doesn't handle postures + */ +internal class PhysicsBasedUnfoldTransitionProgressProvider( + private val foldStateProvider: FoldStateProvider +) : + UnfoldTransitionProgressProvider, + FoldUpdatesListener, + DynamicAnimation.OnAnimationEndListener { + + private val springAnimation = SpringAnimation(this, AnimationProgressProperty) + .apply { + addEndListener(this@PhysicsBasedUnfoldTransitionProgressProvider) + } + + private var isTransitionRunning = false + private var isAnimatedCancelRunning = false + + private var transitionProgress: Float = 0.0f + set(value) { + if (isTransitionRunning) { + listeners.forEach { it.onTransitionProgress(value) } + } + field = value + } + + private val listeners: MutableList = mutableListOf() + + init { + foldStateProvider.addCallback(this) + foldStateProvider.start() + } + + override fun destroy() { + foldStateProvider.stop() + } + + override fun onHingeAngleUpdate(angle: Float) { + if (!isTransitionRunning || isAnimatedCancelRunning) return + val progress = saturate(angle / FINAL_HINGE_ANGLE_POSITION) + springAnimation.animateToFinalPosition(progress) + } + + override fun onFoldUpdate(@FoldUpdate update: Int) { + when (update) { + FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE -> { + startTransition(startValue = 0f) + + // Stop the animation if the device has already opened by the time when + // the display is available as we won't receive the full open event anymore + if (foldStateProvider.isFullyOpened) { + cancelTransition(endValue = 1f, animate = true) + } + } + FOLD_UPDATE_FINISH_FULL_OPEN, FOLD_UPDATE_ABORTED -> { + // Do not cancel if we haven't started the transition yet. + // This could happen when we fully unfolded the device before the screen + // became available. In this case we start and immediately cancel the animation + // in FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE event handler, so we don't need to + // cancel it here. + if (isTransitionRunning) { + cancelTransition(endValue = 1f, animate = true) + } + } + FOLD_UPDATE_FINISH_CLOSED -> { + cancelTransition(endValue = 0f, animate = false) + } + FOLD_UPDATE_START_CLOSING -> { + // The transition might be already running as the device might start closing several + // times before reaching an end state. + if (!isTransitionRunning) { + startTransition(startValue = 1f) + } + } + } + + if (DEBUG) { + Log.d(TAG, "onFoldUpdate = $update") + } + } + + private fun cancelTransition(endValue: Float, animate: Boolean) { + if (isTransitionRunning && animate) { + isAnimatedCancelRunning = true + springAnimation.animateToFinalPosition(endValue) + } else { + transitionProgress = endValue + isAnimatedCancelRunning = false + isTransitionRunning = false + springAnimation.cancel() + + listeners.forEach { + it.onTransitionFinished() + } + + if (DEBUG) { + Log.d(TAG, "onTransitionFinished") + } + } + } + + override fun onAnimationEnd( + animation: DynamicAnimation>, + canceled: Boolean, + value: Float, + velocity: Float + ) { + if (isAnimatedCancelRunning) { + cancelTransition(value, animate = false) + } + } + + private fun onStartTransition() { + listeners.forEach { + it.onTransitionStarted() + } + isTransitionRunning = true + + if (DEBUG) { + Log.d(TAG, "onTransitionStarted") + } + } + + private fun startTransition(startValue: Float) { + if (!isTransitionRunning) onStartTransition() + + springAnimation.apply { + spring = SpringForce().apply { + finalPosition = startValue + dampingRatio = SpringForce.DAMPING_RATIO_NO_BOUNCY + stiffness = SPRING_STIFFNESS + } + minimumVisibleChange = MINIMAL_VISIBLE_CHANGE + setStartValue(startValue) + setMinValue(0f) + setMaxValue(1f) + } + + springAnimation.start() + } + + override fun addCallback(listener: TransitionProgressListener) { + listeners.add(listener) + } + + override fun removeCallback(listener: TransitionProgressListener) { + listeners.remove(listener) + } + + private object AnimationProgressProperty : + FloatPropertyCompat("animation_progress") { + + override fun setValue( + provider: PhysicsBasedUnfoldTransitionProgressProvider, + value: Float + ) { + provider.transitionProgress = value + } + + override fun getValue(provider: PhysicsBasedUnfoldTransitionProgressProvider): Float = + provider.transitionProgress + } +} + +private const val TAG = "PhysicsBasedUnfoldTransitionProgressProvider" +private const val DEBUG = true + +private const val SPRING_STIFFNESS = 200.0f +private const val MINIMAL_VISIBLE_CHANGE = 0.001f +private const val FINAL_HINGE_ANGLE_POSITION = 165f diff --git a/SystemUIShared/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt new file mode 100644 index 0000000000..6d9631c124 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/updates/DeviceFoldStateProvider.kt @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2021 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.unfold.updates + +import android.annotation.FloatRange +import android.content.Context +import android.hardware.devicestate.DeviceStateManager +import android.os.Handler +import android.util.Log +import androidx.annotation.VisibleForTesting +import androidx.core.util.Consumer +import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate +import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener +import com.android.systemui.unfold.updates.hinge.FULLY_CLOSED_DEGREES +import com.android.systemui.unfold.updates.hinge.FULLY_OPEN_DEGREES +import com.android.systemui.unfold.updates.hinge.HingeAngleProvider +import com.android.systemui.unfold.updates.screen.ScreenStatusProvider +import java.util.concurrent.Executor + +class DeviceFoldStateProvider( + context: Context, + private val hingeAngleProvider: HingeAngleProvider, + private val screenStatusProvider: ScreenStatusProvider, + private val deviceStateManager: DeviceStateManager, + private val mainExecutor: Executor, + private val handler: Handler +) : FoldStateProvider { + + private val outputListeners: MutableList = mutableListOf() + + @FoldUpdate + private var lastFoldUpdate: Int? = null + + @FloatRange(from = 0.0, to = 180.0) + private var lastHingeAngle: Float = 0f + + private val hingeAngleListener = HingeAngleListener() + private val screenListener = ScreenStatusListener() + private val foldStateListener = FoldStateListener(context) + private val timeoutRunnable = TimeoutRunnable() + + private var isFolded = false + private var isUnfoldHandled = true + + override fun start() { + deviceStateManager.registerCallback( + mainExecutor, + foldStateListener + ) + screenStatusProvider.addCallback(screenListener) + hingeAngleProvider.addCallback(hingeAngleListener) + } + + override fun stop() { + screenStatusProvider.removeCallback(screenListener) + deviceStateManager.unregisterCallback(foldStateListener) + hingeAngleProvider.removeCallback(hingeAngleListener) + hingeAngleProvider.stop() + } + + override fun addCallback(listener: FoldUpdatesListener) { + outputListeners.add(listener) + } + + override fun removeCallback(listener: FoldUpdatesListener) { + outputListeners.remove(listener) + } + + override val isFullyOpened: Boolean + get() = !isFolded && lastFoldUpdate == FOLD_UPDATE_FINISH_FULL_OPEN + + private val isTransitionInProgess: Boolean + get() = lastFoldUpdate == FOLD_UPDATE_START_OPENING || + lastFoldUpdate == FOLD_UPDATE_START_CLOSING + + private fun onHingeAngle(angle: Float) { + if (DEBUG) { Log.d(TAG, "Hinge angle: $angle, lastHingeAngle: $lastHingeAngle") } + + val isClosing = angle < lastHingeAngle + val isFullyOpened = FULLY_OPEN_DEGREES - angle < FULLY_OPEN_THRESHOLD_DEGREES + val closingEventDispatched = lastFoldUpdate == FOLD_UPDATE_START_CLOSING + + if (isClosing && !closingEventDispatched && !isFullyOpened) { + notifyFoldUpdate(FOLD_UPDATE_START_CLOSING) + } + + if (isTransitionInProgess) { + if (isFullyOpened) { + notifyFoldUpdate(FOLD_UPDATE_FINISH_FULL_OPEN) + cancelTimeout() + } else { + // The timeout will trigger some constant time after the last angle update. + rescheduleAbortAnimationTimeout() + } + } + + lastHingeAngle = angle + outputListeners.forEach { it.onHingeAngleUpdate(angle) } + } + + private inner class FoldStateListener(context: Context) : + DeviceStateManager.FoldStateListener(context, { folded: Boolean -> + isFolded = folded + lastHingeAngle = FULLY_CLOSED_DEGREES + + if (folded) { + hingeAngleProvider.stop() + notifyFoldUpdate(FOLD_UPDATE_FINISH_CLOSED) + cancelTimeout() + isUnfoldHandled = false + } else { + notifyFoldUpdate(FOLD_UPDATE_START_OPENING) + rescheduleAbortAnimationTimeout() + hingeAngleProvider.start() + } + }) + + private fun notifyFoldUpdate(@FoldUpdate update: Int) { + if (DEBUG) { Log.d(TAG, stateToString(update)) } + outputListeners.forEach { it.onFoldUpdate(update) } + lastFoldUpdate = update + } + + private fun rescheduleAbortAnimationTimeout() { + if (isTransitionInProgess) { + cancelTimeout() + } + handler.postDelayed(timeoutRunnable, ABORT_CLOSING_MILLIS) + } + + private fun cancelTimeout() { + handler.removeCallbacks(timeoutRunnable) + } + + private inner class ScreenStatusListener : + ScreenStatusProvider.ScreenListener { + + override fun onScreenTurnedOn() { + // Trigger this event only if we are unfolded and this is the first screen + // turned on event since unfold started. This prevents running the animation when + // turning on the internal display using the power button. + // Initially isUnfoldHandled is true so it will be reset to false *only* when we + // receive 'folded' event. If SystemUI started when device is already folded it will + // still receive 'folded' event on startup. + if (!isFolded && !isUnfoldHandled) { + outputListeners.forEach { it.onFoldUpdate(FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE) } + isUnfoldHandled = true + } + } + } + + private inner class HingeAngleListener : Consumer { + + override fun accept(angle: Float) { + onHingeAngle(angle) + } + } + + private inner class TimeoutRunnable : Runnable { + + override fun run() { + notifyFoldUpdate(FOLD_UPDATE_ABORTED) + } + } +} + +private fun stateToString(@FoldUpdate update: Int): String { + return when (update) { + FOLD_UPDATE_START_OPENING -> "START_OPENING" + FOLD_UPDATE_HALF_OPEN -> "HALF_OPEN" + FOLD_UPDATE_START_CLOSING -> "START_CLOSING" + FOLD_UPDATE_ABORTED -> "ABORTED" + FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE -> "UNFOLDED_SCREEN_AVAILABLE" + FOLD_UPDATE_FINISH_HALF_OPEN -> "FINISH_HALF_OPEN" + FOLD_UPDATE_FINISH_FULL_OPEN -> "FINISH_FULL_OPEN" + FOLD_UPDATE_FINISH_CLOSED -> "FINISH_CLOSED" + else -> "UNKNOWN" + } +} + +private const val TAG = "DeviceFoldProvider" +private const val DEBUG = false + +/** + * Time after which [FOLD_UPDATE_ABORTED] is emitted following a [FOLD_UPDATE_START_CLOSING] or + * [FOLD_UPDATE_START_OPENING] event, if an end state is not reached. + */ +@VisibleForTesting +const val ABORT_CLOSING_MILLIS = 1000L + +/** Threshold after which we consider the device fully unfolded. */ +@VisibleForTesting +const val FULLY_OPEN_THRESHOLD_DEGREES = 15f \ No newline at end of file diff --git a/SystemUIShared/src/com/android/systemui/unfold/updates/FoldStateProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/updates/FoldStateProvider.kt new file mode 100644 index 0000000000..bffebcd451 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/updates/FoldStateProvider.kt @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2021 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.unfold.updates + +import android.annotation.FloatRange +import android.annotation.IntDef +import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener +import com.android.systemui.statusbar.policy.CallbackController + +/** + * Allows to subscribe to main events related to fold/unfold process such as hinge angle update, + * start folding/unfolding, screen availability + */ +interface FoldStateProvider : CallbackController { + fun start() + fun stop() + + val isFullyOpened: Boolean + + interface FoldUpdatesListener { + fun onHingeAngleUpdate(@FloatRange(from = 0.0, to = 180.0) angle: Float) + fun onFoldUpdate(@FoldUpdate update: Int) + } + + @IntDef(prefix = ["FOLD_UPDATE_"], value = [ + FOLD_UPDATE_START_OPENING, + FOLD_UPDATE_HALF_OPEN, + FOLD_UPDATE_START_CLOSING, + FOLD_UPDATE_ABORTED, + FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE, + FOLD_UPDATE_FINISH_HALF_OPEN, + FOLD_UPDATE_FINISH_FULL_OPEN, + FOLD_UPDATE_FINISH_CLOSED + ]) + @Retention(AnnotationRetention.SOURCE) + annotation class FoldUpdate +} + +const val FOLD_UPDATE_START_OPENING = 0 +const val FOLD_UPDATE_HALF_OPEN = 1 +const val FOLD_UPDATE_START_CLOSING = 2 +const val FOLD_UPDATE_ABORTED = 3 +const val FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE = 4 +const val FOLD_UPDATE_FINISH_HALF_OPEN = 5 +const val FOLD_UPDATE_FINISH_FULL_OPEN = 6 +const val FOLD_UPDATE_FINISH_CLOSED = 7 diff --git a/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt new file mode 100644 index 0000000000..9b58b1fcad --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/EmptyHingeAngleProvider.kt @@ -0,0 +1,17 @@ +package com.android.systemui.unfold.updates.hinge + +import androidx.core.util.Consumer + +internal class EmptyHingeAngleProvider : HingeAngleProvider { + override fun start() { + } + + override fun stop() { + } + + override fun removeCallback(listener: Consumer) { + } + + override fun addCallback(listener: Consumer) { + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt new file mode 100644 index 0000000000..6f524560de --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeAngleProvider.kt @@ -0,0 +1,18 @@ +package com.android.systemui.unfold.updates.hinge + +import androidx.core.util.Consumer +import com.android.systemui.statusbar.policy.CallbackController + +/** + * Emits device hinge angle values (angle between two integral parts of the device). + * The hinge angle could be from 0 to 360 degrees inclusive. + * For foldable devices usually 0 corresponds to fully closed (folded) state and + * 180 degrees corresponds to fully open (flat) state + */ +interface HingeAngleProvider : CallbackController> { + fun start() + fun stop() +} + +const val FULLY_OPEN_DEGREES = 180f +const val FULLY_CLOSED_DEGREES = 0f diff --git a/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt new file mode 100644 index 0000000000..a42ebef04d --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/updates/hinge/HingeSensorAngleProvider.kt @@ -0,0 +1,42 @@ +package com.android.systemui.unfold.updates.hinge + +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import androidx.core.util.Consumer + +internal class HingeSensorAngleProvider( + private val sensorManager: SensorManager +) : HingeAngleProvider { + + private val sensorListener = HingeAngleSensorListener() + private val listeners: MutableList> = arrayListOf() + + override fun start() { + val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_HINGE_ANGLE) + sensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_FASTEST) + } + + override fun stop() { + sensorManager.unregisterListener(sensorListener) + } + + override fun removeCallback(listener: Consumer) { + listeners.remove(listener) + } + + override fun addCallback(listener: Consumer) { + listeners.add(listener) + } + + private inner class HingeAngleSensorListener : SensorEventListener { + + override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { + } + + override fun onSensorChanged(event: SensorEvent) { + listeners.forEach { it.accept(event.values[0]) } + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt new file mode 100644 index 0000000000..1eec8033ac --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/updates/screen/ScreenStatusProvider.kt @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2021 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.unfold.updates.screen + +import com.android.systemui.unfold.updates.screen.ScreenStatusProvider.ScreenListener +import com.android.systemui.statusbar.policy.CallbackController + +interface ScreenStatusProvider : CallbackController { + + interface ScreenListener { + /** + * Called when the screen is on and ready (windows are drawn and screen blocker is removed) + */ + fun onScreenTurnedOn() + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt new file mode 100644 index 0000000000..58d7dfb133 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/util/NaturalRotationUnfoldProgressProvider.kt @@ -0,0 +1,72 @@ +package com.android.systemui.unfold.util + +import android.content.Context +import android.os.RemoteException +import android.view.IRotationWatcher +import android.view.IWindowManager +import android.view.Surface +import com.android.systemui.unfold.UnfoldTransitionProgressProvider +import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener + +/** + * [UnfoldTransitionProgressProvider] that emits transition progress only when the display has + * default rotation or 180 degrees opposite rotation (ROTATION_0 or ROTATION_180). + * It could be helpful to run the animation only when the display's rotation is perpendicular + * to the fold. + */ +class NaturalRotationUnfoldProgressProvider( + private val context: Context, + private val windowManagerInterface: IWindowManager, + unfoldTransitionProgressProvider: UnfoldTransitionProgressProvider +) : UnfoldTransitionProgressProvider { + + private val scopedUnfoldTransitionProgressProvider = + ScopedUnfoldTransitionProgressProvider(unfoldTransitionProgressProvider) + private val rotationWatcher = RotationWatcher() + + private var isNaturalRotation: Boolean = false + + fun init() { + try { + windowManagerInterface.watchRotation(rotationWatcher, context.display.displayId) + } catch (e: RemoteException) { + throw e.rethrowFromSystemServer() + } + + onRotationChanged(context.display.rotation) + } + + private fun onRotationChanged(rotation: Int) { + val isNewRotationNatural = rotation == Surface.ROTATION_0 || + rotation == Surface.ROTATION_180 + + if (isNaturalRotation != isNewRotationNatural) { + isNaturalRotation = isNewRotationNatural + scopedUnfoldTransitionProgressProvider.setReadyToHandleTransition(isNewRotationNatural) + } + } + + override fun destroy() { + try { + windowManagerInterface.removeRotationWatcher(rotationWatcher) + } catch (e: RemoteException) { + e.rethrowFromSystemServer() + } + + scopedUnfoldTransitionProgressProvider.destroy() + } + + override fun addCallback(listener: TransitionProgressListener) { + scopedUnfoldTransitionProgressProvider.addCallback(listener) + } + + override fun removeCallback(listener: TransitionProgressListener) { + scopedUnfoldTransitionProgressProvider.removeCallback(listener) + } + + private inner class RotationWatcher : IRotationWatcher.Stub() { + override fun onRotationChanged(rotation: Int) { + this@NaturalRotationUnfoldProgressProvider.onRotationChanged(rotation) + } + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt b/SystemUIShared/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt new file mode 100644 index 0000000000..df9078a155 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/util/ScaleAwareTransitionProgressProvider.kt @@ -0,0 +1,50 @@ +package com.android.systemui.unfold.util + +import android.animation.ValueAnimator +import android.content.ContentResolver +import android.database.ContentObserver +import android.provider.Settings +import com.android.systemui.unfold.UnfoldTransitionProgressProvider +import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener + +/** Wraps [UnfoldTransitionProgressProvider] to disable transitions when animations are disabled. */ +class ScaleAwareTransitionProgressProvider( + unfoldTransitionProgressProvider: UnfoldTransitionProgressProvider, + private val contentResolver: ContentResolver +) : UnfoldTransitionProgressProvider { + + private val scopedUnfoldTransitionProgressProvider = + ScopedUnfoldTransitionProgressProvider(unfoldTransitionProgressProvider) + + private val animatorDurationScaleObserver = object : ContentObserver(null) { + override fun onChange(selfChange: Boolean) { + onAnimatorScaleChanged() + } + } + + init { + contentResolver.registerContentObserver( + Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE), + /* notifyForDescendants= */ false, + animatorDurationScaleObserver) + onAnimatorScaleChanged() + } + + private fun onAnimatorScaleChanged() { + val animationsEnabled = ValueAnimator.areAnimatorsEnabled() + scopedUnfoldTransitionProgressProvider.setReadyToHandleTransition(animationsEnabled) + } + + override fun addCallback(listener: TransitionProgressListener) { + scopedUnfoldTransitionProgressProvider.addCallback(listener) + } + + override fun removeCallback(listener: TransitionProgressListener) { + scopedUnfoldTransitionProgressProvider.removeCallback(listener) + } + + override fun destroy() { + contentResolver.unregisterContentObserver(animatorDurationScaleObserver) + scopedUnfoldTransitionProgressProvider.destroy() + } +} diff --git a/SystemUIShared/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.java b/SystemUIShared/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.java new file mode 100644 index 0000000000..543232da30 --- /dev/null +++ b/SystemUIShared/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.java @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2021 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.unfold.util; + +import android.annotation.NonNull; +import android.annotation.Nullable; + +import com.android.systemui.unfold.UnfoldTransitionProgressProvider; +import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener; + +import java.util.ArrayList; +import java.util.List; + +/** + * Manages progress listeners that can have smaller lifespan than the unfold animation. + * Allows to limit getting transition updates to only when + * {@link ScopedUnfoldTransitionProgressProvider#setReadyToHandleTransition} is called + * with readyToHandleTransition = true + * + * If the transition has already started by the moment when the clients are ready to play + * the transition then it will report transition started callback and current animation progress. + */ +public final class ScopedUnfoldTransitionProgressProvider implements + UnfoldTransitionProgressProvider, TransitionProgressListener { + + private static final float PROGRESS_UNSET = -1f; + + @Nullable + private UnfoldTransitionProgressProvider mSource; + + private final List mListeners = new ArrayList<>(); + + private boolean mIsReadyToHandleTransition; + private boolean mIsTransitionRunning; + private float mLastTransitionProgress = PROGRESS_UNSET; + + public ScopedUnfoldTransitionProgressProvider() { + this(null); + } + + public ScopedUnfoldTransitionProgressProvider( + @Nullable UnfoldTransitionProgressProvider source) { + setSourceProvider(source); + } + + /** + * Sets the source for the unfold transition progress updates, + * it replaces current provider if it is already set + * @param provider transition provider that emits transition progress updates + */ + public void setSourceProvider(@Nullable UnfoldTransitionProgressProvider provider) { + if (mSource != null) { + mSource.removeCallback(this); + } + + if (provider != null) { + mSource = provider; + mSource.addCallback(this); + } else { + mSource = null; + } + } + + /** + * Allows to notify this provide whether the listeners can play the transition or not. + * Call this method with readyToHandleTransition = true when all listeners + * are ready to consume the transition progress events. + * Call it with readyToHandleTransition = false when listeners can't process the events. + */ + public void setReadyToHandleTransition(boolean isReadyToHandleTransition) { + if (mIsTransitionRunning) { + if (isReadyToHandleTransition) { + mListeners.forEach(TransitionProgressListener::onTransitionStarted); + + if (mLastTransitionProgress != PROGRESS_UNSET) { + mListeners.forEach(listener -> + listener.onTransitionProgress(mLastTransitionProgress)); + } + } else { + mIsTransitionRunning = false; + mListeners.forEach(TransitionProgressListener::onTransitionFinished); + } + } + + mIsReadyToHandleTransition = isReadyToHandleTransition; + } + + @Override + public void addCallback(@NonNull TransitionProgressListener listener) { + mListeners.add(listener); + } + + @Override + public void removeCallback(@NonNull TransitionProgressListener listener) { + mListeners.remove(listener); + } + + @Override + public void destroy() { + mSource.removeCallback(this); + } + + @Override + public void onTransitionStarted() { + this.mIsTransitionRunning = true; + if (mIsReadyToHandleTransition) { + mListeners.forEach(TransitionProgressListener::onTransitionStarted); + } + } + + @Override + public void onTransitionProgress(float progress) { + if (mIsReadyToHandleTransition) { + mListeners.forEach(listener -> listener.onTransitionProgress(progress)); + } + + mLastTransitionProgress = progress; + } + + @Override + public void onTransitionFinished() { + if (mIsReadyToHandleTransition) { + mListeners.forEach(TransitionProgressListener::onTransitionFinished); + } + + mIsTransitionRunning = false; + mLastTransitionProgress = PROGRESS_UNSET; + } +}