1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.server.wm; 18 19 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; 20 import static android.server.wm.ActivityTransitionTests.CustomBackgroundTransitionActivity.BACKGROUND_COLOR_KEY; 21 import static android.server.wm.ActivityTransitionTests.CustomBackgroundTransitionActivity.ENTER_ANIM_KEY; 22 import static android.server.wm.ActivityTransitionTests.CustomBackgroundTransitionActivity.EXIT_ANIM_KEY; 23 import static android.server.wm.ActivityTransitionTests.EdgeExtensionActivity.BOTTOM; 24 import static android.server.wm.ActivityTransitionTests.EdgeExtensionActivity.DIRECTION_KEY; 25 import static android.server.wm.ActivityTransitionTests.EdgeExtensionActivity.LEFT; 26 import static android.server.wm.ActivityTransitionTests.EdgeExtensionActivity.RIGHT; 27 import static android.server.wm.ActivityTransitionTests.EdgeExtensionActivity.TOP; 28 import static android.server.wm.app.Components.TEST_ACTIVITY; 29 import static android.view.Display.DEFAULT_DISPLAY; 30 import static android.view.RoundedCorner.POSITION_BOTTOM_LEFT; 31 import static android.view.RoundedCorner.POSITION_BOTTOM_RIGHT; 32 import static android.view.RoundedCorner.POSITION_TOP_LEFT; 33 import static android.view.RoundedCorner.POSITION_TOP_RIGHT; 34 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; 35 36 import static org.junit.Assert.assertTrue; 37 import static org.junit.Assert.fail; 38 39 import android.app.Activity; 40 import android.app.ActivityOptions; 41 import android.app.Instrumentation; 42 import android.content.BroadcastReceiver; 43 import android.content.ComponentName; 44 import android.content.Context; 45 import android.content.Intent; 46 import android.content.IntentFilter; 47 import android.graphics.Bitmap; 48 import android.graphics.Color; 49 import android.graphics.ColorSpace; 50 import android.graphics.Insets; 51 import android.graphics.Point; 52 import android.graphics.Rect; 53 import android.os.Bundle; 54 import android.os.Handler; 55 import android.os.Looper; 56 import android.os.SystemClock; 57 import android.platform.test.annotations.Presubmit; 58 import android.provider.Settings; 59 import android.server.wm.cts.R; 60 import android.server.wm.settings.SettingsSession; 61 import android.util.Range; 62 import android.view.RoundedCorner; 63 import android.view.View; 64 import android.view.ViewGroup; 65 import android.view.WindowInsets; 66 67 import androidx.annotation.Nullable; 68 import androidx.test.platform.app.InstrumentationRegistry; 69 70 import org.junit.After; 71 import org.junit.Before; 72 import org.junit.ClassRule; 73 import org.junit.Test; 74 import org.junit.rules.TestRule; 75 76 import java.io.IOException; 77 import java.util.ArrayList; 78 import java.util.concurrent.CountDownLatch; 79 import java.util.concurrent.TimeUnit; 80 import java.util.concurrent.atomic.AtomicLong; 81 import java.util.function.Function; 82 83 /** 84 * <p>Build/Install/Run: 85 * atest CtsWindowManagerDeviceTestCases:ActivityTransitionTests 86 */ 87 @Presubmit 88 public class ActivityTransitionTests extends ActivityManagerTestBase { 89 // Duration of the R.anim.alpha animation. 90 private static final long CUSTOM_ANIMATION_DURATION = 2000L; 91 92 // Allowable range with error error for the R.anim.alpha animation duration. 93 private static final Range<Long> CUSTOM_ANIMATION_DURATION_RANGE = new Range<>( 94 CUSTOM_ANIMATION_DURATION - 200L, CUSTOM_ANIMATION_DURATION + 1000L); 95 96 static final String TEST_METHOD_KEY = "test_method_key"; 97 static final String TRANSITION_TYPE_KEY = "transition_type_key"; 98 99 static final int TEST_METHOD_OVERRIDE_PENDING_TRANSITION = 1; 100 static final int TEST_METHOD_OVERRIDE_ACTIVITY_TRANSITION = 2; 101 static final int TEST_METHOD_CLEAR_OVERRIDE_ACTIVITY_TRANSITION = 3; 102 103 static final int TRANSITION_TYPE_OPEN = 0x1; 104 static final int TRANSITION_TYPE_CLOSE = 0x2; 105 106 static final String ACTION_UPDATE = 107 "android.server.wm.ActivityTransitionTests.ACTION_UPDATE"; 108 static final String ACTION_FINISH = 109 "android.server.wm.ActivityTransitionTests.ACTION_FINISH"; 110 111 private boolean mAnimationScaleResetRequired = false; 112 private String mInitialWindowAnimationScale; 113 private String mInitialTransitionAnimationScale; 114 private String mInitialAnimatorDurationScale; 115 116 // We need to allow for some variation stemming from color conversions 117 private static final float COLOR_VALUE_VARIANCE_TOLERANCE = 0.05f; 118 119 @ClassRule 120 public static DisableImmersiveModeConfirmationRule mDisableImmersiveModeConfirmationRule = 121 new DisableImmersiveModeConfirmationRule(); 122 123 @ClassRule 124 public static final TestRule enableWindowAnimationRule = SettingsSession.overrideForTest( 125 Settings.Global.getUriFor(Settings.Global.WINDOW_ANIMATION_SCALE), 126 Settings.Global::getFloat, 127 Settings.Global::putFloat, 128 1.0f); 129 130 @ClassRule 131 public static final TestRule enableTransitionAnimationRule = SettingsSession.overrideForTest( 132 Settings.Global.getUriFor(Settings.Global.TRANSITION_ANIMATION_SCALE), 133 Settings.Global::getFloat, 134 Settings.Global::putFloat, 135 1.0f); 136 137 @ClassRule 138 public static final TestRule enableAnimatorDurationRule = SettingsSession.overrideForTest( 139 Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE), 140 Settings.Global::getFloat, 141 Settings.Global::putFloat, 142 1.0f); 143 144 @Before setUp()145 public void setUp() throws Exception { 146 super.setUp(); 147 mWmState.setSanityCheckWithFocusedWindow(false); 148 mWmState.waitForDisplayUnfrozen(); 149 } 150 151 @After tearDown()152 public void tearDown() { 153 mWmState.setSanityCheckWithFocusedWindow(true); 154 } 155 startLauncherActivity()156 private LauncherActivity startLauncherActivity() { 157 final Intent intent = new Intent(mContext, LauncherActivity.class) 158 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 159 final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); 160 return (LauncherActivity) instrumentation.startActivitySync(intent); 161 } 162 163 @Test testActivityTransitionOverride()164 public void testActivityTransitionOverride() throws Exception { 165 final CountDownLatch latch = new CountDownLatch(1); 166 AtomicLong transitionStartTime = new AtomicLong(); 167 AtomicLong transitionEndTime = new AtomicLong(); 168 169 final ActivityOptions.OnAnimationStartedListener startedListener = transitionStartTime::set; 170 final ActivityOptions.OnAnimationFinishedListener finishedListener = (t) -> { 171 transitionEndTime.set(t); 172 latch.countDown(); 173 }; 174 175 final LauncherActivity launcherActivity = startLauncherActivity(); 176 177 final ActivityOptions options = ActivityOptions.makeCustomAnimation(mContext, 178 R.anim.alpha, 0 /* exitResId */, 0 /* backgroundColor */, 179 new Handler(Looper.getMainLooper()), startedListener, finishedListener); 180 launcherActivity.startActivity(options, TransitionActivity.class); 181 mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY); 182 waitAndAssertTopResumedActivity(new ComponentName(mContext, TransitionActivity.class), 183 DEFAULT_DISPLAY, "Activity must be launched"); 184 185 latch.await(5, TimeUnit.SECONDS); 186 final long totalTime = transitionEndTime.get() - transitionStartTime.get(); 187 assertTrue("Actual transition duration should be in the range " 188 + "<" + CUSTOM_ANIMATION_DURATION_RANGE.getLower() + ", " 189 + CUSTOM_ANIMATION_DURATION_RANGE.getUpper() + "> ms, " 190 + "actual=" + totalTime, CUSTOM_ANIMATION_DURATION_RANGE.contains(totalTime)); 191 } 192 193 @Test testTaskTransitionOverrideDisabled()194 public void testTaskTransitionOverrideDisabled() throws Exception { 195 final CountDownLatch latch = new CountDownLatch(1); 196 AtomicLong transitionStartTime = new AtomicLong(); 197 AtomicLong transitionEndTime = new AtomicLong(); 198 199 final ActivityOptions.OnAnimationStartedListener startedListener = transitionStartTime::set; 200 final ActivityOptions.OnAnimationFinishedListener finishedListener = (t) -> { 201 transitionEndTime.set(t); 202 latch.countDown(); 203 }; 204 205 // Overriding task transit animation is disabled, so default wallpaper close animation 206 // is played. 207 final Bundle bundle = ActivityOptions.makeCustomAnimation(mContext, 208 R.anim.alpha, 0 /* exitResId */, 0 /* backgroundColor */, 209 new Handler(Looper.getMainLooper()), startedListener, finishedListener).toBundle(); 210 final Intent intent = new Intent().setComponent(TEST_ACTIVITY) 211 .addFlags(FLAG_ACTIVITY_NEW_TASK); 212 mContext.startActivity(intent, bundle); 213 mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY); 214 waitAndAssertTopResumedActivity(TEST_ACTIVITY, DEFAULT_DISPLAY, 215 "Activity must be launched"); 216 217 latch.await(5, TimeUnit.SECONDS); 218 final long totalTime = transitionEndTime.get() - transitionStartTime.get(); 219 assertTrue("Actual transition duration should be out of the range " 220 + "<" + CUSTOM_ANIMATION_DURATION_RANGE.getLower() + ", " 221 + CUSTOM_ANIMATION_DURATION_RANGE.getUpper() + "> ms, " 222 + "actual=" + totalTime, !CUSTOM_ANIMATION_DURATION_RANGE.contains(totalTime)); 223 } 224 225 @Test testTaskWindowAnimationOverrideDisabled()226 public void testTaskWindowAnimationOverrideDisabled() throws Exception { 227 final CountDownLatch latch = new CountDownLatch(1); 228 AtomicLong transitionStartTime = new AtomicLong(); 229 AtomicLong transitionEndTime = new AtomicLong(); 230 231 final ActivityOptions.OnAnimationStartedListener startedListener = transitionStartTime::set; 232 final ActivityOptions.OnAnimationFinishedListener finishedListener = (t) -> { 233 transitionEndTime.set(t); 234 latch.countDown(); 235 }; 236 237 // Overriding task transit animation is disabled, so default wallpaper close animation 238 // is played. 239 final Bundle bundle = ActivityOptions.makeCustomAnimation(mContext, 240 R.anim.alpha, 0 /* exitResId */, 0 /* backgroundColor */, 241 new Handler(Looper.getMainLooper()), startedListener, finishedListener).toBundle(); 242 243 final ComponentName customWindowAnimationActivity = new ComponentName( 244 mContext, CustomWindowAnimationActivity.class); 245 final Intent intent = new Intent().setComponent(customWindowAnimationActivity) 246 .addFlags(FLAG_ACTIVITY_NEW_TASK); 247 mContext.startActivity(intent, bundle); 248 mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY); 249 waitAndAssertTopResumedActivity(customWindowAnimationActivity, DEFAULT_DISPLAY, 250 "Activity must be launched"); 251 252 latch.await(5, TimeUnit.SECONDS); 253 final long totalTime = transitionEndTime.get() - transitionStartTime.get(); 254 assertTrue("Actual transition duration should be out of the range " 255 + "<" + CUSTOM_ANIMATION_DURATION_RANGE.getLower() + ", " 256 + CUSTOM_ANIMATION_DURATION_RANGE.getUpper() + "> ms, " 257 + "actual=" + totalTime, !CUSTOM_ANIMATION_DURATION_RANGE.contains(totalTime)); 258 } 259 260 /** 261 * Checks that the activity's theme's background color is used as the default animation's 262 * background color when no override is specified. 263 */ 264 @Test testThemeBackgroundColorShowsDuringActivityTransition()265 public void testThemeBackgroundColorShowsDuringActivityTransition() { 266 final int backgroundColor = Color.WHITE; 267 final TestBounds testBounds = getTestBounds(); 268 269 getTestBuilder().setClass(TransitionActivityWithWhiteBackground.class) 270 .setTestFunction(createAssertAppRegionOfScreenIsColor(backgroundColor, testBounds)) 271 .run(); 272 } 273 274 /** 275 * Checks that the background color set in the animation definition is used as the animation's 276 * background color instead of the theme's background color. 277 * 278 * @see R.anim.alpha_0_with_red_backdrop for animation defintition. 279 */ 280 @Test testAnimationBackgroundColorIsUsedDuringActivityTransition()281 public void testAnimationBackgroundColorIsUsedDuringActivityTransition() { 282 final int backgroundColor = Color.RED; 283 final ActivityOptions activityOptions = ActivityOptions.makeCustomAnimation(mContext, 284 R.anim.alpha_0_with_red_backdrop, R.anim.alpha_0_with_red_backdrop); 285 final TestBounds testBounds = getTestBounds(); 286 287 getTestBuilder().setClass(TransitionActivityWithWhiteBackground.class) 288 .setActivityOptions(activityOptions) 289 .setTestFunction(createAssertAppRegionOfScreenIsColor(backgroundColor, testBounds)) 290 .run(); 291 } 292 293 /** 294 * Checks that we can override the default background color of the animation using the 295 * CustomAnimation activityOptions. 296 */ 297 @Test testCustomTransitionCanOverrideBackgroundColor()298 public void testCustomTransitionCanOverrideBackgroundColor() { 299 final int backgroundColor = Color.GREEN; 300 final ActivityOptions activityOptions = ActivityOptions.makeCustomAnimation(mContext, 301 R.anim.alpha_0_with_backdrop, R.anim.alpha_0_with_backdrop, backgroundColor 302 ); 303 final TestBounds testBounds = getTestBounds(); 304 305 getTestBuilder().setClass(TransitionActivityWithWhiteBackground.class) 306 .setActivityOptions(activityOptions) 307 .setTestFunction(createAssertAppRegionOfScreenIsColor(backgroundColor, testBounds)) 308 .run(); 309 } 310 311 /** 312 * Checks that we can override the default background color of the animation through 313 * overridePendingTransition. 314 */ 315 @Test testPendingTransitionCanOverrideBackgroundColor()316 public void testPendingTransitionCanOverrideBackgroundColor() { 317 final int backgroundColor = Color.GREEN; 318 319 final Bundle extras = new Bundle(); 320 extras.putInt(ENTER_ANIM_KEY, R.anim.alpha_0_with_backdrop); 321 extras.putInt(EXIT_ANIM_KEY, R.anim.alpha_0_with_backdrop); 322 extras.putInt(BACKGROUND_COLOR_KEY, backgroundColor); 323 addTestMethodToExtras(TEST_METHOD_OVERRIDE_PENDING_TRANSITION, 0, extras); 324 final TestBounds testBounds = getTestBounds(); 325 326 getTestBuilder().setClass(CustomBackgroundTransitionActivity.class).setExtras(extras) 327 .setTestFunction(createAssertAppRegionOfScreenIsColor(backgroundColor, testBounds)) 328 .run(); 329 } 330 331 @Test testSetTransitionCanOverrideBackgroundColor()332 public void testSetTransitionCanOverrideBackgroundColor() { 333 final int backgroundColor = Color.GREEN; 334 335 final Bundle extras = new Bundle(); 336 extras.putInt(ENTER_ANIM_KEY, R.anim.alpha_0_with_backdrop); 337 extras.putInt(EXIT_ANIM_KEY, R.anim.alpha_0_with_backdrop); 338 extras.putInt(BACKGROUND_COLOR_KEY, backgroundColor); 339 addTestMethodToExtras(TEST_METHOD_OVERRIDE_ACTIVITY_TRANSITION, 340 TRANSITION_TYPE_OPEN | TRANSITION_TYPE_CLOSE, extras); 341 final TestBounds testBounds = getTestBounds(); 342 343 getTestBuilder().setClass(CustomBackgroundTransitionActivity.class).setExtras(extras) 344 .setTestFunction(createAssertAppRegionOfScreenIsColor(backgroundColor, testBounds)) 345 .run(); 346 347 mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY); 348 mContext.sendBroadcast(new Intent(ACTION_FINISH)); 349 runAndAssertActivityTransition( 350 createAssertAppRegionOfScreenIsColor(backgroundColor, testBounds)); 351 } 352 /** 353 * Checks that when an activity transition with a left edge extension is run that the animating 354 * activity is extended on the left side by clamping the edge pixels of the activity. 355 * 356 * The test runs an activity transition where the animating activities are X scaled to 50%, 357 * positioned of the right side of the screen, and edge extended on the left. Because the 358 * animating activities are half red half blue (split at the middle of the X axis of the 359 * activity). We expect first 75% pixel columns of the screen to be red (50% from the edge 360 * extension and the next 25% from from the activity) and the remaining 25% columns after that 361 * to be blue (from the activity). 362 * 363 * @see R.anim.edge_extension_left for the transition applied. 364 */ 365 @Test testLeftEdgeExtensionWorksDuringActivityTransition()366 public void testLeftEdgeExtensionWorksDuringActivityTransition() { 367 final Bundle extras = new Bundle(); 368 extras.putInt(DIRECTION_KEY, LEFT); 369 addTestMethodToExtras(TEST_METHOD_OVERRIDE_PENDING_TRANSITION, 0, extras); 370 final TestBounds testBounds = getTestBounds(); 371 final Rect appBounds = testBounds.appBounds; 372 final int xIndex = appBounds.left + (appBounds.right - appBounds.left) * 3 / 4; 373 getTestBuilder().setClass(EdgeExtensionActivity.class).setExtras(extras) 374 .setTestFunction(createAssertColorChangeXIndex(xIndex, testBounds)) 375 .run(); 376 } 377 378 /** 379 * Checks that when an activity transition with a top edge extension is run that the animating 380 * activity is extended on the left side by clamping the edge pixels of the activity. 381 * 382 * The test runs an activity transition where the animating activities are Y scaled to 50%, 383 * positioned of the bottom of the screen, and edge extended on the top. Because the 384 * animating activities are half red half blue (split at the middle of the X axis of the 385 * activity). We expect first 50% pixel columns of the screen to be red (the top half from the 386 * extension and the bottom half from the activity) and the remaining 50% columns after that 387 * to be blue (the top half from the extension and the bottom half from the activity). 388 * 389 * @see R.anim.edge_extension_top for the transition applied. 390 */ 391 @Test testTopEdgeExtensionWorksDuringActivityTransition()392 public void testTopEdgeExtensionWorksDuringActivityTransition() { 393 final Bundle extras = new Bundle(); 394 extras.putInt(DIRECTION_KEY, TOP); 395 addTestMethodToExtras(TEST_METHOD_OVERRIDE_PENDING_TRANSITION, 0, extras); 396 final TestBounds testBounds = getTestBounds(); 397 final Rect appBounds = testBounds.appBounds; 398 final int xIndex = (appBounds.left + appBounds.right) / 2; 399 getTestBuilder().setClass(EdgeExtensionActivity.class).setExtras(extras) 400 .setTestFunction(createAssertColorChangeXIndex(xIndex, testBounds)) 401 .run(); 402 } 403 404 /** 405 * Checks that when an activity transition with a right edge extension is run that the animating 406 * activity is extended on the right side by clamping the edge pixels of the activity. 407 * 408 * The test runs an activity transition where the animating activities are X scaled to 50% and 409 * edge extended on the right. Because the animating activities are half red half blue. We 410 * expect first 25% pixel columns of the screen to be red (from the activity) and the remaining 411 * 75% columns after that to be blue (25% from the activity and 50% from the edge extension 412 * which should be extending the right edge pixel (so red pixels). 413 * 414 * @see R.anim.edge_extension_right for the transition applied. 415 */ 416 @Test testRightEdgeExtensionWorksDuringActivityTransition()417 public void testRightEdgeExtensionWorksDuringActivityTransition() { 418 final Bundle extras = new Bundle(); 419 extras.putInt(DIRECTION_KEY, RIGHT); 420 addTestMethodToExtras(TEST_METHOD_OVERRIDE_PENDING_TRANSITION, 0, extras); 421 final TestBounds testBounds = getTestBounds(); 422 final Rect appBounds = testBounds.appBounds; 423 final int xIndex = appBounds.left + (appBounds.right - appBounds.left) / 4; 424 getTestBuilder().setClass(EdgeExtensionActivity.class).setExtras(extras) 425 .setTestFunction(createAssertColorChangeXIndex(xIndex, testBounds)) 426 .run(); 427 } 428 429 /** 430 * Borrow the test from testRightEdgeExtensionWorksDuringActivityTransition, mainly test for 431 * API Activity#overrideActivityTransition. 432 */ 433 @Test testOverrideActivityTransition()434 public void testOverrideActivityTransition() { 435 final Bundle extras = new Bundle(); 436 extras.putInt(DIRECTION_KEY, RIGHT); 437 addTestMethodToExtras(TEST_METHOD_OVERRIDE_ACTIVITY_TRANSITION, 438 TRANSITION_TYPE_OPEN | TRANSITION_TYPE_CLOSE, extras); 439 final TestBounds testBounds = getTestBounds(); 440 final Rect appBounds = testBounds.appBounds; 441 final int xIndex = appBounds.left + (appBounds.right - appBounds.left) / 4; 442 getTestBuilder().setClass(EdgeExtensionActivity.class).setExtras(extras) 443 .setTestFunction(createAssertColorChangeXIndex(xIndex, testBounds)) 444 .run(); 445 446 mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY); 447 mContext.sendBroadcast(new Intent(ACTION_FINISH)); 448 runAndAssertActivityTransition(createAssertColorChangeXIndex(xIndex, testBounds)); 449 } 450 451 /** 452 * Borrow the test from testRightEdgeExtensionWorksDuringActivityTransition, mainly test for 453 * API Activity#clearOverrideActivityTransition. 454 */ 455 @Test testClearOverrideActivityTransition()456 public void testClearOverrideActivityTransition() { 457 final Bundle extras = new Bundle(); 458 extras.putInt(DIRECTION_KEY, RIGHT); 459 addTestMethodToExtras(TEST_METHOD_OVERRIDE_ACTIVITY_TRANSITION, 460 TRANSITION_TYPE_OPEN | TRANSITION_TYPE_CLOSE, extras); 461 final TestBounds testBounds = getTestBounds(); 462 final Rect appBounds = testBounds.appBounds; 463 final int xIndex = appBounds.left + (appBounds.right - appBounds.left) / 4; 464 final LauncherActivity launcherActivity = startLauncherActivity(); 465 launcherActivity.startActivity(null, EdgeExtensionActivity.class, extras); 466 467 mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY); 468 final Intent update = new Intent(ACTION_UPDATE); 469 update.putExtra(TEST_METHOD_KEY, TEST_METHOD_CLEAR_OVERRIDE_ACTIVITY_TRANSITION); 470 update.putExtra(TRANSITION_TYPE_KEY, TRANSITION_TYPE_OPEN | TRANSITION_TYPE_CLOSE); 471 mContext.sendBroadcast(update); 472 mContext.sendBroadcast(new Intent(ACTION_FINISH)); 473 runAndAssertActivityTransition(createAssertSingleColor(testBounds, Color.CYAN)); 474 } 475 476 /** 477 * Checks that when an activity transition with a bottom edge extension is run that the 478 * animating activity is extended on the bottom side by clamping the edge pixels of the 479 * activity. 480 * 481 * The test runs an activity transition where the animating activities are Y scaled to 50%, 482 * positioned of the top of the screen, and edge extended on the bottom. Because the 483 * animating activities are half red half blue (split at the middle of the X axis of the 484 * activity). We expect first 50% pixel columns of the screen to be red (the top half from the 485 * activity and the bottom half from gthe extensions) and the remaining 50% columns after that 486 * to be blue (the top half from the activity and the bottom half from the extension). 487 * 488 * @see R.anim.edge_extension_bottom for the transition applied. 489 */ 490 @Test testBottomEdgeExtensionWorksDuringActivityTransition()491 public void testBottomEdgeExtensionWorksDuringActivityTransition() { 492 final Bundle extras = new Bundle(); 493 extras.putInt(DIRECTION_KEY, BOTTOM); 494 addTestMethodToExtras(TEST_METHOD_OVERRIDE_PENDING_TRANSITION, 0, extras); 495 final TestBounds testBounds = getTestBounds(); 496 final Rect appBounds = testBounds.appBounds; 497 final int xIndex = (appBounds.left + appBounds.right) / 2; 498 getTestBuilder().setClass(EdgeExtensionActivity.class).setExtras(extras) 499 .setTestFunction(createAssertColorChangeXIndex(xIndex, testBounds)) 500 .run(); 501 } 502 getTestBuilder()503 private TestBuilder getTestBuilder() { 504 return new TestBuilder(); 505 } 506 507 private class TestBuilder { 508 private ActivityOptions mActivityOptions = ActivityOptions.makeBasic(); 509 private Bundle mExtras = Bundle.EMPTY; 510 private Class<?> mKlass; 511 private Function<Bitmap, AssertionResult> mTestFunction; 512 setActivityOptions(ActivityOptions activityOptions)513 public TestBuilder setActivityOptions(ActivityOptions activityOptions) { 514 this.mActivityOptions = activityOptions; 515 return this; 516 } 517 setExtras(Bundle extra)518 public TestBuilder setExtras(Bundle extra) { 519 this.mExtras = extra; 520 return this; 521 } 522 setClass(Class<?> klass)523 public TestBuilder setClass(Class<?> klass) { 524 this.mKlass = klass; 525 return this; 526 } 527 setTestFunction(Function<Bitmap, AssertionResult> testFunction)528 public TestBuilder setTestFunction(Function<Bitmap, AssertionResult> testFunction) { 529 this.mTestFunction = testFunction; 530 return this; 531 } 532 run()533 public void run() { 534 final LauncherActivity launcherActivity = startLauncherActivity(); 535 launcherActivity.startActivity(mActivityOptions, mKlass, mExtras); 536 runAndAssertActivityTransition(mTestFunction); 537 } 538 } 539 540 private static class TestBounds { 541 public Rect rect; 542 public Rect appBounds; 543 public ArrayList<Rect> excluded; 544 } 545 getTestBounds()546 private TestBounds getTestBounds() { 547 final LauncherActivity activity = startLauncherActivity(); 548 final TestBounds bounds = new TestBounds(); 549 bounds.rect = activity.getActivityFullyVisibleRegion(); 550 bounds.appBounds = getTopAppBounds(); 551 bounds.excluded = activity.getRoundedCornersRegions(); 552 launchHomeActivityNoWait(); 553 removeRootTasksWithActivityTypes(ALL_ACTIVITY_TYPE_BUT_HOME); 554 mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY); 555 return bounds; 556 } 557 runAndAssertActivityTransition(Function<Bitmap, AssertionResult> assertFunction)558 private void runAndAssertActivityTransition(Function<Bitmap, AssertionResult> assertFunction) { 559 // Busy wait until we are running the transition to capture the screenshot 560 // Set a limited time to wait for transition start since there can still miss the state. 561 Condition.waitFor(new Condition<>("Wait for transition running", () -> { 562 mWmState.computeState(); 563 return WindowManagerState.APP_STATE_RUNNING.equals( 564 mWmState.getDisplay(DEFAULT_DISPLAY).getAppTransitionState()); 565 }).setRetryIntervalMs(15).setRetryLimit(200)); 566 567 // Because of differences in timing between devices we try the given assert function 568 // by taking multiple screenshots approximately to ensure we capture at least one screenshot 569 // around the beginning of the activity transition. 570 // The Timing issue exists around the beginning, so we use a sleep duration that increases 571 // exponentially. The total amount of sleep duration is between 5 and 10 seconds, which 572 // matches the most common wait time in CTS (2^0 + 2^1 + ... + 2^13 = about 8000). 573 final ArrayList<AssertionResult> failedResults = new ArrayList<>(); 574 int sleepDurationMilliseconds = 1; 575 for (int i = 0; i < 13; i++) { 576 final AssertionResult result = assertFunction.apply( 577 mInstrumentation.getUiAutomation().takeScreenshot()); 578 if (!result.isFailure) { 579 return; 580 } 581 failedResults.add(result); 582 SystemClock.sleep(sleepDurationMilliseconds); 583 sleepDurationMilliseconds *= 2; 584 } 585 586 fail("No screenshot of the activity transition passed the assertions ::\n" 587 + String.join(",\n", failedResults.stream().map(Object::toString) 588 .toArray(String[]::new))); 589 } 590 rectsContain(ArrayList<Rect> rect, int x, int y)591 private boolean rectsContain(ArrayList<Rect> rect, int x, int y) { 592 for (Rect r : rect) { 593 if (r.contains(x, y)) { 594 return true; 595 } 596 } 597 return false; 598 } 599 createAssertAppRegionOfScreenIsColor(int color, TestBounds testBounds)600 private Function<Bitmap, AssertionResult> createAssertAppRegionOfScreenIsColor(int color, 601 TestBounds testBounds) { 602 return (screen) -> getIsAppRegionOfScreenOfColorResult(screen, color, testBounds); 603 } 604 605 private static class ColorCheckResult extends AssertionResult { 606 public final Point firstWrongPixel; 607 public final Color expectedColor; 608 public final Color actualColor; 609 ColorCheckResult(boolean isFailure, Point firstWrongPixel, Color expectedColor, Color actualColor)610 private ColorCheckResult(boolean isFailure, Point firstWrongPixel, Color expectedColor, 611 Color actualColor) { 612 super(isFailure); 613 this.firstWrongPixel = firstWrongPixel; 614 this.expectedColor = expectedColor; 615 this.actualColor = actualColor; 616 } 617 ColorCheckResult(Point firstWrongPixel, Color expectedColor, Color actualColor)618 private ColorCheckResult(Point firstWrongPixel, Color expectedColor, Color actualColor) { 619 this(true, firstWrongPixel, expectedColor, actualColor); 620 } 621 622 @Override toString()623 public String toString() { 624 return "ColorCheckResult{" 625 + "isFailure=" + isFailure 626 + ", firstWrongPixel=" + firstWrongPixel 627 + ", expectedColor=" + expectedColor 628 + ", actualColor=" + actualColor 629 + '}'; 630 } 631 } 632 getIsAppRegionOfScreenOfColorResult(Bitmap screen, int color, TestBounds testBounds)633 private AssertionResult getIsAppRegionOfScreenOfColorResult(Bitmap screen, int color, 634 TestBounds testBounds) { 635 for (int x = testBounds.rect.left; x < testBounds.rect.right; x++) { 636 for (int y = testBounds.rect.top; 637 y < testBounds.rect.bottom; y++) { 638 if (rectsContain(testBounds.excluded, x, y)) { 639 continue; 640 } 641 642 final Color rawColor = screen.getColor(x, y); 643 final Color sRgbColor; 644 if (!rawColor.getColorSpace().equals(ColorSpace.get(ColorSpace.Named.SRGB))) { 645 // Conversion is required because the color space of the screenshot may be in 646 // the DCI-P3 color space or some other color space and we want to compare the 647 // color against once in the SRGB color space, so we must convert the color back 648 // to the SRGB color space. 649 sRgbColor = screen.getColor(x, y) 650 .convert(ColorSpace.get(ColorSpace.Named.SRGB)); 651 } else { 652 sRgbColor = rawColor; 653 } 654 final Color expectedColor = Color.valueOf(color); 655 if (arrayEquals(new float[]{ 656 expectedColor.red(), expectedColor.green(), expectedColor.blue()}, 657 new float[]{sRgbColor.red(), sRgbColor.green(), sRgbColor.blue()})) { 658 return new ColorCheckResult(new Point(x, y), expectedColor, sRgbColor); 659 } 660 } 661 } 662 663 return AssertionResult.SUCCESS; 664 } 665 arrayEquals(float[] array1, float[] array2)666 private boolean arrayEquals(float[] array1, float[] array2) { 667 return arrayEquals(array1, array2, COLOR_VALUE_VARIANCE_TOLERANCE); 668 } 669 arrayEquals(float[] array1, float[] array2, float varianceTolerance)670 private boolean arrayEquals(float[] array1, float[] array2, float varianceTolerance) { 671 if (array1.length != array2.length) { 672 return true; 673 } 674 for (int i = 0; i < array1.length; i++) { 675 if (Math.abs(array1[i] - array2[i]) > varianceTolerance) { 676 return true; 677 } 678 } 679 return false; 680 } 681 getTopAppBounds()682 private Rect getTopAppBounds() { 683 getWmState().computeState(); 684 final WindowManagerState.Activity activity = getWmState().getActivity( 685 ComponentName.unflattenFromString(getWmState().getFocusedActivity())); 686 return activity.getAppBounds(); 687 } 688 689 private static class AssertionResult { 690 public final boolean isFailure; 691 public final String message; 692 AssertionResult(boolean isFailure, String message)693 private AssertionResult(boolean isFailure, String message) { 694 this.isFailure = isFailure; 695 this.message = message; 696 } 697 AssertionResult(boolean isFailure)698 private AssertionResult(boolean isFailure) { 699 this(isFailure, null); 700 } 701 702 @Override toString()703 public String toString() { 704 return "AssertionResult{" 705 + "isFailure=" + isFailure 706 + ", message='" + message + '\'' 707 + '}'; 708 } 709 710 private static final AssertionResult SUCCESS = new AssertionResult(false); 711 private static final AssertionResult FAILURE = new AssertionResult(true); 712 } 713 714 // The activity we are extending is a half red, half blue. 715 // We are scaling the activity in the animation so if the extension doesn't work we should 716 // have a blue, then red, then black section, and if it does work we should see on a blue, 717 // followed by an extended red section. createAssertColorChangeXIndex(int xIndex, TestBounds testBounds)718 private Function<Bitmap, AssertionResult> createAssertColorChangeXIndex(int xIndex, 719 TestBounds testBounds) { 720 return (screen) -> assertColorChangeXIndex( 721 screen, xIndex, testBounds, Color.BLUE, Color.RED); 722 } 723 724 // Verify the screenshot is filled with a single color. createAssertSingleColor( TestBounds testBounds, int color)725 private Function<Bitmap, AssertionResult> createAssertSingleColor( 726 TestBounds testBounds, int color) { 727 return (screen) -> assertColorChangeXIndex( 728 screen, 0, testBounds, color, color); 729 } 730 assertColorChangeXIndex(Bitmap screen, int xIndex, TestBounds testBounds, int lessXColor, int largeXColor)731 private AssertionResult assertColorChangeXIndex(Bitmap screen, int xIndex, 732 TestBounds testBounds, int lessXColor, int largeXColor) { 733 for (int x = testBounds.rect.left; x < testBounds.rect.right; x++) { 734 for (int y = testBounds.rect.top; 735 y < testBounds.rect.bottom; y++) { 736 if (rectsContain(testBounds.excluded, x, y)) { 737 continue; 738 } 739 740 // Edge pixels can have any color depending on the blending strategy of the device. 741 if (Math.abs(x - xIndex) <= 1) { 742 continue; 743 } 744 745 final Color expectedColor; 746 if (x < xIndex) { 747 expectedColor = Color.valueOf(lessXColor); 748 } else { 749 expectedColor = Color.valueOf(largeXColor); 750 } 751 752 final Color rawColor = screen.getColor(x, y); 753 final Color sRgbColor; 754 if (!rawColor.getColorSpace().equals(ColorSpace.get(ColorSpace.Named.SRGB))) { 755 // Conversion is required because the color space of the screenshot may be in 756 // the DCI-P3 color space or some other color space and we want to compare the 757 // color against once in the SRGB color space, so we must convert the color back 758 // to the SRGB color space. 759 sRgbColor = screen.getColor(x, y) 760 .convert(ColorSpace.get(ColorSpace.Named.SRGB)); 761 } else { 762 sRgbColor = rawColor; 763 } 764 765 if (arrayEquals(new float[]{ 766 expectedColor.red(), expectedColor.green(), expectedColor.blue()}, 767 new float[]{sRgbColor.red(), sRgbColor.green(), sRgbColor.blue()})) { 768 return new ColorCheckResult(new Point(x, y), expectedColor, sRgbColor); 769 } 770 } 771 } 772 773 return AssertionResult.SUCCESS; 774 } 775 addTestMethodToExtras(int apiType, int transitionType, Bundle extras)776 private static void addTestMethodToExtras(int apiType, int transitionType, Bundle extras) { 777 extras.putInt(TEST_METHOD_KEY, apiType); 778 extras.putInt(TRANSITION_TYPE_KEY, transitionType); 779 } 780 781 public static class LauncherActivity extends Activity { 782 783 private WindowInsets mInsets; 784 785 @Override onCreate(@ullable Bundle savedInstanceState)786 protected void onCreate(@Nullable Bundle savedInstanceState) { 787 super.onCreate(savedInstanceState); 788 789 // Ensure the activity is edge-to-edge 790 // In tests we rely on the activity's content filling the entire window 791 getWindow().setDecorFitsSystemWindows(false); 792 793 View view = new View(this); 794 view.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); 795 view.setOnApplyWindowInsetsListener((v, insets) -> mInsets = insets); 796 view.setBackgroundColor(Color.CYAN); 797 setContentView(view); 798 } 799 getActivityFullyVisibleRegion()800 private Rect getActivityFullyVisibleRegion() { 801 final Rect activityBounds = getWindowManager().getCurrentWindowMetrics().getBounds(); 802 final Insets insets = mInsets.getInsets(WindowInsets.Type.systemBars() 803 | WindowInsets.Type.displayCutout()); 804 activityBounds.inset(insets); 805 806 return new Rect(activityBounds); 807 } 808 getRoundedCornersRegions()809 private ArrayList<Rect> getRoundedCornersRegions() { 810 RoundedCorner topRightCorner = mInsets.getRoundedCorner(POSITION_TOP_RIGHT); 811 RoundedCorner topLeftCorner = mInsets.getRoundedCorner(POSITION_TOP_LEFT); 812 RoundedCorner bottomRightCorner = mInsets.getRoundedCorner(POSITION_BOTTOM_RIGHT); 813 RoundedCorner bottomLeftCorner = mInsets.getRoundedCorner(POSITION_BOTTOM_LEFT); 814 815 final ArrayList<Rect> roundedCornersRects = new ArrayList<>(); 816 817 if (topRightCorner != null) { 818 final Point center = topRightCorner.getCenter(); 819 final int radius = topRightCorner.getRadius(); 820 roundedCornersRects.add( 821 new Rect(center.x, center.y - radius, 822 center.x + radius, center.y)); 823 } 824 if (topLeftCorner != null) { 825 final Point center = topLeftCorner.getCenter(); 826 final int radius = topLeftCorner.getRadius(); 827 roundedCornersRects.add( 828 new Rect(center.x - radius, center.y - radius, 829 center.x, center.y)); 830 } 831 if (bottomRightCorner != null) { 832 final Point center = bottomRightCorner.getCenter(); 833 final int radius = bottomRightCorner.getRadius(); 834 roundedCornersRects.add( 835 new Rect(center.x, center.y, 836 center.x + radius, center.y + radius)); 837 } 838 if (bottomLeftCorner != null) { 839 final Point center = bottomLeftCorner.getCenter(); 840 final int radius = bottomLeftCorner.getRadius(); 841 roundedCornersRects.add( 842 new Rect(center.x - radius, center.y, 843 center.x, center.y + radius)); 844 } 845 846 return roundedCornersRects; 847 } 848 startActivity(ActivityOptions activityOptions, Class<?> klass)849 public void startActivity(ActivityOptions activityOptions, Class<?> klass) { 850 startActivity(activityOptions, klass, new Bundle()); 851 } 852 startActivity(ActivityOptions activityOptions, Class<?> klass, Bundle extras)853 public void startActivity(ActivityOptions activityOptions, Class<?> klass, 854 Bundle extras) { 855 final Intent i = new Intent(this, klass); 856 i.putExtras(extras); 857 startActivity(i, activityOptions != null ? activityOptions.toBundle() : null); 858 } 859 } 860 861 public static class TransitionActivity extends Activity { } 862 863 public static class CustomBackgroundTransitionActivity extends Activity { 864 static final String ENTER_ANIM_KEY = "enterAnim"; 865 static final String EXIT_ANIM_KEY = "enterAnim"; 866 static final String BACKGROUND_COLOR_KEY = "backgroundColor"; 867 868 private boolean mPendingOverrideTransition; 869 private int mPendingEnterRes; 870 private int mPendingExitRes; 871 private int mBackgroundColor; 872 873 @Override onCreate(@ullable Bundle savedInstanceState)874 protected void onCreate(@Nullable Bundle savedInstanceState) { 875 super.onCreate(savedInstanceState); 876 registerReceiver(mReceiver, new IntentFilter(ACTION_FINISH), Context.RECEIVER_EXPORTED); 877 processIntent(); 878 } 879 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 880 @Override 881 public void onReceive(Context context, Intent intent) { 882 if (ACTION_FINISH.equals(intent.getAction())) { 883 finish(); 884 } 885 } 886 }; 887 processIntent()888 private void processIntent() { 889 Bundle extras = getIntent().getExtras(); 890 int testAPI = extras.getInt(TEST_METHOD_KEY); 891 int enterAnim = extras.getInt(ENTER_ANIM_KEY); 892 int exitAnim = extras.getInt(EXIT_ANIM_KEY); 893 int backgroundColor = extras.getInt(BACKGROUND_COLOR_KEY); 894 int transitionType = extras.getInt(TRANSITION_TYPE_KEY); 895 if (testAPI == TEST_METHOD_OVERRIDE_PENDING_TRANSITION) { 896 mPendingOverrideTransition = true; 897 mPendingEnterRes = enterAnim; 898 mPendingExitRes = exitAnim; 899 mBackgroundColor = backgroundColor; 900 } else if (testAPI == TEST_METHOD_OVERRIDE_ACTIVITY_TRANSITION) { 901 if ((transitionType & TRANSITION_TYPE_OPEN) != 0) { 902 if (backgroundColor != 0) { 903 overrideActivityTransition(OVERRIDE_TRANSITION_OPEN, enterAnim, exitAnim, 904 backgroundColor /* backgroundColor */); 905 } else { 906 overrideActivityTransition(OVERRIDE_TRANSITION_OPEN, enterAnim, exitAnim); 907 } 908 } 909 if ((transitionType & TRANSITION_TYPE_CLOSE) != 0) { 910 if (backgroundColor != 0) { 911 overrideActivityTransition(OVERRIDE_TRANSITION_CLOSE, enterAnim, exitAnim, 912 backgroundColor /* backgroundColor */); 913 } else { 914 overrideActivityTransition(OVERRIDE_TRANSITION_CLOSE, enterAnim, exitAnim); 915 } 916 } 917 } 918 } 919 920 @Override onResume()921 protected void onResume() { 922 super.onResume(); 923 924 if (mPendingOverrideTransition) { 925 overridePendingTransition(mPendingEnterRes, mPendingExitRes, mBackgroundColor); 926 mPendingOverrideTransition = false; 927 } 928 } 929 930 @Override onDestroy()931 protected void onDestroy() { 932 super.onDestroy(); 933 unregisterReceiver(mReceiver); 934 } 935 } 936 937 public static class TransitionActivityWithWhiteBackground extends Activity { } 938 939 public static class EdgeExtensionActivity extends Activity { 940 static final String DIRECTION_KEY = "direction"; 941 static final int LEFT = 0; 942 static final int TOP = 1; 943 static final int RIGHT = 2; 944 static final int BOTTOM = 3; 945 946 private boolean mPendingOverrideTransition; 947 private int mPendingEnterRes; 948 private int mPendingExitRes; 949 950 @Override onCreate(@ullable Bundle savedInstanceState)951 protected void onCreate(@Nullable Bundle savedInstanceState) { 952 super.onCreate(savedInstanceState); 953 setContentView(R.layout.vertical_color_split); 954 955 // Ensure the activity is edge-to-edge 956 // In tests we rely on the activity's content filling the entire window 957 getWindow().setDecorFitsSystemWindows(false); 958 959 // Hide anything that the decor view might add to the window to avoid extending that 960 getWindow().getInsetsController() 961 .hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars()); 962 final IntentFilter intentFilter = new IntentFilter(); 963 intentFilter.addAction(ACTION_FINISH); 964 intentFilter.addAction(ACTION_UPDATE); 965 registerReceiver(mReceiver, intentFilter, Context.RECEIVER_EXPORTED); 966 processIntent(); 967 } 968 969 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 970 @Override 971 public void onReceive(Context context, Intent intent) { 972 if (ACTION_UPDATE.equals(intent.getAction())) { 973 final int clearApi = intent.getIntExtra(TEST_METHOD_KEY, 0); 974 if (clearApi == TEST_METHOD_CLEAR_OVERRIDE_ACTIVITY_TRANSITION) { 975 final int clearType = intent.getIntExtra(TRANSITION_TYPE_KEY, 0); 976 if ((clearType & TRANSITION_TYPE_OPEN) != 0) { 977 clearOverrideActivityTransition(OVERRIDE_TRANSITION_OPEN); 978 } 979 if ((clearType & TRANSITION_TYPE_CLOSE) != 0) { 980 clearOverrideActivityTransition(OVERRIDE_TRANSITION_CLOSE); 981 } 982 } 983 } 984 if (ACTION_FINISH.equals(intent.getAction())) { 985 finish(); 986 } 987 } 988 }; 989 990 @Override onDestroy()991 protected void onDestroy() { 992 super.onDestroy(); 993 unregisterReceiver(mReceiver); 994 } 995 996 @Override onResume()997 protected void onResume() { 998 super.onResume(); 999 1000 if (mPendingOverrideTransition) { 1001 overridePendingTransition(mPendingEnterRes, mPendingExitRes); 1002 mPendingOverrideTransition = false; 1003 } 1004 } 1005 processIntent()1006 private void processIntent() { 1007 Bundle extras = getIntent().getExtras(); 1008 int direction = extras.getInt(DIRECTION_KEY); 1009 int testAPI = extras.getInt(TEST_METHOD_KEY); 1010 int transitionType = extras.getInt(TRANSITION_TYPE_KEY); 1011 int testAnim = 0; 1012 switch (direction) { 1013 case LEFT: 1014 testAnim = R.anim.edge_extension_left; 1015 break; 1016 case TOP: 1017 testAnim = R.anim.edge_extension_top; 1018 break; 1019 case RIGHT: 1020 testAnim = R.anim.edge_extension_right; 1021 break; 1022 case BOTTOM: 1023 testAnim = R.anim.edge_extension_bottom; 1024 break; 1025 } 1026 if (testAPI == TEST_METHOD_OVERRIDE_PENDING_TRANSITION) { 1027 mPendingOverrideTransition = true; 1028 mPendingEnterRes = testAnim; 1029 mPendingExitRes = R.anim.alpha_0; 1030 } else if (testAPI == TEST_METHOD_OVERRIDE_ACTIVITY_TRANSITION) { 1031 if ((transitionType & TRANSITION_TYPE_OPEN) != 0) { 1032 overrideActivityTransition(OVERRIDE_TRANSITION_OPEN, testAnim, R.anim.alpha_0, 1033 0 /* backgroundColor */); 1034 } 1035 if ((transitionType & TRANSITION_TYPE_CLOSE) != 0) { 1036 overrideActivityTransition(OVERRIDE_TRANSITION_CLOSE, R.anim.alpha_0, testAnim, 1037 0 /* backgroundColor */); 1038 } 1039 } 1040 } 1041 } 1042 1043 public static class CustomWindowAnimationActivity extends Activity { } 1044 } 1045