Merge "On lockscreen to quick-settings transition, media-player should fade in to quick settings instead of just appear." into tm-qpr-dev
diff --git a/core/java/android/content/ClipboardManager.java b/core/java/android/content/ClipboardManager.java
index d41cda1..85af877 100644
--- a/core/java/android/content/ClipboardManager.java
+++ b/core/java/android/content/ClipboardManager.java
@@ -129,7 +129,11 @@
try {
Objects.requireNonNull(clip);
clip.prepareToLeaveProcess(true);
- mService.setPrimaryClip(clip, mContext.getOpPackageName(), mContext.getUserId());
+ mService.setPrimaryClip(
+ clip,
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
+ mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -154,7 +158,11 @@
Objects.requireNonNull(sourcePackage);
clip.prepareToLeaveProcess(true);
mService.setPrimaryClipAsPackage(
- clip, mContext.getOpPackageName(), mContext.getUserId(), sourcePackage);
+ clip,
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
+ mContext.getUserId(),
+ sourcePackage);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -167,7 +175,10 @@
*/
public void clearPrimaryClip() {
try {
- mService.clearPrimaryClip(mContext.getOpPackageName(), mContext.getUserId());
+ mService.clearPrimaryClip(
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
+ mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -183,24 +194,29 @@
*/
public @Nullable ClipData getPrimaryClip() {
try {
- return mService.getPrimaryClip(mContext.getOpPackageName(), mContext.getUserId());
+ return mService.getPrimaryClip(
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
+ mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
- * Returns a description of the current primary clip on the clipboard
- * but not a copy of its data.
+ * Returns a description of the current primary clip on the clipboard but not a copy of its
+ * data.
*
- * <em>If the application is not the default IME or does not have input focus this return
+ * <p><em>If the application is not the default IME or does not have input focus this return
* {@code null}.</em>
*
* @see #setPrimaryClip(ClipData)
*/
public @Nullable ClipDescription getPrimaryClipDescription() {
try {
- return mService.getPrimaryClipDescription(mContext.getOpPackageName(),
+ return mService.getPrimaryClipDescription(
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -215,7 +231,10 @@
*/
public boolean hasPrimaryClip() {
try {
- return mService.hasPrimaryClip(mContext.getOpPackageName(), mContext.getUserId());
+ return mService.hasPrimaryClip(
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
+ mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -226,7 +245,9 @@
if (mPrimaryClipChangedListeners.isEmpty()) {
try {
mService.addPrimaryClipChangedListener(
- mPrimaryClipChangedServiceListener, mContext.getOpPackageName(),
+ mPrimaryClipChangedServiceListener,
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -242,7 +263,9 @@
if (mPrimaryClipChangedListeners.isEmpty()) {
try {
mService.removePrimaryClipChangedListener(
- mPrimaryClipChangedServiceListener, mContext.getOpPackageName(),
+ mPrimaryClipChangedServiceListener,
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -280,7 +303,10 @@
@Deprecated
public boolean hasText() {
try {
- return mService.hasClipboardText(mContext.getOpPackageName(), mContext.getUserId());
+ return mService.hasClipboardText(
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
+ mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -297,7 +323,10 @@
@RequiresPermission(Manifest.permission.SET_CLIP_SOURCE)
public String getPrimaryClipSource() {
try {
- return mService.getPrimaryClipSource(mContext.getOpPackageName(), mContext.getUserId());
+ return mService.getPrimaryClipSource(
+ mContext.getOpPackageName(),
+ mContext.getAttributionTag(),
+ mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/core/java/android/content/IClipboard.aidl b/core/java/android/content/IClipboard.aidl
index 102b8e7..46ece2b 100644
--- a/core/java/android/content/IClipboard.aidl
+++ b/core/java/android/content/IClipboard.aidl
@@ -26,22 +26,22 @@
* {@hide}
*/
interface IClipboard {
- void setPrimaryClip(in ClipData clip, String callingPackage, int userId);
- void setPrimaryClipAsPackage(in ClipData clip, String callingPackage, int userId,
+ void setPrimaryClip(in ClipData clip, String callingPackage, String attributionTag, int userId);
+ void setPrimaryClipAsPackage(in ClipData clip, String callingPackage, String attributionTag, int userId,
String sourcePackage);
- void clearPrimaryClip(String callingPackage, int userId);
- ClipData getPrimaryClip(String pkg, int userId);
- ClipDescription getPrimaryClipDescription(String callingPackage, int userId);
- boolean hasPrimaryClip(String callingPackage, int userId);
+ void clearPrimaryClip(String callingPackage, String attributionTag, int userId);
+ ClipData getPrimaryClip(String pkg, String attributionTag, int userId);
+ ClipDescription getPrimaryClipDescription(String callingPackage, String attributionTag, int userId);
+ boolean hasPrimaryClip(String callingPackage, String attributionTag, int userId);
void addPrimaryClipChangedListener(in IOnPrimaryClipChangedListener listener,
- String callingPackage, int userId);
+ String callingPackage, String attributionTag, int userId);
void removePrimaryClipChangedListener(in IOnPrimaryClipChangedListener listener,
- String callingPackage, int userId);
+ String callingPackage, String attributionTag, int userId);
/**
* Returns true if the clipboard contains text; false otherwise.
*/
- boolean hasClipboardText(String callingPackage, int userId);
+ boolean hasClipboardText(String callingPackage, String attributionTag, int userId);
- String getPrimaryClipSource(String callingPackage, int userId);
+ String getPrimaryClipSource(String callingPackage, String attributionTag, int userId);
}
diff --git a/core/java/android/view/ThreadedRenderer.java b/core/java/android/view/ThreadedRenderer.java
index 785735c..c97eb73 100644
--- a/core/java/android/view/ThreadedRenderer.java
+++ b/core/java/android/view/ThreadedRenderer.java
@@ -25,11 +25,11 @@
import android.graphics.FrameInfo;
import android.graphics.HardwareRenderer;
import android.graphics.Picture;
-import android.graphics.Point;
import android.graphics.RecordingCanvas;
import android.graphics.Rect;
import android.graphics.RenderNode;
import android.os.Trace;
+import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Surface.OutOfResourcesException;
import android.view.View.AttachInfo;
@@ -596,11 +596,18 @@
*/
void setLightCenter(AttachInfo attachInfo) {
// Adjust light position for window offsets.
- final Point displaySize = attachInfo.mPoint;
- attachInfo.mDisplay.getRealSize(displaySize);
- final float lightX = displaySize.x / 2f - attachInfo.mWindowLeft;
+ DisplayMetrics displayMetrics = new DisplayMetrics();
+ attachInfo.mDisplay.getRealMetrics(displayMetrics);
+ final float lightX = displayMetrics.widthPixels / 2f - attachInfo.mWindowLeft;
final float lightY = mLightY - attachInfo.mWindowTop;
- setLightSourceGeometry(lightX, lightY, mLightZ, mLightRadius);
+ // To prevent shadow distortion on larger screens, scale the z position of the light source
+ // relative to the smallest screen dimension.
+ final float zRatio = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels)
+ / (450f * displayMetrics.density);
+ final float zWeightedAdjustment = (zRatio + 2) / 3f;
+ final float lightZ = mLightZ * zWeightedAdjustment;
+
+ setLightSourceGeometry(lightX, lightY, lightZ, mLightRadius);
}
/**
@@ -849,12 +856,18 @@
public void setLightCenter(final Display display,
final int windowLeft, final int windowTop) {
// Adjust light position for window offsets.
- final Point displaySize = new Point();
- display.getRealSize(displaySize);
- final float lightX = displaySize.x / 2f - windowLeft;
+ DisplayMetrics displayMetrics = new DisplayMetrics();
+ display.getRealMetrics(displayMetrics);
+ final float lightX = displayMetrics.widthPixels / 2f - windowLeft;
final float lightY = mLightY - windowTop;
+ // To prevent shadow distortion on larger screens, scale the z position of the light
+ // source relative to the smallest screen dimension.
+ final float zRatio = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels)
+ / (450f * displayMetrics.density);
+ final float zWeightedAdjustment = (zRatio + 2) / 3f;
+ final float lightZ = mLightZ * zWeightedAdjustment;
- setLightSourceGeometry(lightX, lightY, mLightZ, mLightRadius);
+ setLightSourceGeometry(lightX, lightY, lightZ, mLightRadius);
}
public RenderNode getRootNode() {
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index 1dedec3..f691300 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -30,6 +30,7 @@
import android.annotation.Nullable;
import android.app.Activity;
import android.app.ActivityManager;
+import android.app.ActivityOptions;
import android.app.SharedElementCallback;
import android.app.prediction.AppPredictionContext;
import android.app.prediction.AppPredictionManager;
@@ -101,7 +102,10 @@
import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.animation.AccelerateInterpolator;
+import android.view.animation.AlphaAnimation;
+import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
+import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Space;
@@ -197,6 +201,8 @@
private static final String PLURALS_COUNT = "count";
private static final String PLURALS_FILE_NAME = "file_name";
+ private static final String IMAGE_EDITOR_SHARED_ELEMENT = "screenshot_preview_image";
+
private boolean mIsAppPredictorComponentAvailable;
private Map<ChooserTarget, AppTarget> mDirectShareAppTargetCache;
private Map<ChooserTarget, ShortcutInfo> mDirectShareShortcutInfoCache;
@@ -250,6 +256,11 @@
private static final int DEFAULT_LIST_VIEW_UPDATE_DELAY_MS = 125;
+ private static final int URI_PERMISSION_INTENT_FLAGS = Intent.FLAG_GRANT_READ_URI_PERMISSION
+ | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+ | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
+ | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
+
@VisibleForTesting
int mListViewUpdateDelayMs = DeviceConfig.getInt(DeviceConfig.NAMESPACE_SYSTEMUI,
SystemUiDeviceConfigFlags.SHARESHEET_LIST_VIEW_UPDATE_DELAY,
@@ -305,6 +316,8 @@
private boolean mRemoveSharedElements = false;
+ private View mContentView = null;
+
private class ContentPreviewCoordinator {
private static final int IMAGE_FADE_IN_MILLIS = 150;
private static final int IMAGE_LOAD_TIMEOUT = 1;
@@ -990,6 +1003,7 @@
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: " + getComponentName().flattenToShortString());
+ maybeCancelFinishAnimation();
}
@Override
@@ -1085,6 +1099,10 @@
final ComponentName cn = getEditSharingComponent();
final Intent resolveIntent = new Intent(originalIntent);
+ // Retain only URI permission grant flags if present. Other flags may prevent the scene
+ // transition animation from running (i.e FLAG_ACTIVITY_NO_ANIMATION,
+ // FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_NEW_DOCUMENT) but also not needed.
+ resolveIntent.setFlags(originalIntent.getFlags() & URI_PERMISSION_INTENT_FLAGS);
resolveIntent.setComponent(cn);
resolveIntent.setAction(Intent.ACTION_EDIT);
final ResolveInfo ri = getPackageManager().resolveActivity(
@@ -1101,7 +1119,6 @@
return dri;
}
-
@VisibleForTesting
protected TargetInfo getNearbySharingTarget(Intent originalIntent) {
final ComponentName cn = getNearbySharingComponent();
@@ -1204,15 +1221,30 @@
"",
-1,
false);
+ View firstImgView = getFirstVisibleImgPreviewView();
// Action bar is user-independent, always start as primary
- safelyStartActivityAsUser(ti, getPersonalProfileUserHandle());
- finish();
+ if (firstImgView == null) {
+ safelyStartActivityAsUser(ti, getPersonalProfileUserHandle());
+ finish();
+ } else {
+ ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
+ this, firstImgView, IMAGE_EDITOR_SHARED_ELEMENT);
+ safelyStartActivityAsUser(
+ ti, getPersonalProfileUserHandle(), options.toBundle());
+ startFinishAnimation();
+ }
}
);
b.setId(R.id.chooser_edit_button);
return b;
}
+ @Nullable
+ private View getFirstVisibleImgPreviewView() {
+ View firstImage = findViewById(R.id.content_preview_image_1_large);
+ return firstImage != null && firstImage.isVisibleToUser() ? firstImage : null;
+ }
+
private void addActionButton(ViewGroup parent, Button b) {
if (b == null) return;
final ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
@@ -1560,6 +1592,14 @@
}
@Override
+ protected void onStop() {
+ super.onStop();
+ if (maybeCancelFinishAnimation()) {
+ finish();
+ }
+ }
+
+ @Override
protected void onDestroy() {
super.onDestroy();
@@ -2887,6 +2927,30 @@
.setSubtype(previewType));
}
+ private void startFinishAnimation() {
+ View rootView = findRootView();
+ rootView.startAnimation(new FinishAnimation(this, rootView));
+ }
+
+ private boolean maybeCancelFinishAnimation() {
+ View rootView = findRootView();
+ Animation animation = rootView.getAnimation();
+ if (animation instanceof FinishAnimation) {
+ boolean hasEnded = animation.hasEnded();
+ animation.cancel();
+ rootView.clearAnimation();
+ return !hasEnded;
+ }
+ return false;
+ }
+
+ private View findRootView() {
+ if (mContentView == null) {
+ mContentView = findViewById(android.R.id.content);
+ }
+ return mContentView;
+ }
+
abstract static class ViewHolderBase extends RecyclerView.ViewHolder {
private int mViewType;
@@ -3987,6 +4051,66 @@
}
}
+ /**
+ * Used in combination with the scene transition when launching the image editor
+ */
+ private static class FinishAnimation extends AlphaAnimation implements
+ Animation.AnimationListener {
+ private Activity mActivity;
+ private View mRootView;
+ private final float mFromAlpha;
+
+ FinishAnimation(Activity activity, View rootView) {
+ super(rootView.getAlpha(), 0.0f);
+ mActivity = activity;
+ mRootView = rootView;
+ mFromAlpha = rootView.getAlpha();
+ setInterpolator(new LinearInterpolator());
+ long duration = activity.getWindow().getTransitionBackgroundFadeDuration();
+ setDuration(duration);
+ // The scene transition animation looks better when it's not overlapped with this
+ // fade-out animation thus the delay.
+ // It is most likely that the image editor will cause this activity to stop and this
+ // animation will be cancelled in the background without running (i.e. we'll animate
+ // only when this activity remains partially visible after the image editor launch).
+ setStartOffset(duration);
+ super.setAnimationListener(this);
+ }
+
+ @Override
+ public void setAnimationListener(AnimationListener listener) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void cancel() {
+ mRootView.setAlpha(mFromAlpha);
+ cleanup();
+ super.cancel();
+ }
+
+ @Override
+ public void onAnimationStart(Animation animation) {
+ }
+
+ @Override
+ public void onAnimationEnd(Animation animation) {
+ if (mActivity != null) {
+ mActivity.finish();
+ cleanup();
+ }
+ }
+
+ @Override
+ public void onAnimationRepeat(Animation animation) {
+ }
+
+ private void cleanup() {
+ mActivity = null;
+ mRootView = null;
+ }
+ }
+
@Override
protected void maybeLogProfileChange() {
getChooserActivityLogger().logShareheetProfileChanged();
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index 40429c6..e9e437f 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -1314,7 +1314,7 @@
StrictMode.disableDeathOnFileUriExposure();
try {
UserHandle currentUserHandle = mMultiProfilePagerAdapter.getCurrentUserHandle();
- safelyStartActivityInternal(cti, currentUserHandle);
+ safelyStartActivityInternal(cti, currentUserHandle, null);
} finally {
StrictMode.enableDeathOnFileUriExposure();
}
@@ -1327,18 +1327,23 @@
*/
@VisibleForTesting
public void safelyStartActivityAsUser(TargetInfo cti, UserHandle user) {
+ safelyStartActivityAsUser(cti, user, null);
+ }
+
+ protected void safelyStartActivityAsUser(
+ TargetInfo cti, UserHandle user, @Nullable Bundle options) {
// We're dispatching intents that might be coming from legacy apps, so
// don't kill ourselves.
StrictMode.disableDeathOnFileUriExposure();
try {
- safelyStartActivityInternal(cti, user);
+ safelyStartActivityInternal(cti, user, options);
} finally {
StrictMode.enableDeathOnFileUriExposure();
}
}
-
- private void safelyStartActivityInternal(TargetInfo cti, UserHandle user) {
+ private void safelyStartActivityInternal(
+ TargetInfo cti, UserHandle user, @Nullable Bundle options) {
// If the target is suspended, the activity will not be successfully launched.
// Do not unregister from package manager updates in this case
if (!cti.isSuspended() && mRegistered) {
@@ -1356,14 +1361,14 @@
Toast.makeText(this, mProfileSwitchMessage, Toast.LENGTH_LONG).show();
}
if (!mSafeForwardingMode) {
- if (cti.startAsUser(this, null, user)) {
+ if (cti.startAsUser(this, options, user)) {
onActivityStarted(cti);
maybeLogCrossProfileTargetLaunch(cti, user);
}
return;
}
try {
- if (cti.startAsCaller(this, null, user.getIdentifier())) {
+ if (cti.startAsCaller(this, options, user.getIdentifier())) {
onActivityStarted(cti);
maybeLogCrossProfileTargetLaunch(cti, user);
}
diff --git a/core/java/com/android/internal/widget/ResolverDrawerLayout.java b/core/java/com/android/internal/widget/ResolverDrawerLayout.java
index 1cdc108..af9c5a5 100644
--- a/core/java/com/android/internal/widget/ResolverDrawerLayout.java
+++ b/core/java/com/android/internal/widget/ResolverDrawerLayout.java
@@ -53,7 +53,7 @@
/**
* Max width of the whole drawer layout
*/
- private int mMaxWidth;
+ private final int mMaxWidth;
/**
* Max total visible height of views not marked always-show when in the closed/initial state
@@ -187,8 +187,10 @@
}
public void setSmallCollapsed(boolean smallCollapsed) {
- mSmallCollapsed = smallCollapsed;
- requestLayout();
+ if (mSmallCollapsed != smallCollapsed) {
+ mSmallCollapsed = smallCollapsed;
+ requestLayout();
+ }
}
public boolean isSmallCollapsed() {
@@ -200,9 +202,10 @@
}
public void setShowAtTop(boolean showOnTop) {
- mShowAtTop = showOnTop;
- invalidate();
- requestLayout();
+ if (mShowAtTop != showOnTop) {
+ mShowAtTop = showOnTop;
+ requestLayout();
+ }
}
public boolean getShowAtTop() {
@@ -220,6 +223,9 @@
public void setCollapsibleHeightReserved(int heightPixels) {
final int oldReserved = mCollapsibleHeightReserved;
mCollapsibleHeightReserved = heightPixels;
+ if (oldReserved != mCollapsibleHeightReserved) {
+ requestLayout();
+ }
final int dReserved = mCollapsibleHeightReserved - oldReserved;
if (dReserved != 0 && mIsDragging) {
@@ -255,7 +261,7 @@
if (getShowAtTop()) {
// Keep the drawer fully open.
- mCollapseOffset = 0;
+ setCollapseOffset(0);
return false;
}
@@ -264,9 +270,9 @@
if (remainClosed && (oldCollapsibleHeight < mCollapsibleHeight
&& mCollapseOffset == oldCollapsibleHeight)) {
// Stay closed even at the new height.
- mCollapseOffset = mCollapsibleHeight;
+ setCollapseOffset(mCollapsibleHeight);
} else {
- mCollapseOffset = Math.min(mCollapseOffset, mCollapsibleHeight);
+ setCollapseOffset(Math.min(mCollapseOffset, mCollapsibleHeight));
}
final boolean isCollapsedNew = mCollapseOffset != 0;
if (isCollapsedOld != isCollapsedNew) {
@@ -274,11 +280,18 @@
}
} else {
// Start out collapsed at first unless we restored state for otherwise
- mCollapseOffset = mOpenOnLayout ? 0 : mCollapsibleHeight;
+ setCollapseOffset(mOpenOnLayout ? 0 : mCollapsibleHeight);
}
return true;
}
+ private void setCollapseOffset(float collapseOffset) {
+ if (mCollapseOffset != collapseOffset) {
+ mCollapseOffset = collapseOffset;
+ requestLayout();
+ }
+ }
+
private int getMaxCollapsedHeight() {
return (isSmallCollapsed() ? mMaxCollapsedHeightSmall : mMaxCollapsedHeight)
+ mCollapsibleHeightReserved;
@@ -420,8 +433,7 @@
case MotionEvent.ACTION_POINTER_DOWN: {
final int pointerIndex = ev.getActionIndex();
- final int pointerId = ev.getPointerId(pointerIndex);
- mActivePointerId = pointerId;
+ mActivePointerId = ev.getPointerId(pointerIndex);
mInitialTouchX = ev.getX(pointerIndex);
mInitialTouchY = mLastTouchY = ev.getY(pointerIndex);
}
@@ -924,7 +936,7 @@
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int sourceWidth = MeasureSpec.getSize(widthMeasureSpec);
int widthSize = sourceWidth;
- int heightSize = MeasureSpec.getSize(heightMeasureSpec);
+ final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// Single-use layout; just ignore the mode and use available space.
// Clamp to maxWidth.
diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml
index b754100..2542268 100644
--- a/core/res/res/values/dimens.xml
+++ b/core/res/res/values/dimens.xml
@@ -684,7 +684,7 @@
<!-- Lighting and shadow properties -->
<dimen name="light_y">0dp</dimen>
- <dimen name="light_z">600dp</dimen>
+ <dimen name="light_z">500dp</dimen>
<dimen name="light_radius">800dp</dimen>
<item type="dimen" format="float" name="ambient_shadow_alpha">0.039</item>
<item type="dimen" format="float" name="spot_shadow_alpha">0.19</item>
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java
index 0cf2b28..d53a98c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/back/BackAnimationController.java
@@ -403,7 +403,9 @@
private boolean shouldDispatchToLauncher(int backType) {
return backType == BackNavigationInfo.TYPE_RETURN_TO_HOME
&& mBackToLauncherCallback != null
- && mEnableAnimations.get();
+ && mEnableAnimations.get()
+ && mBackNavigationInfo != null
+ && mBackNavigationInfo.getDepartingAnimationTarget() != null;
}
private static void dispatchOnBackStarted(IOnBackInvokedCallback callback) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java
index 572516d..cdca051 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java
@@ -95,6 +95,7 @@
mDragResizeCallback = dragResizeCallback;
}
+ @Override
void relayout(ActivityManager.RunningTaskInfo taskInfo) {
final int shadowRadiusDp = taskInfo.isFocused
? DECOR_SHADOW_FOCUSED_THICKNESS_IN_DIP : DECOR_SHADOW_UNFOCUSED_THICKNESS_IN_DIP;
@@ -119,8 +120,8 @@
});
if (mResult.mRootView == null) {
- // This means the task is hidden. Nothing is set up in this case including the
- // decoration surface.
+ // This means something blocks the window decor from showing, e.g. the task is hidden.
+ // Nothing is set up in this case including the decoration surface.
return;
}
if (oldRootView != mResult.mRootView) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java
index 0c502283..c19a33a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/WindowDecoration.java
@@ -38,6 +38,8 @@
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.common.DisplayController;
+import java.util.function.Supplier;
+
/**
* Manages a container surface and a windowless window to show window decoration. Responsible to
* update window decoration window state and layout parameters on task info changes and so that
@@ -53,7 +55,8 @@
*
* @param <T> The type of the root view
*/
-public class WindowDecoration<T extends View & TaskFocusStateConsumer> implements AutoCloseable {
+public abstract class WindowDecoration<T extends View & TaskFocusStateConsumer>
+ implements AutoCloseable {
private static final int[] CAPTION_INSETS_TYPES = { InsetsState.ITYPE_CAPTION_BAR };
/**
@@ -62,6 +65,20 @@
final Context mContext;
final DisplayController mDisplayController;
final ShellTaskOrganizer mTaskOrganizer;
+ final Supplier<SurfaceControl.Builder> mSurfaceControlBuilderSupplier;
+ final SurfaceControlViewHostFactory mSurfaceControlViewHostFactory;
+ private final DisplayController.OnDisplaysChangedListener mOnDisplaysChangedListener =
+ new DisplayController.OnDisplaysChangedListener() {
+ @Override
+ public void onDisplayAdded(int displayId) {
+ if (mTaskInfo.displayId != displayId) {
+ return;
+ }
+
+ mDisplayController.removeDisplayWindowListener(this);
+ relayout(mTaskInfo);
+ }
+ };
RunningTaskInfo mTaskInfo;
final SurfaceControl mTaskSurface;
@@ -71,7 +88,7 @@
SurfaceControl mDecorationContainerSurface;
SurfaceControl mTaskBackgroundSurface;
- private CaptionWindowManager mCaptionWindowManager;
+ private final CaptionWindowManager mCaptionWindowManager;
private SurfaceControlViewHost mViewHost;
private final Rect mCaptionInsetsRect = new Rect();
@@ -84,11 +101,25 @@
ShellTaskOrganizer taskOrganizer,
RunningTaskInfo taskInfo,
SurfaceControl taskSurface) {
+ this(context, displayController, taskOrganizer, taskInfo, taskSurface,
+ SurfaceControl.Builder::new, new SurfaceControlViewHostFactory() {});
+ }
+
+ WindowDecoration(
+ Context context,
+ DisplayController displayController,
+ ShellTaskOrganizer taskOrganizer,
+ RunningTaskInfo taskInfo,
+ SurfaceControl taskSurface,
+ Supplier<SurfaceControl.Builder> surfaceControlBuilderSupplier,
+ SurfaceControlViewHostFactory surfaceControlViewHostFactory) {
mContext = context;
mDisplayController = displayController;
mTaskOrganizer = taskOrganizer;
mTaskInfo = taskInfo;
mTaskSurface = taskSurface;
+ mSurfaceControlBuilderSupplier = surfaceControlBuilderSupplier;
+ mSurfaceControlViewHostFactory = surfaceControlViewHostFactory;
mDisplay = mDisplayController.getDisplay(mTaskInfo.displayId);
mDecorWindowContext = mContext.createConfigurationContext(mTaskInfo.getConfiguration());
@@ -99,6 +130,15 @@
new CaptionWindowManager(mTaskInfo.getConfiguration(), mTaskSurface);
}
+ /**
+ * Used by {@link WindowDecoration} to trigger a new relayout because the requirements for a
+ * relayout weren't satisfied are satisfied now.
+ *
+ * @param taskInfo The previous {@link RunningTaskInfo} passed into {@link #relayout} or the
+ * constructor.
+ */
+ abstract void relayout(RunningTaskInfo taskInfo);
+
void relayout(RunningTaskInfo taskInfo, int layoutResId, T rootView, float captionHeightDp,
Rect outsetsDp, float shadowRadiusDp, SurfaceControl.Transaction t,
WindowContainerTransaction wct, RelayoutResult<T> outResult) {
@@ -110,7 +150,7 @@
}
if (!mTaskInfo.isVisible) {
- close();
+ releaseViews();
t.hide(mTaskSurface);
return;
}
@@ -123,10 +163,14 @@
rootView = null; // Clear it just in case we use it accidentally
final Configuration taskConfig = mTaskInfo.getConfiguration();
if (oldTaskConfig.densityDpi != taskConfig.densityDpi
+ || mDisplay == null
|| mDisplay.getDisplayId() != mTaskInfo.displayId) {
- close();
+ releaseViews();
- mDisplay = mDisplayController.getDisplay(mTaskInfo.displayId);
+ if (!obtainDisplayOrRegisterListener()) {
+ outResult.mRootView = null;
+ return;
+ }
mDecorWindowContext = mContext.createConfigurationContext(taskConfig);
if (layoutResId != 0) {
outResult.mRootView =
@@ -141,7 +185,7 @@
// DecorationContainerSurface
if (mDecorationContainerSurface == null) {
- final SurfaceControl.Builder builder = new SurfaceControl.Builder();
+ final SurfaceControl.Builder builder = mSurfaceControlBuilderSupplier.get();
mDecorationContainerSurface = builder
.setName("Decor container of Task=" + mTaskInfo.taskId)
.setContainerLayer()
@@ -168,7 +212,7 @@
// TaskBackgroundSurface
if (mTaskBackgroundSurface == null) {
- final SurfaceControl.Builder builder = new SurfaceControl.Builder();
+ final SurfaceControl.Builder builder = mSurfaceControlBuilderSupplier.get();
mTaskBackgroundSurface = builder
.setName("Background of Task=" + mTaskInfo.taskId)
.setEffectLayer()
@@ -195,7 +239,7 @@
lp.setTitle("Caption of Task=" + mTaskInfo.taskId);
lp.setTrustedOverlay();
if (mViewHost == null) {
- mViewHost = new SurfaceControlViewHost(mDecorWindowContext, mDisplay,
+ mViewHost = mSurfaceControlViewHostFactory.create(mDecorWindowContext, mDisplay,
mCaptionWindowManager, true);
mViewHost.setView(outResult.mRootView, lp);
} else {
@@ -225,8 +269,22 @@
.show(mTaskSurface);
}
- @Override
- public void close() {
+ /**
+ * Obtains the {@link Display} instance for the display ID in {@link #mTaskInfo} if it exists or
+ * registers {@link #mOnDisplaysChangedListener} if it doesn't.
+ *
+ * @return {@code true} if the {@link Display} instance exists; or {@code false} otherwise
+ */
+ private boolean obtainDisplayOrRegisterListener() {
+ mDisplay = mDisplayController.getDisplay(mTaskInfo.displayId);
+ if (mDisplay == null) {
+ mDisplayController.addDisplayWindowListener(mOnDisplaysChangedListener);
+ return false;
+ }
+ return true;
+ }
+
+ private void releaseViews() {
if (mViewHost != null) {
mViewHost.release();
mViewHost = null;
@@ -243,6 +301,12 @@
}
}
+ @Override
+ public void close() {
+ mDisplayController.removeDisplayWindowListener(mOnDisplaysChangedListener);
+ releaseViews();
+ }
+
static class RelayoutResult<T extends View & TaskFocusStateConsumer> {
int mWidth;
int mHeight;
@@ -267,4 +331,11 @@
super.setConfiguration(configuration);
}
}
+
+ interface SurfaceControlViewHostFactory {
+ default SurfaceControlViewHost create(
+ Context c, Display d, WindowlessWindowManager wmm, boolean useSfChoreographer) {
+ return new SurfaceControlViewHost(c, d, wmm, useSfChoreographer);
+ }
+ }
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/MockSurfaceControlHelper.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/MockSurfaceControlHelper.java
new file mode 100644
index 0000000..4922872
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/MockSurfaceControlHelper.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell;
+
+import static org.mockito.Mockito.RETURNS_SELF;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import android.view.SurfaceControl;
+
+/**
+ * Helper class to provide mocks for {@link SurfaceControl.Builder} and
+ * {@link SurfaceControl.Transaction} with method chaining support.
+ */
+public class MockSurfaceControlHelper {
+ private MockSurfaceControlHelper() {}
+
+ /**
+ * Creates a mock {@link SurfaceControl.Builder} that supports method chaining and return the
+ * given {@link SurfaceControl} when calling {@link SurfaceControl.Builder#build()}.
+ *
+ * @param mockSurfaceControl the first {@link SurfaceControl} to return
+ * @param mockSurfaceControls following {@link SurfaceControl} to return
+ * @return the mock of {@link SurfaceControl.Builder}
+ */
+ public static SurfaceControl.Builder createMockSurfaceControlBuilder(
+ SurfaceControl mockSurfaceControl, SurfaceControl... mockSurfaceControls) {
+ final SurfaceControl.Builder mockBuilder = mock(SurfaceControl.Builder.class, RETURNS_SELF);
+ doReturn(mockSurfaceControl, (Object[]) mockSurfaceControls)
+ .when(mockBuilder)
+ .build();
+ return mockBuilder;
+ }
+
+ /**
+ * Creates a mock {@link SurfaceControl.Transaction} that supports method chaining.
+ * @return the mock of {@link SurfaceControl.Transaction}
+ */
+ public static SurfaceControl.Transaction createMockSurfaceControlTransaction() {
+ return mock(SurfaceControl.Transaction.class, RETURNS_SELF);
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/TestRunningTaskInfoBuilder.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/TestRunningTaskInfoBuilder.java
index 51eec27..c0720cf 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/TestRunningTaskInfoBuilder.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/TestRunningTaskInfoBuilder.java
@@ -25,8 +25,10 @@
import android.app.ActivityManager;
import android.app.WindowConfiguration;
+import android.graphics.Point;
import android.graphics.Rect;
import android.os.IBinder;
+import android.view.Display;
import android.window.IWindowContainerToken;
import android.window.WindowContainerToken;
@@ -38,6 +40,10 @@
private int mParentTaskId = INVALID_TASK_ID;
private @WindowConfiguration.ActivityType int mActivityType = ACTIVITY_TYPE_STANDARD;
private @WindowConfiguration.WindowingMode int mWindowingMode = WINDOWING_MODE_UNDEFINED;
+ private int mDisplayId = Display.DEFAULT_DISPLAY;
+ private ActivityManager.TaskDescription.Builder mTaskDescriptionBuilder = null;
+ private final Point mPositionInParent = new Point();
+ private boolean mIsVisible = false;
public static WindowContainerToken createMockWCToken() {
final IWindowContainerToken itoken = mock(IWindowContainerToken.class);
@@ -68,17 +74,42 @@
return this;
}
+ public TestRunningTaskInfoBuilder setDisplayId(int displayId) {
+ mDisplayId = displayId;
+ return this;
+ }
+
+ public TestRunningTaskInfoBuilder setTaskDescriptionBuilder(
+ ActivityManager.TaskDescription.Builder builder) {
+ mTaskDescriptionBuilder = builder;
+ return this;
+ }
+
+ public TestRunningTaskInfoBuilder setPositionInParent(int x, int y) {
+ mPositionInParent.set(x, y);
+ return this;
+ }
+
+ public TestRunningTaskInfoBuilder setVisible(boolean isVisible) {
+ mIsVisible = isVisible;
+ return this;
+ }
+
public ActivityManager.RunningTaskInfo build() {
final ActivityManager.RunningTaskInfo info = new ActivityManager.RunningTaskInfo();
- info.parentTaskId = INVALID_TASK_ID;
info.taskId = sNextTaskId++;
info.parentTaskId = mParentTaskId;
+ info.displayId = mDisplayId;
info.configuration.windowConfiguration.setBounds(mBounds);
info.configuration.windowConfiguration.setActivityType(mActivityType);
info.configuration.windowConfiguration.setWindowingMode(mWindowingMode);
info.token = mToken;
info.isResizeable = true;
info.supportsMultiWindow = true;
+ info.taskDescription =
+ mTaskDescriptionBuilder != null ? mTaskDescriptionBuilder.build() : null;
+ info.positionInParent = mPositionInParent;
+ info.isVisible = mIsVisible;
return info;
}
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipAnimationControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipAnimationControllerTest.java
index c685fdc..52d78ca 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipAnimationControllerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipAnimationControllerTest.java
@@ -21,6 +21,7 @@
import static android.view.Surface.ROTATION_270;
import static android.view.Surface.ROTATION_90;
+import static com.android.wm.shell.MockSurfaceControlHelper.createMockSurfaceControlTransaction;
import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_LEAVE_PIP;
import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_TO_PIP;
@@ -37,6 +38,7 @@
import androidx.test.filters.SmallTest;
+import com.android.wm.shell.MockSurfaceControlHelper;
import com.android.wm.shell.ShellTestCase;
import org.junit.Before;
@@ -103,7 +105,8 @@
final PipAnimationController.PipTransitionAnimator oldAnimator = mPipAnimationController
.getAnimator(mTaskInfo, mLeash, baseValue, startValue, endValue1, null,
TRANSITION_DIRECTION_TO_PIP, 0, ROTATION_0);
- oldAnimator.setSurfaceControlTransactionFactory(PipDummySurfaceControlTx::new);
+ oldAnimator.setSurfaceControlTransactionFactory(
+ MockSurfaceControlHelper::createMockSurfaceControlTransaction);
oldAnimator.start();
final PipAnimationController.PipTransitionAnimator newAnimator = mPipAnimationController
@@ -133,7 +136,7 @@
@Test
public void pipTransitionAnimator_rotatedEndValue() {
- final PipDummySurfaceControlTx tx = new PipDummySurfaceControlTx();
+ final SurfaceControl.Transaction tx = createMockSurfaceControlTransaction();
final Rect startBounds = new Rect(200, 700, 400, 800);
final Rect endBounds = new Rect(0, 0, 500, 1000);
// Fullscreen to PiP.
@@ -183,7 +186,8 @@
final PipAnimationController.PipTransitionAnimator animator = mPipAnimationController
.getAnimator(mTaskInfo, mLeash, baseValue, startValue, endValue, null,
TRANSITION_DIRECTION_TO_PIP, 0, ROTATION_0);
- animator.setSurfaceControlTransactionFactory(PipDummySurfaceControlTx::new);
+ animator.setSurfaceControlTransactionFactory(
+ MockSurfaceControlHelper::createMockSurfaceControlTransaction);
animator.setPipAnimationCallback(mPipAnimationCallback);
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipDummySurfaceControlTx.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipDummySurfaceControlTx.java
deleted file mode 100644
index ccf8f6e..0000000
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipDummySurfaceControlTx.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.pip;
-
-import android.graphics.Matrix;
-import android.view.SurfaceControl;
-
-/**
- * A dummy {@link SurfaceControl.Transaction} class for testing purpose and supports
- * method chaining.
- */
-public class PipDummySurfaceControlTx extends SurfaceControl.Transaction {
- @Override
- public SurfaceControl.Transaction setAlpha(SurfaceControl leash, float alpha) {
- return this;
- }
-
- @Override
- public SurfaceControl.Transaction setPosition(SurfaceControl leash, float x, float y) {
- return this;
- }
-
- @Override
- public SurfaceControl.Transaction setWindowCrop(SurfaceControl leash, int w, int h) {
- return this;
- }
-
- @Override
- public SurfaceControl.Transaction setCornerRadius(SurfaceControl leash, float radius) {
- return this;
- }
-
- @Override
- public SurfaceControl.Transaction setShadowRadius(SurfaceControl leash, float radius) {
- return this;
- }
-
- @Override
- public SurfaceControl.Transaction setMatrix(SurfaceControl leash, Matrix matrix,
- float[] float9) {
- return this;
- }
-
- @Override
- public SurfaceControl.Transaction setFrameTimelineVsync(long frameTimelineVsyncId) {
- return this;
- }
-
- @Override
- public void apply() {}
-}
-
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
index e8e6254..b351f8f 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
@@ -44,6 +44,7 @@
import android.view.DisplayInfo;
import android.window.WindowContainerToken;
+import com.android.wm.shell.MockSurfaceControlHelper;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.ShellTestCase;
import com.android.wm.shell.TestShellExecutor;
@@ -246,7 +247,8 @@
mPipBoundsState.setDisplayLayout(new DisplayLayout(info,
mContext.getResources(), true, true));
mSpiedPipTaskOrganizer.setOneShotAnimationType(PipAnimationController.ANIM_TYPE_ALPHA);
- mSpiedPipTaskOrganizer.setSurfaceControlTransactionFactory(PipDummySurfaceControlTx::new);
+ mSpiedPipTaskOrganizer.setSurfaceControlTransactionFactory(
+ MockSurfaceControlHelper::createMockSurfaceControlTransaction);
doNothing().when(mSpiedPipTaskOrganizer).enterPipWithAlphaAnimation(any(), anyLong());
doNothing().when(mSpiedPipTaskOrganizer).scheduleAnimateResizePip(any(), anyInt(), any());
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/WindowDecorationTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/WindowDecorationTests.java
new file mode 100644
index 0000000..680034bd
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/WindowDecorationTests.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.windowdecor;
+
+import static com.android.wm.shell.MockSurfaceControlHelper.createMockSurfaceControlBuilder;
+import static com.android.wm.shell.MockSurfaceControlHelper.createMockSurfaceControlTransaction;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.same;
+import static org.mockito.Mockito.verify;
+
+import android.app.ActivityManager;
+import android.content.Context;
+import android.graphics.Color;
+import android.graphics.Rect;
+import android.testing.AndroidTestingRunner;
+import android.view.Display;
+import android.view.SurfaceControl;
+import android.view.SurfaceControlViewHost;
+import android.view.View;
+import android.window.WindowContainerTransaction;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.wm.shell.ShellTaskOrganizer;
+import com.android.wm.shell.ShellTestCase;
+import com.android.wm.shell.TestRunningTaskInfoBuilder;
+import com.android.wm.shell.common.DisplayController;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+
+import java.util.function.Supplier;
+
+/**
+ * Tests for {@link WindowDecoration}.
+ *
+ * Build/Install/Run:
+ * atest WMShellUnitTests:WindowDecorationTests
+ */
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+public class WindowDecorationTests extends ShellTestCase {
+ private static final int CAPTION_HEIGHT_DP = 32;
+ private static final int SHADOW_RADIUS_DP = 5;
+
+ private final Rect mOutsetsDp = new Rect();
+ private final WindowDecoration.RelayoutResult<TestView> mRelayoutResult =
+ new WindowDecoration.RelayoutResult<>();
+
+ @Mock
+ private DisplayController mMockDisplayController;
+ @Mock
+ private ShellTaskOrganizer mMockShellTaskOrganizer;
+ @Mock
+ private WindowDecoration.SurfaceControlViewHostFactory mMockSurfaceControlViewHostFactory;
+ @Mock
+ private SurfaceControlViewHost mMockSurfaceControlViewHost;
+ @Mock
+ private TestView mMockView;
+ @Mock
+ private WindowContainerTransaction mMockWindowContainerTransaction;
+
+ private SurfaceControl.Builder mMockSurfaceControlBuilder;
+ private SurfaceControl.Transaction mMockSurfaceControlTransaction;
+
+ @Before
+ public void setUp() {
+ mMockSurfaceControlBuilder = createMockSurfaceControlBuilder(mock(SurfaceControl.class));
+ mMockSurfaceControlTransaction = createMockSurfaceControlTransaction();
+
+ doReturn(mMockSurfaceControlViewHost).when(mMockSurfaceControlViewHostFactory)
+ .create(any(), any(), any(), anyBoolean());
+ }
+
+ @Test
+ public void testNotCrashWhenDisplayAppearsAfterTask() {
+ doReturn(mock(Display.class)).when(mMockDisplayController)
+ .getDisplay(Display.DEFAULT_DISPLAY);
+
+ final int displayId = Display.DEFAULT_DISPLAY + 1;
+ final ActivityManager.TaskDescription.Builder taskDescriptionBuilder =
+ new ActivityManager.TaskDescription.Builder()
+ .setBackgroundColor(Color.BLACK);
+ final ActivityManager.RunningTaskInfo taskInfo = new TestRunningTaskInfoBuilder()
+ .setDisplayId(displayId)
+ .setTaskDescriptionBuilder(taskDescriptionBuilder)
+ .setVisible(true)
+ .build();
+
+ final TestWindowDecoration windowDecor =
+ createWindowDecoration(taskInfo, new SurfaceControl());
+ windowDecor.relayout(taskInfo);
+
+ // It shouldn't show the window decoration when it can't obtain the display instance.
+ assertThat(mRelayoutResult.mRootView).isNull();
+
+ final ArgumentCaptor<DisplayController.OnDisplaysChangedListener> listenerArgumentCaptor =
+ ArgumentCaptor.forClass(DisplayController.OnDisplaysChangedListener.class);
+ verify(mMockDisplayController).addDisplayWindowListener(listenerArgumentCaptor.capture());
+ final DisplayController.OnDisplaysChangedListener listener =
+ listenerArgumentCaptor.getValue();
+
+ // Adding an irrelevant display shouldn't change the result.
+ listener.onDisplayAdded(Display.DEFAULT_DISPLAY);
+ assertThat(mRelayoutResult.mRootView).isNull();
+
+ final Display mockDisplay = mock(Display.class);
+ doReturn(mockDisplay).when(mMockDisplayController).getDisplay(displayId);
+
+ listener.onDisplayAdded(displayId);
+
+ // The listener should be removed when the display shows up.
+ verify(mMockDisplayController).removeDisplayWindowListener(same(listener));
+
+ assertThat(mRelayoutResult.mRootView).isSameInstanceAs(mMockView);
+ verify(mMockSurfaceControlViewHostFactory)
+ .create(any(), eq(mockDisplay), any(), anyBoolean());
+ verify(mMockSurfaceControlViewHost).setView(same(mMockView), any());
+ }
+
+ private TestWindowDecoration createWindowDecoration(
+ ActivityManager.RunningTaskInfo taskInfo, SurfaceControl testSurface) {
+ return new TestWindowDecoration(mContext, mMockDisplayController, mMockShellTaskOrganizer,
+ taskInfo, testSurface, () -> mMockSurfaceControlBuilder,
+ mMockSurfaceControlViewHostFactory);
+ }
+
+ private static class TestView extends View implements TaskFocusStateConsumer {
+ private TestView(Context context) {
+ super(context);
+ }
+
+ @Override
+ public void setTaskFocusState(boolean focused) {}
+ }
+
+ private class TestWindowDecoration extends WindowDecoration<TestView> {
+ TestWindowDecoration(Context context, DisplayController displayController,
+ ShellTaskOrganizer taskOrganizer, ActivityManager.RunningTaskInfo taskInfo,
+ SurfaceControl taskSurface,
+ Supplier<SurfaceControl.Builder> surfaceControlBuilderSupplier,
+ SurfaceControlViewHostFactory surfaceControlViewHostFactory) {
+ super(context, displayController, taskOrganizer, taskInfo, taskSurface,
+ surfaceControlBuilderSupplier, surfaceControlViewHostFactory);
+ }
+
+ @Override
+ void relayout(ActivityManager.RunningTaskInfo taskInfo) {
+ relayout(null /* taskInfo */, 0 /* layoutResId */, mMockView, CAPTION_HEIGHT_DP,
+ mOutsetsDp, SHADOW_RADIUS_DP, mMockSurfaceControlTransaction,
+ mMockWindowContainerTransaction, mRelayoutResult);
+ }
+ }
+}
diff --git a/libs/hwui/Readback.cpp b/libs/hwui/Readback.cpp
index 4cce87a..a3ba88e 100644
--- a/libs/hwui/Readback.cpp
+++ b/libs/hwui/Readback.cpp
@@ -90,11 +90,36 @@
SkRect srcRect = inSrcRect.toSkRect();
- SkRect imageSrcRect =
- SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
- if (imageSrcRect.isEmpty()) {
- imageSrcRect = SkRect::MakeIWH(description.width, description.height);
+ SkRect imageSrcRect = SkRect::MakeIWH(description.width, description.height);
+ SkISize imageWH = SkISize::Make(description.width, description.height);
+ if (cropRect.left < cropRect.right && cropRect.top < cropRect.bottom) {
+ imageSrcRect =
+ SkRect::MakeLTRB(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom);
+ imageWH = SkISize::Make(cropRect.right - cropRect.left, cropRect.bottom - cropRect.top);
+
+ // Chroma channels of YUV420 images are subsampled we may need to shrink the crop region by
+ // a whole texel on each side. Since skia still adds its own 0.5 inset, we apply an
+ // additional 0.5 inset. See GLConsumer::computeTransformMatrix for details.
+ float shrinkAmount = 0.0f;
+ switch (description.format) {
+ // Use HAL formats since some AHB formats are only available in vndk
+ case HAL_PIXEL_FORMAT_YCBCR_420_888:
+ case HAL_PIXEL_FORMAT_YV12:
+ case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
+ shrinkAmount = 0.5f;
+ break;
+ default:
+ break;
+ }
+
+ // Shrink the crop if it has more than 1-px and differs from the buffer size.
+ if (imageWH.width() > 1 && imageWH.width() < (int32_t)description.width)
+ imageSrcRect = imageSrcRect.makeInset(shrinkAmount, 0);
+
+ if (imageWH.height() > 1 && imageWH.height() < (int32_t)description.height)
+ imageSrcRect = imageSrcRect.makeInset(0, shrinkAmount);
}
+
ALOGV("imageSrcRect = " RECT_STRING, SK_RECT_ARGS(imageSrcRect));
// Represents the "logical" width/height of the texture. That is, the dimensions of the buffer
@@ -153,7 +178,7 @@
*/
SkMatrix m;
- const SkRect imageDstRect = SkRect::MakeIWH(imageSrcRect.width(), imageSrcRect.height());
+ const SkRect imageDstRect = SkRect::Make(imageWH);
const float px = imageDstRect.centerX();
const float py = imageDstRect.centerY();
if (windowTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
diff --git a/packages/SystemUI/docs/camera.md b/packages/SystemUI/docs/camera.md
index cabc65c..a1c8458 100644
--- a/packages/SystemUI/docs/camera.md
+++ b/packages/SystemUI/docs/camera.md
@@ -1,34 +1,23 @@
# How double-click power launches the camera
-
-_as of august 2020_
-
+_Last update: July 2022_
## Sequence of events
-
-
-
-1. [PhoneWindowManager.java](/services/core/java/com/android/server/policy/PhoneWindowManager.java) is responsible for all power button presses (see `interceptPowerKeyDown`).
-2. Even though PWMgr has a lot of logic to detect all manner of power button multipresses and gestures, it also checks with GestureLauncherService, which is also [offered the chance](/services/core/java/com/android/server/policy/PhoneWindowManager.java#943) to [intercept](/services/core/java/com/android/server/GestureLauncherService.java#358) the power key.
-3. GLS is responsible for the camera timeout, and if it detects one, it [forwards it to the StatusBarManagerService](/services/core/java/com/android/server/GestureLauncherService.java#475) (which hands it off to SystemUI).
-4. Inside SystemUI, [onCameraLaunchDetected](/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java#3927) looks at the keyguard state and determines
+1. [PhoneWindowManager.java](/services/core/java/com/android/server/policy/PhoneWindowManager.java) is responsible for all power button presses (see `interceptPowerKeyDown`)
+2. Even though `PhoneWindowManager` has a lot of logic to detect all manner of power button multi-presses and gestures, it also checks with `GestureLauncherService`, which is also [offered the chance](/services/core/java/com/android/server/policy/PhoneWindowManager.java#943) to [intercept](/services/core/java/com/android/server/GestureLauncherService.java) the power key
+3. `GestureLauncherService` is responsible for the camera timeout, and if it detects one, it [forwards it to the StatusBarManagerService](/services/core/java/com/android/server/GestureLauncherService.java) (which hands it off to SystemUI)
+4. Inside SystemUI, `onCameraLaunchDetected` in [CentralSurfacesCommandQueueCallbacks.java](/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesCommandQueueCallbacks.java) looks at the keyguard state and determines
1. whether the camera is even allowed
2. whether the screen is on; if not, we need to delay until that happens
3. whether the device is locked (defined as "keyguard is showing").
-5. If the device is unlocked (no keyguard), the camera is launched immediately. [Callsite in onCameraLaunchGestureDetected](/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java#4047).
-6. If the keyguard is up, however, [KeyguardBottomAreaView.launchCamera](/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java#477) takes over to handle the "secure camera" (a different intent, usually directing to the same app, but giving that app the cue to not allow access to the photo roll, etc).
-7. If the intent [would have to launch a resolver](/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java#480) (the user has multiple cameras installed and hasn’t chosen one to always launch for the `SECURE_CAMERA_INTENT`),
- 1. In order to show the resolver, the lockscreen "bouncer" (authentication method) [is first presented](/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java#523).
-8. Otherwise (just one secure camera), [it is launched](/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java#501) (with some window animation gymnastics).
+5. If the device is unlocked (no keyguard), the camera is launched immediately
+6. If the keyguard is up, however, [NotificationPanelViewController.launchCamera](/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelViewController.java) takes over to handle the "secure camera" (a different intent, usually directing to the same app, but giving that app the cue to not allow access to the photo roll, etc).
+7. If the intent would have to launch a resolver (because the user has multiple camera apps installed and has not chosen one to always launch for the `SECURE_CAMERA_INTENT`, then - in order to show the resolver, the lockscreen "bouncer" (authentication method) is first presented
+8. Otherwise (just one secure camera), it is launched
-
-## Which intent launches?
-
-
-
-* If the keyguard is not showing (device is unlocked)
- * `CameraIntents.getInsecureCameraIntent()`, defined to be `MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA`.
- * [Callsite](/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java#3950) in StatusBar.java.
-* If the keyguard is showing (device locked)
- * [KeyguardBottomAreaView.getCameraIntent()](/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java#366) is consulted, which allows the "keyguard right button" (which we don’t actually show) to control the camera intent. The [default implementation](/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java#831) returns one of `CameraIntents.getInsecureCameraIntent()` or `CameraIntents.getSecureCameraIntent()`, which are `MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA` and `MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE`, respectively.
- * [Callsite](/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java#523) in KeyguardBottomAreaView.java.
-* Note that starting in Android 12, as required by some OEMs, if the special string resource `config_cameraGesturePackage` is nonempty, this will be treated as a package name to be added to the insecure camera intent, constraining the invocation to that single app and typically preventing implicit intent resolution. This package must be on the device or the camera gesture will no longer work properly.
\ No newline at end of file
+## Which intent launches the camera app?
+[CameraGestureHelper](/packages/SystemUI/src/com/android/systemui/camera/CameraGestureHelper.kt) encapsulate this logic. Roughly:
+* If the keyguard is not showing (device is unlocked)
+ * `CameraIntents.getInsecureCameraIntent()`, defined to be `MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA`.
+* If the keyguard is showing (device is locked)
+ * one of `CameraIntents.getInsecureCameraIntent()` or `CameraIntents.getSecureCameraIntent()`, which are `MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA` and `MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE`, respectively
+* Note that starting in Android 12, as required by some OEMs, if the special string resource `config_cameraGesturePackage` is nonempty, this will be treated as a package name to be added to the insecure camera intent, constraining the invocation to that single app and typically preventing implicit intent resolution. This package must be on the device or the camera gesture will no longer work properly
diff --git a/packages/SystemUI/res-keyguard/layout/keyguard_bouncer_user_switcher.xml b/packages/SystemUI/res-keyguard/layout/keyguard_bouncer_user_switcher.xml
index 36035fc..01e3de2 100644
--- a/packages/SystemUI/res-keyguard/layout/keyguard_bouncer_user_switcher.xml
+++ b/packages/SystemUI/res-keyguard/layout/keyguard_bouncer_user_switcher.xml
@@ -45,6 +45,7 @@
style="@style/Bouncer.UserSwitcher.Spinner.Header"
android:clickable="false"
android:id="@+id/user_switcher_header"
+ android:textDirection="locale"
android:layout_width="@dimen/bouncer_user_switcher_width"
android:layout_height="wrap_content" />
</LinearLayout>>
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java
index db41601..a66dc77 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteTransitionCompat.java
@@ -427,18 +427,14 @@
mPipTransaction = null;
}
}
- // Release surface references now. This is apparently to free GPU
- // memory while doing quick operations (eg. during CTS).
- for (int i = 0; i < mLeashMap.size(); ++i) {
- if (mLeashMap.keyAt(i) == mLeashMap.valueAt(i)) continue;
- t.remove(mLeashMap.valueAt(i));
- }
try {
mFinishCB.onTransitionFinished(wct.isEmpty() ? null : wct, t);
} catch (RemoteException e) {
Log.e("RemoteTransitionCompat", "Failed to call animation finish callback", e);
t.apply();
}
+ // Only release the non-local created surface references. The animator is responsible
+ // for releasing the leashes created by local.
for (int i = 0; i < mInfo.getChanges().size(); ++i) {
mInfo.getChanges().get(i).getLeash().release();
}
diff --git a/packages/SystemUI/src/com/android/systemui/camera/CameraGestureHelper.kt b/packages/SystemUI/src/com/android/systemui/camera/CameraGestureHelper.kt
index 4986fe8..99267e8 100644
--- a/packages/SystemUI/src/com/android/systemui/camera/CameraGestureHelper.kt
+++ b/packages/SystemUI/src/com/android/systemui/camera/CameraGestureHelper.kt
@@ -125,6 +125,13 @@
// launched from behind the lock-screen.
activityStarter.startActivity(intent, false /* dismissShade */)
}
+
+ // Call this to make sure that the keyguard returns if the app that is being launched
+ // crashes after a timeout.
+ centralSurfaces.startLaunchTransitionTimeout()
+ // Call this to make sure the keyguard is ready to be dismissed once the next intent is
+ // handled by the OS (in our case it is the activity we started right above)
+ centralSurfaces.readyForKeyguardDone()
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
index a146340..2214287 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
@@ -398,7 +398,14 @@
if (child instanceof ActivatableNotificationView) {
ActivatableNotificationView anv =
(ActivatableNotificationView) child;
- updateCornerRoundnessOnScroll(anv, viewStart, shelfStart);
+ // Because we show whole notifications on the lockscreen, the bottom notification is
+ // always "just about to enter the shelf" by normal scrolling rules. This is fine
+ // if the shelf is visible, but if the shelf is hidden, it causes incorrect curling.
+ // notificationClipEnd handles the discrepancy between a visible and hidden shelf,
+ // so we use that when on the keyguard (and while animating away) to reduce curling.
+ final float keyguardSafeShelfStart =
+ mAmbientState.isOnKeyguard() ? notificationClipEnd : shelfStart;
+ updateCornerRoundnessOnScroll(anv, viewStart, keyguardSafeShelfStart);
}
}
diff --git a/services/core/java/com/android/server/clipboard/ClipboardService.java b/services/core/java/com/android/server/clipboard/ClipboardService.java
index 61350bb..076ac2b 100644
--- a/services/core/java/com/android/server/clipboard/ClipboardService.java
+++ b/services/core/java/com/android/server/clipboard/ClipboardService.java
@@ -215,9 +215,12 @@
private class ListenerInfo {
final int mUid;
final String mPackageName;
- ListenerInfo(int uid, String packageName) {
+ final String mAttributionTag;
+
+ ListenerInfo(int uid, String packageName, String attributionTag) {
mUid = uid;
mPackageName = packageName;
+ mAttributionTag = attributionTag;
}
}
@@ -355,27 +358,43 @@
}
@Override
- public void setPrimaryClip(ClipData clip, String callingPackage, @UserIdInt int userId) {
- checkAndSetPrimaryClip(clip, callingPackage, userId, callingPackage);
+ public void setPrimaryClip(
+ ClipData clip,
+ String callingPackage,
+ String attributionTag,
+ @UserIdInt int userId) {
+ checkAndSetPrimaryClip(clip, callingPackage, attributionTag, userId, callingPackage);
}
@Override
public void setPrimaryClipAsPackage(
- ClipData clip, String callingPackage, @UserIdInt int userId, String sourcePackage) {
+ ClipData clip,
+ String callingPackage,
+ String attributionTag,
+ @UserIdInt int userId,
+ String sourcePackage) {
getContext().enforceCallingOrSelfPermission(Manifest.permission.SET_CLIP_SOURCE,
"Requires SET_CLIP_SOURCE permission");
- checkAndSetPrimaryClip(clip, callingPackage, userId, sourcePackage);
+ checkAndSetPrimaryClip(clip, callingPackage, attributionTag, userId, sourcePackage);
}
private void checkAndSetPrimaryClip(
- ClipData clip, String callingPackage, @UserIdInt int userId, String sourcePackage) {
+ ClipData clip,
+ String callingPackage,
+ String attributionTag,
+ @UserIdInt int userId,
+ String sourcePackage) {
if (clip == null || clip.getItemCount() <= 0) {
throw new IllegalArgumentException("No items");
}
final int intendingUid = getIntendingUid(callingPackage, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
- if (!clipboardAccessAllowed(AppOpsManager.OP_WRITE_CLIPBOARD, callingPackage,
- intendingUid, intendingUserId)) {
+ if (!clipboardAccessAllowed(
+ AppOpsManager.OP_WRITE_CLIPBOARD,
+ callingPackage,
+ attributionTag,
+ intendingUid,
+ intendingUserId)) {
return;
}
checkDataOwner(clip, intendingUid);
@@ -392,8 +411,13 @@
PROPERTY_AUTO_CLEAR_ENABLED, true)) {
mClipboardClearHandler.removeEqualMessages(ClipboardClearHandler.MSG_CLEAR,
userId);
- Message clearMessage = Message.obtain(mClipboardClearHandler,
- ClipboardClearHandler.MSG_CLEAR, userId, intendingUid, userId);
+ Message clearMessage =
+ Message.obtain(
+ mClipboardClearHandler,
+ ClipboardClearHandler.MSG_CLEAR,
+ userId,
+ intendingUid,
+ userId);
mClipboardClearHandler.sendMessageDelayed(clearMessage,
getTimeoutForAutoClear());
}
@@ -409,11 +433,16 @@
}
@Override
- public void clearPrimaryClip(String callingPackage, @UserIdInt int userId) {
+ public void clearPrimaryClip(
+ String callingPackage, String attributionTag, @UserIdInt int userId) {
final int intendingUid = getIntendingUid(callingPackage, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
- if (!clipboardAccessAllowed(AppOpsManager.OP_WRITE_CLIPBOARD, callingPackage,
- intendingUid, intendingUserId)) {
+ if (!clipboardAccessAllowed(
+ AppOpsManager.OP_WRITE_CLIPBOARD,
+ callingPackage,
+ attributionTag,
+ intendingUid,
+ intendingUserId)) {
return;
}
synchronized (mLock) {
@@ -424,11 +453,15 @@
}
@Override
- public ClipData getPrimaryClip(String pkg, @UserIdInt int userId) {
+ public ClipData getPrimaryClip(String pkg, String attributionTag, @UserIdInt int userId) {
final int intendingUid = getIntendingUid(pkg, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
- if (!clipboardAccessAllowed(AppOpsManager.OP_READ_CLIPBOARD, pkg,
- intendingUid, intendingUserId)
+ if (!clipboardAccessAllowed(
+ AppOpsManager.OP_READ_CLIPBOARD,
+ pkg,
+ attributionTag,
+ intendingUid,
+ intendingUserId)
|| isDeviceLocked(intendingUserId)) {
return null;
}
@@ -453,12 +486,17 @@
}
@Override
- public ClipDescription getPrimaryClipDescription(String callingPackage,
- @UserIdInt int userId) {
+ public ClipDescription getPrimaryClipDescription(
+ String callingPackage, String attributionTag, @UserIdInt int userId) {
final int intendingUid = getIntendingUid(callingPackage, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
- if (!clipboardAccessAllowed(AppOpsManager.OP_READ_CLIPBOARD, callingPackage,
- intendingUid, intendingUserId, false)
+ if (!clipboardAccessAllowed(
+ AppOpsManager.OP_READ_CLIPBOARD,
+ callingPackage,
+ attributionTag,
+ intendingUid,
+ intendingUserId,
+ false)
|| isDeviceLocked(intendingUserId)) {
return null;
}
@@ -470,11 +508,17 @@
}
@Override
- public boolean hasPrimaryClip(String callingPackage, @UserIdInt int userId) {
+ public boolean hasPrimaryClip(
+ String callingPackage, String attributionTag, @UserIdInt int userId) {
final int intendingUid = getIntendingUid(callingPackage, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
- if (!clipboardAccessAllowed(AppOpsManager.OP_READ_CLIPBOARD, callingPackage,
- intendingUid, intendingUserId, false)
+ if (!clipboardAccessAllowed(
+ AppOpsManager.OP_READ_CLIPBOARD,
+ callingPackage,
+ attributionTag,
+ intendingUid,
+ intendingUserId,
+ false)
|| isDeviceLocked(intendingUserId)) {
return false;
}
@@ -484,19 +528,28 @@
}
@Override
- public void addPrimaryClipChangedListener(IOnPrimaryClipChangedListener listener,
- String callingPackage, @UserIdInt int userId) {
+ public void addPrimaryClipChangedListener(
+ IOnPrimaryClipChangedListener listener,
+ String callingPackage,
+ String attributionTag,
+ @UserIdInt int userId) {
final int intendingUid = getIntendingUid(callingPackage, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
synchronized (mLock) {
- getClipboardLocked(intendingUserId).primaryClipListeners.register(listener,
- new ListenerInfo(intendingUid, callingPackage));
+ getClipboardLocked(intendingUserId)
+ .primaryClipListeners
+ .register(
+ listener,
+ new ListenerInfo(intendingUid, callingPackage, attributionTag));
}
}
@Override
- public void removePrimaryClipChangedListener(IOnPrimaryClipChangedListener listener,
- String callingPackage, @UserIdInt int userId) {
+ public void removePrimaryClipChangedListener(
+ IOnPrimaryClipChangedListener listener,
+ String callingPackage,
+ String attributionTag,
+ @UserIdInt int userId) {
final int intendingUserId = getIntendingUserId(callingPackage, userId);
synchronized (mLock) {
getClipboardLocked(intendingUserId).primaryClipListeners.unregister(listener);
@@ -504,11 +557,16 @@
}
@Override
- public boolean hasClipboardText(String callingPackage, int userId) {
+ public boolean hasClipboardText(String callingPackage, String attributionTag, int userId) {
final int intendingUid = getIntendingUid(callingPackage, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
- if (!clipboardAccessAllowed(AppOpsManager.OP_READ_CLIPBOARD, callingPackage,
- intendingUid, intendingUserId, false)
+ if (!clipboardAccessAllowed(
+ AppOpsManager.OP_READ_CLIPBOARD,
+ callingPackage,
+ attributionTag,
+ intendingUid,
+ intendingUserId,
+ false)
|| isDeviceLocked(intendingUserId)) {
return false;
}
@@ -523,13 +581,19 @@
}
@Override
- public String getPrimaryClipSource(String callingPackage, int userId) {
+ public String getPrimaryClipSource(
+ String callingPackage, String attributionTag, int userId) {
getContext().enforceCallingOrSelfPermission(Manifest.permission.SET_CLIP_SOURCE,
"Requires SET_CLIP_SOURCE permission");
final int intendingUid = getIntendingUid(callingPackage, userId);
final int intendingUserId = UserHandle.getUserId(intendingUid);
- if (!clipboardAccessAllowed(AppOpsManager.OP_READ_CLIPBOARD, callingPackage,
- intendingUid, intendingUserId, false)
+ if (!clipboardAccessAllowed(
+ AppOpsManager.OP_READ_CLIPBOARD,
+ callingPackage,
+ attributionTag,
+ intendingUid,
+ intendingUserId,
+ false)
|| isDeviceLocked(intendingUserId)) {
return null;
}
@@ -718,8 +782,12 @@
ListenerInfo li = (ListenerInfo)
clipboard.primaryClipListeners.getBroadcastCookie(i);
- if (clipboardAccessAllowed(AppOpsManager.OP_READ_CLIPBOARD, li.mPackageName,
- li.mUid, UserHandle.getUserId(li.mUid))) {
+ if (clipboardAccessAllowed(
+ AppOpsManager.OP_READ_CLIPBOARD,
+ li.mPackageName,
+ li.mAttributionTag,
+ li.mUid,
+ UserHandle.getUserId(li.mUid))) {
clipboard.primaryClipListeners.getBroadcastItem(i)
.dispatchPrimaryClipChanged();
}
@@ -965,13 +1033,18 @@
}
}
- private boolean clipboardAccessAllowed(int op, String callingPackage, int uid,
- @UserIdInt int userId) {
- return clipboardAccessAllowed(op, callingPackage, uid, userId, true);
+ private boolean clipboardAccessAllowed(
+ int op, String callingPackage, String attributionTag, int uid, @UserIdInt int userId) {
+ return clipboardAccessAllowed(op, callingPackage, attributionTag, uid, userId, true);
}
- private boolean clipboardAccessAllowed(int op, String callingPackage, int uid,
- @UserIdInt int userId, boolean shouldNoteOp) {
+ private boolean clipboardAccessAllowed(
+ int op,
+ String callingPackage,
+ String attributionTag,
+ int uid,
+ @UserIdInt int userId,
+ boolean shouldNoteOp) {
boolean allowed;
@@ -1040,7 +1113,7 @@
// Finally, check the app op.
int appOpsResult;
if (shouldNoteOp) {
- appOpsResult = mAppOps.noteOp(op, uid, callingPackage);
+ appOpsResult = mAppOps.noteOp(op, uid, callingPackage, attributionTag, null);
} else {
appOpsResult = mAppOps.checkOp(op, uid, callingPackage);
}
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index fdb31b2e..5787efb 100755
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -7030,6 +7030,7 @@
@GuardedBy("mNotificationLock")
void snoozeLocked(NotificationRecord r) {
+ final List<NotificationRecord> recordsToSnooze = new ArrayList<>();
if (r.getSbn().isGroup()) {
final List<NotificationRecord> groupNotifications =
findCurrentAndSnoozedGroupNotificationsLocked(
@@ -7038,8 +7039,8 @@
if (r.getNotification().isGroupSummary()) {
// snooze all children
for (int i = 0; i < groupNotifications.size(); i++) {
- if (mKey != groupNotifications.get(i).getKey()) {
- snoozeNotificationLocked(groupNotifications.get(i));
+ if (!mKey.equals(groupNotifications.get(i).getKey())) {
+ recordsToSnooze.add(groupNotifications.get(i));
}
}
} else {
@@ -7049,8 +7050,8 @@
if (groupNotifications.size() == 2) {
// snooze summary and the one child
for (int i = 0; i < groupNotifications.size(); i++) {
- if (mKey != groupNotifications.get(i).getKey()) {
- snoozeNotificationLocked(groupNotifications.get(i));
+ if (!mKey.equals(groupNotifications.get(i).getKey())) {
+ recordsToSnooze.add(groupNotifications.get(i));
}
}
}
@@ -7058,7 +7059,15 @@
}
}
// snooze the notification
- snoozeNotificationLocked(r);
+ recordsToSnooze.add(r);
+
+ if (mSnoozeHelper.canSnooze(recordsToSnooze.size())) {
+ for (int i = 0; i < recordsToSnooze.size(); i++) {
+ snoozeNotificationLocked(recordsToSnooze.get(i));
+ }
+ } else {
+ Log.w(TAG, "Cannot snooze " + r.getKey() + ": too many snoozed notifications");
+ }
}
diff --git a/services/core/java/com/android/server/notification/SnoozeHelper.java b/services/core/java/com/android/server/notification/SnoozeHelper.java
index 7f265df..15d7c1e 100644
--- a/services/core/java/com/android/server/notification/SnoozeHelper.java
+++ b/services/core/java/com/android/server/notification/SnoozeHelper.java
@@ -62,6 +62,8 @@
public class SnoozeHelper {
public static final int XML_SNOOZED_NOTIFICATION_VERSION = 1;
+ static final int CONCURRENT_SNOOZE_LIMIT = 500;
+
protected static final String XML_TAG_NAME = "snoozed-notifications";
private static final String XML_SNOOZED_NOTIFICATION = "notification";
@@ -135,6 +137,15 @@
}
}
+ protected boolean canSnooze(int numberToSnooze) {
+ synchronized (mLock) {
+ if ((mPackages.size() + numberToSnooze) > CONCURRENT_SNOOZE_LIMIT) {
+ return false;
+ }
+ }
+ return true;
+ }
+
@NonNull
protected Long getSnoozeTimeForUnpostedNotification(int userId, String pkg, String key) {
Long time = null;
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index a9b154c..d4155d1 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -5338,11 +5338,7 @@
ANIMATION_TYPE_APP_TRANSITION | ANIMATION_TYPE_WINDOW_ANIMATION
| ANIMATION_TYPE_RECENTS);
if (!delayed) {
- // We aren't delayed anything, but exiting windows rely on the animation finished
- // callback being called in case the ActivityRecord was pretending to be delayed,
- // which we might have done because we were in closing/opening apps list.
if (!usingShellTransitions) {
- onAnimationFinished(ANIMATION_TYPE_APP_TRANSITION, null /* AnimationAdapter */);
if (visible) {
// The token was made immediately visible, there will be no entrance animation.
// We need to inform the client the enter animation was finished.
@@ -7737,9 +7733,6 @@
// relatively fixed.
overrideConfig.colorMode = fullConfig.colorMode;
overrideConfig.densityDpi = fullConfig.densityDpi;
- // The smallest screen width is the short side of screen bounds. Because the bounds
- // and density won't be changed, smallestScreenWidthDp is also fixed.
- overrideConfig.smallestScreenWidthDp = fullConfig.smallestScreenWidthDp;
if (info.isFixedOrientation()) {
// lock rotation too. When in size-compat, onConfigurationChanged will watch for and
// apply runtime rotation changes.
@@ -7836,7 +7829,7 @@
// computed accordingly.
if (!matchParentBounds()) {
getTaskFragment().computeConfigResourceOverrides(resolvedConfig,
- newParentConfiguration);
+ newParentConfiguration, areBoundsLetterboxed());
}
// If activity in fullscreen mode is letterboxed because of fixed orientation then bounds
// are already calculated in resolveFixedOrientationConfiguration.
@@ -8007,7 +8000,8 @@
}
// Since bounds has changed, the configuration needs to be computed accordingly.
- getTaskFragment().computeConfigResourceOverrides(resolvedConfig, newParentConfiguration);
+ getTaskFragment().computeConfigResourceOverrides(resolvedConfig, newParentConfiguration,
+ areBoundsLetterboxed());
}
void recomputeConfiguration() {
@@ -8223,7 +8217,7 @@
// Calculate app bounds using fixed orientation bounds because they will be needed later
// for comparison with size compat app bounds in {@link resolveSizeCompatModeConfiguration}.
getTaskFragment().computeConfigResourceOverrides(getResolvedOverrideConfiguration(),
- newParentConfig);
+ newParentConfig, mCompatDisplayInsets, areBoundsLetterboxed());
mLetterboxBoundsForFixedOrientationAndAspectRatio = new Rect(resolvedBounds);
}
@@ -8251,7 +8245,7 @@
// Compute the configuration based on the resolved bounds. If aspect ratio doesn't
// restrict, the bounds should be the requested override bounds.
getTaskFragment().computeConfigResourceOverrides(resolvedConfig, newParentConfiguration,
- getFixedRotationTransformDisplayInfo());
+ getFixedRotationTransformDisplayInfo(), areBoundsLetterboxed());
}
}
@@ -8315,7 +8309,7 @@
// are calculated in compat container space. The actual position on screen will be applied
// later, so the calculation is simpler that doesn't need to involve offset from parent.
getTaskFragment().computeConfigResourceOverrides(resolvedConfig, newParentConfiguration,
- mCompatDisplayInsets);
+ mCompatDisplayInsets, areBoundsLetterboxed());
// Use current screen layout as source because the size of app is independent to parent.
resolvedConfig.screenLayout = TaskFragment.computeScreenLayoutOverride(
getConfiguration().screenLayout, resolvedConfig.screenWidthDp,
diff --git a/services/core/java/com/android/server/wm/BackNavigationController.java b/services/core/java/com/android/server/wm/BackNavigationController.java
index d07cc68..9295c18 100644
--- a/services/core/java/com/android/server/wm/BackNavigationController.java
+++ b/services/core/java/com/android/server/wm/BackNavigationController.java
@@ -112,6 +112,7 @@
RemoteAnimationTarget topAppTarget = null;
int prevTaskId;
int prevUserId;
+ boolean prepareAnimation;
BackNavigationInfo.Builder infoBuilder = new BackNavigationInfo.Builder();
synchronized (wmService.mGlobalLock) {
@@ -257,7 +258,8 @@
BackNavigationInfo.typeToString(backType));
// For now, we only animate when going home.
- boolean prepareAnimation = backType == BackNavigationInfo.TYPE_RETURN_TO_HOME
+ prepareAnimation = backType == BackNavigationInfo.TYPE_RETURN_TO_HOME
+ && requestAnimation
// Only create a new leash if no leash has been created.
// Otherwise return null for animation target to avoid conflict.
&& !removedWindowContainer.hasCommittedReparentToAnimationLeash();
@@ -292,7 +294,7 @@
}
// Special handling for back to home animation
- if (backType == BackNavigationInfo.TYPE_RETURN_TO_HOME && requestAnimation
+ if (backType == BackNavigationInfo.TYPE_RETURN_TO_HOME && prepareAnimation
&& prevTask != null) {
currentTask.mBackGestureStarted = true;
// Make launcher show from behind by marking its top activity as visible and
@@ -347,7 +349,7 @@
Task finalTask = currentTask;
RemoteCallback onBackNavigationDone = new RemoteCallback(result -> onBackNavigationDone(
result, finalRemovedWindowContainer, finalBackType, finalTask,
- finalprevActivity, requestAnimation));
+ finalprevActivity, prepareAnimation));
infoBuilder.setOnBackNavigationDone(onBackNavigationDone);
}
@@ -381,14 +383,14 @@
private void onBackNavigationDone(
Bundle result, WindowContainer<?> windowContainer, int backType,
- Task task, ActivityRecord prevActivity, boolean requestAnimation) {
+ Task task, ActivityRecord prevActivity, boolean prepareAnimation) {
SurfaceControl surfaceControl = windowContainer.getSurfaceControl();
boolean triggerBack = result != null && result.getBoolean(
BackNavigationInfo.KEY_TRIGGER_BACK);
ProtoLog.d(WM_DEBUG_BACK_PREVIEW, "onBackNavigationDone backType=%s, "
+ "task=%s, prevActivity=%s", backType, task, prevActivity);
- if (backType == BackNavigationInfo.TYPE_RETURN_TO_HOME && requestAnimation) {
+ if (backType == BackNavigationInfo.TYPE_RETURN_TO_HOME && prepareAnimation) {
if (triggerBack) {
if (surfaceControl != null && surfaceControl.isValid()) {
// When going back to home, hide the task surface before it is re-parented to
diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java
index f8a9d46..21c5886 100644
--- a/services/core/java/com/android/server/wm/TaskFragment.java
+++ b/services/core/java/com/android/server/wm/TaskFragment.java
@@ -1957,29 +1957,37 @@
void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
@NonNull Configuration parentConfig) {
computeConfigResourceOverrides(inOutConfig, parentConfig, null /* overrideDisplayInfo */,
- null /* compatInsets */);
+ null /* compatInsets */, false /* areBoundsLetterboxed */);
}
void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
- @NonNull Configuration parentConfig, @Nullable DisplayInfo overrideDisplayInfo) {
+ @NonNull Configuration parentConfig, boolean areBoundsLetterboxed) {
+ computeConfigResourceOverrides(inOutConfig, parentConfig, null /* overrideDisplayInfo */,
+ null /* compatInsets */, areBoundsLetterboxed);
+ }
+
+ void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
+ @NonNull Configuration parentConfig, @Nullable DisplayInfo overrideDisplayInfo,
+ boolean areBoundsLetterboxed) {
if (overrideDisplayInfo != null) {
// Make sure the screen related configs can be computed by the provided display info.
inOutConfig.screenLayout = Configuration.SCREENLAYOUT_UNDEFINED;
invalidateAppBoundsConfig(inOutConfig);
}
computeConfigResourceOverrides(inOutConfig, parentConfig, overrideDisplayInfo,
- null /* compatInsets */);
+ null /* compatInsets */, areBoundsLetterboxed);
}
void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
@NonNull Configuration parentConfig,
- @Nullable ActivityRecord.CompatDisplayInsets compatInsets) {
+ @Nullable ActivityRecord.CompatDisplayInsets compatInsets,
+ boolean areBoundsLetterboxed) {
if (compatInsets != null) {
// Make sure the app bounds can be computed by the compat insets.
invalidateAppBoundsConfig(inOutConfig);
}
computeConfigResourceOverrides(inOutConfig, parentConfig, null /* overrideDisplayInfo */,
- compatInsets);
+ compatInsets, areBoundsLetterboxed);
}
/**
@@ -2006,7 +2014,8 @@
**/
void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
@NonNull Configuration parentConfig, @Nullable DisplayInfo overrideDisplayInfo,
- @Nullable ActivityRecord.CompatDisplayInsets compatInsets) {
+ @Nullable ActivityRecord.CompatDisplayInsets compatInsets,
+ boolean areBoundsLetterboxed) {
int windowingMode = inOutConfig.windowConfiguration.getWindowingMode();
if (windowingMode == WINDOWING_MODE_UNDEFINED) {
windowingMode = parentConfig.windowConfiguration.getWindowingMode();
@@ -2113,6 +2122,7 @@
: overrideScreenHeightDp;
}
+ // TODO(b/238331848): Consider simplifying logic that computes smallestScreenWidthDp.
if (inOutConfig.smallestScreenWidthDp
== Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
// When entering to or exiting from Pip, the PipTaskOrganizer will set the
@@ -2128,9 +2138,10 @@
// task, because they should not be affected by insets.
inOutConfig.smallestScreenWidthDp = (int) (0.5f
+ Math.min(mTmpFullBounds.width(), mTmpFullBounds.height()) / density);
- } else if (isEmbedded()) {
- // For embedded TFs, the smallest width should be updated. Otherwise, inherit
- // from the parent task would result in applications loaded wrong resource.
+ } else if (isEmbedded() || areBoundsLetterboxed || customContainerPolicy) {
+ // For embedded TFs and activities that are letteboxed or eligible for size
+ // compat mode, the smallest width should be updated. Otherwise, inherit from
+ // the parent task would result in applications loaded wrong resource.
inOutConfig.smallestScreenWidthDp =
Math.min(inOutConfig.screenWidthDp, inOutConfig.screenHeightDp);
}
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 91afa04..19b3384 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -3760,6 +3760,15 @@
* hierarchy change implies a configuration change.
*/
private void onSyncReparent(WindowContainer oldParent, WindowContainer newParent) {
+ // Check if this is changing displays. If so, mark the old display as "ready" for
+ // transitions. This is to work around the problem where setting readiness against this
+ // container will only set the new display as ready and leave the old display as unready.
+ if (mSyncState != SYNC_STATE_NONE && oldParent != null
+ && oldParent.getDisplayContent() != null && (newParent == null
+ || oldParent.getDisplayContent() != newParent.getDisplayContent())) {
+ mTransitionController.setReady(oldParent.getDisplayContent());
+ }
+
if (newParent == null || newParent.mSyncState == SYNC_STATE_NONE) {
if (mSyncState == SYNC_STATE_NONE) {
return;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 22721a1..b1b323b 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -3380,19 +3380,80 @@
}
@Test
- public void testSnoozeRunnable_reSnoozeASingleSnoozedNotification() throws Exception {
+ public void testSnoozeRunnable_tooManySnoozed_singleNotification() {
+ final NotificationRecord notification = generateNotificationRecord(
+ mTestNotificationChannel, 1, null, true);
+ mService.addNotification(notification);
+
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
+ when(mSnoozeHelper.canSnooze(1)).thenReturn(false);
+
+ NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
+ mService.new SnoozeNotificationRunnable(
+ notification.getKey(), 100, null);
+ snoozeNotificationRunnable.run();
+
+ verify(mSnoozeHelper, never()).snooze(any(NotificationRecord.class), anyLong());
+ assertThat(mService.getNotificationRecordCount()).isEqualTo(1);
+ }
+
+ @Test
+ public void testSnoozeRunnable_tooManySnoozed_singleGroupChildNotification() {
+ final NotificationRecord notification = generateNotificationRecord(
+ mTestNotificationChannel, 1, "group", true);
+ final NotificationRecord notificationChild = generateNotificationRecord(
+ mTestNotificationChannel, 1, "group", false);
+ mService.addNotification(notification);
+ mService.addNotification(notificationChild);
+
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
+ when(mSnoozeHelper.canSnooze(2)).thenReturn(false);
+
+ NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
+ mService.new SnoozeNotificationRunnable(
+ notificationChild.getKey(), 100, null);
+ snoozeNotificationRunnable.run();
+
+ verify(mSnoozeHelper, never()).snooze(any(NotificationRecord.class), anyLong());
+ assertThat(mService.getNotificationRecordCount()).isEqualTo(2);
+ }
+
+ @Test
+ public void testSnoozeRunnable_tooManySnoozed_summaryNotification() {
+ final NotificationRecord notification = generateNotificationRecord(
+ mTestNotificationChannel, 1, "group", true);
+ final NotificationRecord notificationChild = generateNotificationRecord(
+ mTestNotificationChannel, 12, "group", false);
+ final NotificationRecord notificationChild2 = generateNotificationRecord(
+ mTestNotificationChannel, 13, "group", false);
+ mService.addNotification(notification);
+ mService.addNotification(notificationChild);
+ mService.addNotification(notificationChild2);
+
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
+ when(mSnoozeHelper.canSnooze(3)).thenReturn(false);
+
+ NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
+ mService.new SnoozeNotificationRunnable(
+ notification.getKey(), 100, null);
+ snoozeNotificationRunnable.run();
+
+ verify(mSnoozeHelper, never()).snooze(any(NotificationRecord.class), anyLong());
+ assertThat(mService.getNotificationRecordCount()).isEqualTo(3);
+ }
+
+ @Test
+ public void testSnoozeRunnable_reSnoozeASingleSnoozedNotification() {
final NotificationRecord notification = generateNotificationRecord(
mTestNotificationChannel, 1, null, true);
mService.addNotification(notification);
when(mSnoozeHelper.getNotification(any())).thenReturn(notification);
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
notification.getKey(), 100, null);
snoozeNotificationRunnable.run();
- NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable2 =
- mService.new SnoozeNotificationRunnable(
- notification.getKey(), 100, null);
snoozeNotificationRunnable.run();
// snooze twice
@@ -3400,19 +3461,17 @@
}
@Test
- public void testSnoozeRunnable_reSnoozeASnoozedNotificationWithGroupKey() throws Exception {
+ public void testSnoozeRunnable_reSnoozeASnoozedNotificationWithGroupKey() {
final NotificationRecord notification = generateNotificationRecord(
mTestNotificationChannel, 1, "group", true);
mService.addNotification(notification);
when(mSnoozeHelper.getNotification(any())).thenReturn(notification);
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
notification.getKey(), 100, null);
snoozeNotificationRunnable.run();
- NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable2 =
- mService.new SnoozeNotificationRunnable(
- notification.getKey(), 100, null);
snoozeNotificationRunnable.run();
// snooze twice
@@ -3430,6 +3489,7 @@
when(mSnoozeHelper.getNotification(any())).thenReturn(notification);
when(mSnoozeHelper.getNotifications(
anyString(), anyString(), anyInt())).thenReturn(new ArrayList<>());
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
@@ -3439,8 +3499,8 @@
.thenReturn(new ArrayList<>(Arrays.asList(notification, notification2)));
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable2 =
mService.new SnoozeNotificationRunnable(
- notification.getKey(), 100, null);
- snoozeNotificationRunnable.run();
+ notification2.getKey(), 100, null);
+ snoozeNotificationRunnable2.run();
// snooze twice
verify(mSnoozeHelper, times(4)).snooze(any(NotificationRecord.class), anyLong());
@@ -3454,6 +3514,7 @@
mTestNotificationChannel, 2, "group", false);
mService.addNotification(grouped);
mService.addNotification(nonGrouped);
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
@@ -3483,6 +3544,7 @@
mService.addNotification(parent);
mService.addNotification(child);
mService.addNotification(child2);
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
@@ -3504,6 +3566,7 @@
mService.addNotification(parent);
mService.addNotification(child);
mService.addNotification(child2);
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
@@ -3529,6 +3592,7 @@
mTestNotificationChannel, 2, "group", false);
mService.addNotification(parent);
mService.addNotification(child);
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
@@ -3556,6 +3620,7 @@
final NotificationRecord child = generateNotificationRecord(
mTestNotificationChannel, 2, "group", false);
mService.addNotification(child);
+ when(mSnoozeHelper.canSnooze(anyInt())).thenReturn(true);
NotificationManagerService.SnoozeNotificationRunnable snoozeNotificationRunnable =
mService.new SnoozeNotificationRunnable(
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java
index 2ae2ef7..8bead57 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/SnoozeHelperTest.java
@@ -15,6 +15,7 @@
*/
package com.android.server.notification;
+import static com.android.server.notification.SnoozeHelper.CONCURRENT_SNOOZE_LIMIT;
import static com.android.server.notification.SnoozeHelper.EXTRA_KEY;
import static junit.framework.Assert.assertEquals;
@@ -281,6 +282,22 @@
}
@Test
+ public void testSnoozeLimit() {
+ for (int i = 0; i < CONCURRENT_SNOOZE_LIMIT; i++ ) {
+ NotificationRecord r = getNotificationRecord("pkg", i, i+"", UserHandle.SYSTEM);
+
+ assertTrue("cannot snooze record " + i, mSnoozeHelper.canSnooze(1));
+
+ if (i % 2 == 0) {
+ mSnoozeHelper.snooze(r, null);
+ } else {
+ mSnoozeHelper.snooze(r, 9000);
+ }
+ }
+ assertFalse(mSnoozeHelper.canSnooze(1));
+ }
+
+ @Test
public void testCancelByApp() throws Exception {
NotificationRecord r = getNotificationRecord("pkg", 1, "one", UserHandle.SYSTEM);
NotificationRecord r2 = getNotificationRecord("pkg", 2, "two", UserHandle.SYSTEM);
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 0c3b270..3f3d01a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -49,7 +49,6 @@
import static android.os.Process.NOBODY_UID;
import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.InsetsState.ITYPE_IME;
-import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
import static android.view.WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
@@ -2539,21 +2538,6 @@
}
@Test
- public void testStuckExitingWindow() {
- final WindowState closingWindow = createWindow(null, FIRST_APPLICATION_WINDOW,
- "closingWindow");
- closingWindow.mAnimatingExit = true;
- closingWindow.mRemoveOnExit = true;
- closingWindow.mActivityRecord.commitVisibility(
- false /* visible */, true /* performLayout */);
-
- // We pretended that we were running an exit animation, but that should have been cleared up
- // by changing visibility of ActivityRecord
- closingWindow.removeIfPossible();
- assertTrue(closingWindow.mRemoved);
- }
-
- @Test
public void testSetOrientation() {
final ActivityRecord activity = new ActivityBuilder(mAtm).setCreateTask(true).build();
activity.setVisible(true);
@@ -3149,6 +3133,7 @@
mDisplayContent.mOpeningApps.clear();
app.mActivityRecord.commitVisibility(false, false);
app.mActivityRecord.onWindowsGone();
+ mDisplayContent.computeImeTargetIfNeeded(app.mActivityRecord);
assertTrue(app.mActivityRecord.mLastImeShown);
assertTrue(app.mActivityRecord.mImeInsetsFrozenUntilStartInput);
diff --git a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
index 324e244..f2640d2 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -1496,6 +1496,79 @@
}
@Test
+ public void testComputeConfigResourceOverrides_unresizableApp() {
+ // Set up a display in landscape and ignoring orientation request.
+ setUpDisplaySizeWithApp(2800, 1400);
+ mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+
+ prepareUnresizable(mActivity, SCREEN_ORIENTATION_PORTRAIT);
+
+ final Rect activityBounds = new Rect(mActivity.getBounds());
+
+ int originalScreenWidthDp = mActivity.getConfiguration().screenWidthDp;
+ int originalScreenHeighthDp = mActivity.getConfiguration().screenHeightDp;
+
+ // App should launch in fixed orientation letterbox.
+ // Activity bounds should be 700x1400 with the ratio as the display.
+ assertTrue(mActivity.isLetterboxedForFixedOrientationAndAspectRatio());
+ assertFitted();
+ assertEquals(originalScreenWidthDp, mActivity.getConfiguration().smallestScreenWidthDp);
+ assertTrue(originalScreenWidthDp < originalScreenHeighthDp);
+
+ // Rotate display to portrait.
+ rotateDisplay(mActivity.mDisplayContent, ROTATION_90);
+
+ // After we rotate, the activity should go in the size-compat mode and report the same
+ // configuration values.
+ assertScaled();
+ assertEquals(originalScreenWidthDp, mActivity.getConfiguration().smallestScreenWidthDp);
+ assertEquals(originalScreenWidthDp, mActivity.getConfiguration().screenWidthDp);
+ assertEquals(originalScreenHeighthDp, mActivity.getConfiguration().screenHeightDp);
+
+ // Restart activity
+ mActivity.restartProcessIfVisible();
+
+ // Now configuration should be updated
+ assertFitted();
+ assertNotEquals(originalScreenWidthDp, mActivity.getConfiguration().screenWidthDp);
+ assertNotEquals(originalScreenHeighthDp, mActivity.getConfiguration().screenHeightDp);
+ assertEquals(mActivity.getConfiguration().screenWidthDp,
+ mActivity.getConfiguration().smallestScreenWidthDp);
+ }
+
+ @Test
+ public void testComputeConfigResourceOverrides_resizableFixedOrientationActivity() {
+ // Set up a display in landscape and ignoring orientation request.
+ setUpDisplaySizeWithApp(2800, 1400);
+ mActivity.mDisplayContent.setIgnoreOrientationRequest(true /* ignoreOrientationRequest */);
+
+ // Portrait fixed app without max aspect.
+ prepareLimitedBounds(mActivity, SCREEN_ORIENTATION_PORTRAIT, false /* isUnresizable */);
+
+ final Rect activityBounds = new Rect(mActivity.getBounds());
+
+ int originalScreenWidthDp = mActivity.getConfiguration().screenWidthDp;
+ int originalScreenHeighthDp = mActivity.getConfiguration().screenHeightDp;
+
+ // App should launch in fixed orientation letterbox.
+ // Activity bounds should be 700x1400 with the ratio as the display.
+ assertTrue(mActivity.isLetterboxedForFixedOrientationAndAspectRatio());
+ assertFitted();
+ assertEquals(originalScreenWidthDp, mActivity.getConfiguration().smallestScreenWidthDp);
+ assertTrue(originalScreenWidthDp < originalScreenHeighthDp);
+
+ // Rotate display to portrait.
+ rotateDisplay(mActivity.mDisplayContent, ROTATION_90);
+
+ // Now configuration should be updated
+ assertFitted();
+ assertNotEquals(originalScreenWidthDp, mActivity.getConfiguration().screenWidthDp);
+ assertNotEquals(originalScreenHeighthDp, mActivity.getConfiguration().screenHeightDp);
+ assertEquals(mActivity.getConfiguration().screenWidthDp,
+ mActivity.getConfiguration().smallestScreenWidthDp);
+ }
+
+ @Test
public void testSplitAspectRatioForUnresizablePortraitApps() {
// Set up a display in landscape and ignoring orientation request.
int screenWidth = 1600;
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java
index 46e21f1..e2fe1b1 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java
@@ -691,7 +691,8 @@
final ActivityRecord.CompatDisplayInsets compatInsets =
new ActivityRecord.CompatDisplayInsets(
display, activity, /* fixedOrientationBounds= */ null);
- task.computeConfigResourceOverrides(inOutConfig, parentConfig, compatInsets);
+ task.computeConfigResourceOverrides(
+ inOutConfig, parentConfig, compatInsets, /* areBoundsLetterboxed */ true);
assertEquals(largerLandscapeBounds, inOutConfig.windowConfiguration.getAppBounds());
final float density = parentConfig.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
index cfc0da7..446ec8b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
@@ -1003,6 +1003,7 @@
assertTrue(app.mActivityRecord.mImeInsetsFrozenUntilStartInput);
// Verify the IME insets is visible on app, but not for app2 during app task switching.
+ mDisplayContent.computeImeTargetIfNeeded(app.mActivityRecord);
assertTrue(app.getInsetsState().getSource(ITYPE_IME).isVisible());
assertFalse(app2.getInsetsState().getSource(ITYPE_IME).isVisible());
}