Debian Codegraph @

libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 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 com.android.wm.shell.transition;
18
19 import static android.app.ActivityOptions.ANIM_CLIP_REVEAL;
20 import static android.app.ActivityOptions.ANIM_CUSTOM;
21 import static android.app.ActivityOptions.ANIM_NONE;
22 import static android.app.ActivityOptions.ANIM_OPEN_CROSS_PROFILE_APPS;
23 import static android.app.ActivityOptions.ANIM_SCALE_UP;
24 import static android.app.ActivityOptions.ANIM_THUMBNAIL_SCALE_DOWN;
25 import static android.app.ActivityOptions.ANIM_THUMBNAIL_SCALE_UP;
26 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
27 import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_POLICY_RESOURCE_UPDATED;
28 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE;
29 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_DRAWABLE;
30 import static android.app.admin.DevicePolicyResources.Drawables.Source.PROFILE_SWITCH_ANIMATION;
31 import static android.app.admin.DevicePolicyResources.Drawables.Style.OUTLINE;
32 import static android.app.admin.DevicePolicyResources.Drawables.WORK_PROFILE_ICON;
33 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_JUMPCUT;
34 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
35 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS;
36 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_UNSPECIFIED;
37 import static android.view.WindowManager.TRANSIT_CHANGE;
38 import static android.view.WindowManager.TRANSIT_CLOSE;
39 import static android.view.WindowManager.TRANSIT_KEYGUARD_UNOCCLUDE;
40 import static android.view.WindowManager.TRANSIT_OPEN;
41 import static android.view.WindowManager.TRANSIT_RELAUNCH;
42 import static android.view.WindowManager.TRANSIT_TO_BACK;
43 import static android.view.WindowManager.TRANSIT_TO_FRONT;
44 import static android.window.TransitionInfo.FLAG_CROSS_PROFILE_OWNER_THUMBNAIL;
45 import static android.window.TransitionInfo.FLAG_CROSS_PROFILE_WORK_THUMBNAIL;
46 import static android.window.TransitionInfo.FLAG_DISPLAY_HAS_ALERT_WINDOWS;
47 import static android.window.TransitionInfo.FLAG_FILLS_TASK;
48 import static android.window.TransitionInfo.FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY;
49 import static android.window.TransitionInfo.FLAG_IS_BEHIND_STARTING_WINDOW;
50 import static android.window.TransitionInfo.FLAG_IS_DISPLAY;
51 import static android.window.TransitionInfo.FLAG_IS_VOICE_INTERACTION;
52 import static android.window.TransitionInfo.FLAG_IS_WALLPAPER;
53 import static android.window.TransitionInfo.FLAG_SHOW_WALLPAPER;
54 import static android.window.TransitionInfo.FLAG_STARTING_WINDOW_TRANSFER_RECIPIENT;
55 import static android.window.TransitionInfo.FLAG_TRANSLUCENT;
56
57 import static com.android.internal.policy.TransitionAnimation.WALLPAPER_TRANSITION_CLOSE;
58 import static com.android.internal.policy.TransitionAnimation.WALLPAPER_TRANSITION_INTRA_CLOSE;
59 import static com.android.internal.policy.TransitionAnimation.WALLPAPER_TRANSITION_INTRA_OPEN;
60 import static com.android.internal.policy.TransitionAnimation.WALLPAPER_TRANSITION_NONE;
61 import static com.android.internal.policy.TransitionAnimation.WALLPAPER_TRANSITION_OPEN;
62 import static com.android.wm.shell.transition.TransitionAnimationHelper.addBackgroundToTransition;
63 import static com.android.wm.shell.transition.TransitionAnimationHelper.edgeExtendWindow;
64 import static com.android.wm.shell.transition.TransitionAnimationHelper.getTransitionBackgroundColorIfSet;
65 import static com.android.wm.shell.transition.TransitionAnimationHelper.loadAttributeAnimation;
66 import static com.android.wm.shell.transition.TransitionAnimationHelper.sDisableCustomTaskAnimationProperty;
67
68 import android.animation.Animator;
69 import android.animation.AnimatorListenerAdapter;
70 import android.animation.ValueAnimator;
71 import android.annotation.ColorInt;
72 import android.annotation.NonNull;
73 import android.annotation.Nullable;
74 import android.app.ActivityManager;
75 import android.app.ActivityThread;
76 import android.app.admin.DevicePolicyManager;
77 import android.content.BroadcastReceiver;
78 import android.content.Context;
79 import android.content.Intent;
80 import android.content.IntentFilter;
81 import android.graphics.Insets;
82 import android.graphics.Point;
83 import android.graphics.Rect;
84 import android.graphics.drawable.Drawable;
85 import android.hardware.HardwareBuffer;
86 import android.os.Handler;
87 import android.os.IBinder;
88 import android.os.UserHandle;
89 import android.util.ArrayMap;
90 import android.view.Choreographer;
91 import android.view.SurfaceControl;
92 import android.view.SurfaceSession;
93 import android.view.WindowManager;
94 import android.view.WindowManager.TransitionType;
95 import android.view.animation.AlphaAnimation;
96 import android.view.animation.Animation;
97 import android.view.animation.Transformation;
98 import android.window.TransitionInfo;
99 import android.window.TransitionMetrics;
100 import android.window.TransitionRequestInfo;
101 import android.window.WindowContainerTransaction;
102
103 import com.android.internal.R;
104 import com.android.internal.annotations.VisibleForTesting;
105 import com.android.internal.policy.AttributeCache;
106 import com.android.internal.policy.ScreenDecorationsUtils;
107 import com.android.internal.policy.TransitionAnimation;
108 import com.android.internal.protolog.common.ProtoLog;
109 import com.android.wm.shell.common.DisplayController;
110 import com.android.wm.shell.common.DisplayLayout;
111 import com.android.wm.shell.common.ShellExecutor;
112 import com.android.wm.shell.common.TransactionPool;
113 import com.android.wm.shell.protolog.ShellProtoLogGroup;
114 import com.android.wm.shell.sysui.ShellInit;
115
116 import java.util.ArrayList;
117 import java.util.List;
118 import java.util.function.Consumer;
119
120 /** The default handler that handles anything not already handled. */
121 public class DefaultTransitionHandler implements Transitions.TransitionHandler {
122 private static final int MAX_ANIMATION_DURATION = 3000;
123
124 private final TransactionPool mTransactionPool;
125 private final DisplayController mDisplayController;
126 private final Context mContext;
127 private final Handler mMainHandler;
128 private final ShellExecutor mMainExecutor;
129 private final ShellExecutor mAnimExecutor;
130 private final TransitionAnimation mTransitionAnimation;
131 private final DevicePolicyManager mDevicePolicyManager;
132
133 private final SurfaceSession mSurfaceSession = new SurfaceSession();
134
135 /** Keeps track of the currently-running animations associated with each transition. */
136 private final ArrayMap<IBinder, ArrayList<Animator>> mAnimations = new ArrayMap<>();
137
138 private final CounterRotatorHelper mRotator = new CounterRotatorHelper();
139 private final Rect mInsets = new Rect(0, 0, 0, 0);
140 private float mTransitionAnimationScaleSetting = 1.0f;
141
142 private final int mCurrentUserId;
143
144 private Drawable mEnterpriseThumbnailDrawable;
145
146 private BroadcastReceiver mEnterpriseResourceUpdatedReceiver = new BroadcastReceiver() {
147 @Override
148 public void onReceive(Context context, Intent intent) {
149 if (intent.getIntExtra(EXTRA_RESOURCE_TYPE, /* default= */ -1)
150 != EXTRA_RESOURCE_TYPE_DRAWABLE) {
151 return;
152 }
153 updateEnterpriseThumbnailDrawable();
154 }
155 };
156
157 DefaultTransitionHandler(@NonNull Context context,
158 @NonNull ShellInit shellInit,
159 @NonNull DisplayController displayController,
160 @NonNull TransactionPool transactionPool,
161 @NonNull ShellExecutor mainExecutor, @NonNull Handler mainHandler,
162 @NonNull ShellExecutor animExecutor) {
163 mDisplayController = displayController;
164 mTransactionPool = transactionPool;
165 mContext = context;
166 mMainHandler = mainHandler;
167 mMainExecutor = mainExecutor;
168 mAnimExecutor = animExecutor;
169 mTransitionAnimation = new TransitionAnimation(context, false /* debug */, Transitions.TAG);
170 mCurrentUserId = UserHandle.myUserId();
171 mDevicePolicyManager = mContext.getSystemService(DevicePolicyManager.class);
172 shellInit.addInitCallback(this::onInit, this);
173 }
174
175 private void onInit() {
176 updateEnterpriseThumbnailDrawable();
177 mContext.registerReceiver(
178 mEnterpriseResourceUpdatedReceiver,
179 new IntentFilter(ACTION_DEVICE_POLICY_RESOURCE_UPDATED),
180 /* broadcastPermission = */ null,
181 mMainHandler);
182
183 AttributeCache.init(mContext);
184 }
185
186 private void updateEnterpriseThumbnailDrawable() {
187 mEnterpriseThumbnailDrawable = mDevicePolicyManager.getResources().getDrawable(
188 WORK_PROFILE_ICON, OUTLINE, PROFILE_SWITCH_ANIMATION,
189 () -> mContext.getDrawable(R.drawable.ic_corp_badge));
190 }
191
192 @VisibleForTesting
193 static int getRotationAnimationHint(@NonNull TransitionInfo.Change displayChange,
194 @NonNull TransitionInfo info, @NonNull DisplayController displayController) {
195 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
196 "Display is changing, resolve the animation hint.");
197 // The explicit request of display has the highest priority.
198 if (displayChange.getRotationAnimation() == ROTATION_ANIMATION_SEAMLESS) {
199 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
200 " display requests explicit seamless");
201 return ROTATION_ANIMATION_SEAMLESS;
202 }
203
204 boolean allTasksSeamless = false;
205 boolean rejectSeamless = false;
206 ActivityManager.RunningTaskInfo topTaskInfo = null;
207 int animationHint = ROTATION_ANIMATION_ROTATE;
208 // Traverse in top-to-bottom order so that the first task is top-most.
209 final int size = info.getChanges().size();
210 for (int i = 0; i < size; ++i) {
211 final TransitionInfo.Change change = info.getChanges().get(i);
212
213 // Only look at changing things. showing/hiding don't need to rotate.
214 if (change.getMode() != TRANSIT_CHANGE) continue;
215
216 // This container isn't rotating, so we can ignore it.
217 if (change.getEndRotation() == change.getStartRotation()) continue;
218 if ((change.getFlags() & FLAG_IS_DISPLAY) != 0) {
219 // In the presence of System Alert windows we can not seamlessly rotate.
220 if ((change.getFlags() & FLAG_DISPLAY_HAS_ALERT_WINDOWS) != 0) {
221 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
222 " display has system alert windows, so not seamless.");
223 rejectSeamless = true;
224 }
225 } else if ((change.getFlags() & FLAG_IS_WALLPAPER) != 0) {
226 if (change.getRotationAnimation() != ROTATION_ANIMATION_SEAMLESS) {
227 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
228 " wallpaper is participating but isn't seamless.");
229 rejectSeamless = true;
230 }
231 } else if (change.getTaskInfo() != null) {
232 final int anim = change.getRotationAnimation();
233 final ActivityManager.RunningTaskInfo taskInfo = change.getTaskInfo();
234 final boolean isTopTask = topTaskInfo == null;
235 if (isTopTask) {
236 topTaskInfo = taskInfo;
237 if (anim != ROTATION_ANIMATION_UNSPECIFIED
238 && anim != ROTATION_ANIMATION_SEAMLESS) {
239 animationHint = anim;
240 }
241 }
242 // We only enable seamless rotation if all the visible task windows requested it.
243 if (anim != ROTATION_ANIMATION_SEAMLESS) {
244 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
245 " task %s isn't requesting seamless, so not seamless.",
246 taskInfo.taskId);
247 allTasksSeamless = false;
248 } else if (isTopTask) {
249 allTasksSeamless = true;
250 }
251 }
252 }
253
254 if (!allTasksSeamless || rejectSeamless) {
255 return animationHint;
256 }
257
258 // This is the only way to get display-id currently, so check display capabilities here.
259 final DisplayLayout displayLayout = displayController.getDisplayLayout(
260 topTaskInfo.displayId);
261 // For the upside down rotation we don't rotate seamlessly as the navigation bar moves
262 // position. Note most apps (using orientation:sensor or user as opposed to fullSensor)
263 // will not enter the reverse portrait orientation, so actually the orientation won't
264 // change at all.
265 final int upsideDownRotation = displayLayout.getUpsideDownRotation();
266 if (displayChange.getStartRotation() == upsideDownRotation
267 || displayChange.getEndRotation() == upsideDownRotation) {
268 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
269 " rotation involves upside-down portrait, so not seamless.");
270 return animationHint;
271 }
272
273 // If the navigation bar can't change sides, then it will jump when we change orientations
274 // and we don't rotate seamlessly - unless that is allowed, e.g. with gesture navigation
275 // where the navbar is low-profile enough that this isn't very noticeable.
276 if (!displayLayout.allowSeamlessRotationDespiteNavBarMoving()
277 && (!(displayLayout.navigationBarCanMove()
278 && (displayChange.getStartAbsBounds().width()
279 != displayChange.getStartAbsBounds().height())))) {
280 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
281 " nav bar changes sides, so not seamless.");
282 return animationHint;
283 }
284 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, " Rotation IS seamless.");
285 return ROTATION_ANIMATION_SEAMLESS;
286 }
287
288 @Override
289 public boolean startAnimation(@NonNull IBinder transition, @NonNull TransitionInfo info,
290 @NonNull SurfaceControl.Transaction startTransaction,
291 @NonNull SurfaceControl.Transaction finishTransaction,
292 @NonNull Transitions.TransitionFinishCallback finishCallback) {
293 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
294 "start default transition animation, info = %s", info);
295 // If keyguard goes away, we should loadKeyguardExitAnimation. Otherwise this just
296 // immediately finishes since there is no animation for screen-wake.
297 if (info.getType() == WindowManager.TRANSIT_WAKE && !info.isKeyguardGoingAway()) {
298 startTransaction.apply();
299 finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
300 return true;
301 }
302
303 if (mAnimations.containsKey(transition)) {
304 throw new IllegalStateException("Got a duplicate startAnimation call for "
305 + transition);
306 }
307 final ArrayList<Animator> animations = new ArrayList<>();
308 mAnimations.put(transition, animations);
309
310 final Runnable onAnimFinish = () -> {
311 if (!animations.isEmpty()) return;
312 mAnimations.remove(transition);
313 finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */);
314 };
315
316 final List<Consumer<SurfaceControl.Transaction>> postStartTransactionCallbacks =
317 new ArrayList<>();
318
319 @ColorInt int backgroundColorForTransition = 0;
320 final int wallpaperTransit = getWallpaperTransitType(info);
321 for (int i = info.getChanges().size() - 1; i >= 0; --i) {
322 final TransitionInfo.Change change = info.getChanges().get(i);
323 if (change.hasAllFlags(FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY
324 | FLAG_IS_BEHIND_STARTING_WINDOW)) {
325 // Don't animate embedded activity if it is covered by the starting window.
326 // Non-embedded case still needs animation because the container can still animate
327 // the starting window together, e.g. CLOSE or CHANGE type.
328 continue;
329 }
330 if (change.hasFlags(TransitionInfo.FLAGS_IS_NON_APP_WINDOW)) {
331 // Wallpaper, IME, and system windows don't need any default animations.
332 continue;
333 }
334 final boolean isTask = change.getTaskInfo() != null;
335 boolean isSeamlessDisplayChange = false;
336
337 if (change.getMode() == TRANSIT_CHANGE && (change.getFlags() & FLAG_IS_DISPLAY) != 0) {
338 if (info.getType() == TRANSIT_CHANGE) {
339 final int anim = getRotationAnimationHint(change, info, mDisplayController);
340 isSeamlessDisplayChange = anim == ROTATION_ANIMATION_SEAMLESS;
341 if (!(isSeamlessDisplayChange || anim == ROTATION_ANIMATION_JUMPCUT)) {
342 startRotationAnimation(startTransaction, change, info, anim, animations,
343 onAnimFinish);
344 continue;
345 }
346 } else {
347 // Opening/closing an app into a new orientation.
348 mRotator.handleClosingChanges(info, startTransaction, change);
349 }
350 }
351
352 if (change.getMode() == TRANSIT_CHANGE) {
353 // If task is child task, only set position in parent and update crop when needed.
354 if (isTask && change.getParent() != null
355 && info.getChange(change.getParent()).getTaskInfo() != null) {
356 final Point positionInParent = change.getTaskInfo().positionInParent;
357 startTransaction.setPosition(change.getLeash(),
358 positionInParent.x, positionInParent.y);
359
360 if (!change.getEndAbsBounds().equals(
361 info.getChange(change.getParent()).getEndAbsBounds())) {
362 startTransaction.setWindowCrop(change.getLeash(),
363 change.getEndAbsBounds().width(),
364 change.getEndAbsBounds().height());
365 }
366
367 continue;
368 }
369
370 // There is no default animation for Pip window in rotation transition, and the
371 // PipTransition will update the surface of its own window at start/finish.
372 if (isTask && change.getTaskInfo().configuration.windowConfiguration
373 .getWindowingMode() == WINDOWING_MODE_PINNED) {
374 continue;
375 }
376 // No default animation for this, so just update bounds/position.
377 startTransaction.setPosition(change.getLeash(),
378 change.getEndAbsBounds().left - info.getRootOffset().x,
379 change.getEndAbsBounds().top - info.getRootOffset().y);
380 // Seamless display transition doesn't need to animate.
381 if (isSeamlessDisplayChange) continue;
382 if (isTask || (change.hasFlags(FLAG_IN_TASK_WITH_EMBEDDED_ACTIVITY)
383 && !change.hasFlags(FLAG_FILLS_TASK))) {
384 // Update Task and embedded split window crop bounds, otherwise we may see crop
385 // on previous bounds during the rotation animation.
386 startTransaction.setWindowCrop(change.getLeash(),
387 change.getEndAbsBounds().width(), change.getEndAbsBounds().height());
388 }
389 // Rotation change of independent non display window container.
390 if (change.getParent() == null
391 && change.getStartRotation() != change.getEndRotation()) {
392 startRotationAnimation(startTransaction, change, info,
393 ROTATION_ANIMATION_ROTATE, animations, onAnimFinish);
394 continue;
395 }
396 }
397
398 // Don't animate anything that isn't independent.
399 if (!TransitionInfo.isIndependent(change, info)) continue;
400
401 Animation a = loadAnimation(info, change, wallpaperTransit);
402 if (a != null) {
403 if (isTask) {
404 final @TransitionType int type = info.getType();
405 final boolean isOpenOrCloseTransition = type == TRANSIT_OPEN
406 || type == TRANSIT_CLOSE
407 || type == TRANSIT_TO_FRONT
408 || type == TRANSIT_TO_BACK;
409 final boolean isTranslucent = (change.getFlags() & FLAG_TRANSLUCENT) != 0;
410 if (isOpenOrCloseTransition && !isTranslucent
411 && wallpaperTransit == WALLPAPER_TRANSITION_NONE) {
412 // Use the overview background as the background for the animation
413 final Context uiContext = ActivityThread.currentActivityThread()
414 .getSystemUiContext();
415 backgroundColorForTransition =
416 uiContext.getColor(R.color.overview_background);
417 }
418 }
419
420 final float cornerRadius;
421 if (a.hasRoundedCorners() && isTask) {
422 // hasRoundedCorners is currently only enabled for tasks
423 final Context displayContext =
424 mDisplayController.getDisplayContext(change.getTaskInfo().displayId);
425 cornerRadius = displayContext == null ? 0
426 : ScreenDecorationsUtils.getWindowCornerRadius(displayContext);
427 } else {
428 cornerRadius = 0;
429 }
430
431 backgroundColorForTransition = getTransitionBackgroundColorIfSet(info, change, a,
432 backgroundColorForTransition);
433
434 boolean delayedEdgeExtension = false;
435 if (!isTask && a.hasExtension()) {
436 if (!Transitions.isOpeningType(change.getMode())) {
437 // Can screenshot now (before startTransaction is applied)
438 edgeExtendWindow(change, a, startTransaction, finishTransaction);
439 } else {
440 // Need to screenshot after startTransaction is applied otherwise activity
441 // may not be visible or ready yet.
442 postStartTransactionCallbacks
443 .add(t -> edgeExtendWindow(change, a, t, finishTransaction));
444 delayedEdgeExtension = true;
445 }
446 }
447
448 final Rect clipRect = Transitions.isClosingType(change.getMode())
449 ? new Rect(mRotator.getEndBoundsInStartRotation(change))
450 : new Rect(change.getEndAbsBounds());
451 clipRect.offsetTo(0, 0);
452
453 if (delayedEdgeExtension) {
454 // If the edge extension needs to happen after the startTransition has been
455 // applied, then we want to only start the animation after the edge extension
456 // postStartTransaction callback has been run
457 postStartTransactionCallbacks.add(t ->
458 startSurfaceAnimation(animations, a, change.getLeash(), onAnimFinish,
459 mTransactionPool, mMainExecutor, mAnimExecutor,
460 change.getEndRelOffset(), cornerRadius, clipRect));
461 } else {
462 startSurfaceAnimation(animations, a, change.getLeash(), onAnimFinish,
463 mTransactionPool, mMainExecutor, mAnimExecutor,
464 change.getEndRelOffset(), cornerRadius, clipRect);
465 }
466
467 if (info.getAnimationOptions() != null) {
468 attachThumbnail(animations, onAnimFinish, change, info.getAnimationOptions(),
469 cornerRadius);
470 }
471 }
472 }
473
474 if (backgroundColorForTransition != 0) {
475 addBackgroundToTransition(info.getRootLeash(), backgroundColorForTransition,
476 startTransaction, finishTransaction);
477 }
478
479 // postStartTransactionCallbacks require that the start transaction is already
480 // applied to run otherwise they may result in flickers and UI inconsistencies.
481 boolean waitForStartTransactionApply = postStartTransactionCallbacks.size() > 0;
482 startTransaction.apply(waitForStartTransactionApply);
483
484 // Run tasks that require startTransaction to already be applied
485 for (Consumer<SurfaceControl.Transaction> postStartTransactionCallback :
486 postStartTransactionCallbacks) {
487 final SurfaceControl.Transaction t = mTransactionPool.acquire();
488 postStartTransactionCallback.accept(t);
489 t.apply();
490 mTransactionPool.release(t);
491 }
492
493 mRotator.cleanUp(finishTransaction);
494 TransitionMetrics.getInstance().reportAnimationStart(transition);
495 // run finish now in-case there are no animations
496 onAnimFinish.run();
497 return true;
498 }
499
500 @Override
501 public void mergeAnimation(@NonNull IBinder transition, @NonNull TransitionInfo info,
502 @NonNull SurfaceControl.Transaction t, @NonNull IBinder mergeTarget,
503 @NonNull Transitions.TransitionFinishCallback finishCallback) {
504 ArrayList<Animator> anims = mAnimations.get(mergeTarget);
505 if (anims == null) return;
506 for (int i = anims.size() - 1; i >= 0; --i) {
507 final Animator anim = anims.get(i);
508 mAnimExecutor.execute(anim::end);
509 }
510 }
511
512 private void startRotationAnimation(SurfaceControl.Transaction startTransaction,
513 TransitionInfo.Change change, TransitionInfo info, int animHint,
514 ArrayList<Animator> animations, Runnable onAnimFinish) {
515 final ScreenRotationAnimation anim = new ScreenRotationAnimation(mContext, mSurfaceSession,
516 mTransactionPool, startTransaction, change, info.getRootLeash(), animHint);
517 // The rotation animation may consist of 3 animations: fade-out screenshot, fade-in real
518 // content, and background color. The item of "animGroup" will be removed if the sub
519 // animation is finished. Then if the list becomes empty, the rotation animation is done.
520 final ArrayList<Animator> animGroup = new ArrayList<>(3);
521 final ArrayList<Animator> animGroupStore = new ArrayList<>(3);
522 final Runnable finishCallback = () -> {
523 if (!animGroup.isEmpty()) return;
524 anim.kill();
525 animations.removeAll(animGroupStore);
526 onAnimFinish.run();
527 };
528 anim.startAnimation(animGroup, finishCallback, mTransitionAnimationScaleSetting,
529 mMainExecutor, mAnimExecutor);
530 for (int i = animGroup.size() - 1; i >= 0; i--) {
531 final Animator animator = animGroup.get(i);
532 animGroupStore.add(animator);
533 animations.add(animator);
534 }
535 }
536
537 @Nullable
538 @Override
539 public WindowContainerTransaction handleRequest(@NonNull IBinder transition,
540 @NonNull TransitionRequestInfo request) {
541 return null;
542 }
543
544 @Override
545 public void setAnimScaleSetting(float scale) {
546 mTransitionAnimationScaleSetting = scale;
547 }
548
549 @Nullable
550 private Animation loadAnimation(@NonNull TransitionInfo info,
551 @NonNull TransitionInfo.Change change, int wallpaperTransit) {
552 Animation a;
553
554 final int type = info.getType();
555 final int flags = info.getFlags();
556 final int changeMode = change.getMode();
557 final int changeFlags = change.getFlags();
558 final boolean isOpeningType = Transitions.isOpeningType(type);
559 final boolean enter = Transitions.isOpeningType(changeMode);
560 final boolean isTask = change.getTaskInfo() != null;
561 final TransitionInfo.AnimationOptions options = info.getAnimationOptions();
562 final int overrideType = options != null ? options.getType() : ANIM_NONE;
563 final boolean canCustomContainer = !isTask || !sDisableCustomTaskAnimationProperty;
564 final Rect endBounds = Transitions.isClosingType(changeMode)
565 ? mRotator.getEndBoundsInStartRotation(change)
566 : change.getEndAbsBounds();
567
568 if (info.isKeyguardGoingAway()) {
569 a = mTransitionAnimation.loadKeyguardExitAnimation(flags,
570 (changeFlags & FLAG_SHOW_WALLPAPER) != 0);
571 } else if (type == TRANSIT_KEYGUARD_UNOCCLUDE) {
572 a = mTransitionAnimation.loadKeyguardUnoccludeAnimation();
573 } else if ((changeFlags & FLAG_IS_VOICE_INTERACTION) != 0) {
574 if (isOpeningType) {
575 a = mTransitionAnimation.loadVoiceActivityOpenAnimation(enter);
576 } else {
577 a = mTransitionAnimation.loadVoiceActivityExitAnimation(enter);
578 }
579 } else if (changeMode == TRANSIT_CHANGE) {
580 // In the absence of a specific adapter, we just want to keep everything stationary.
581 a = new AlphaAnimation(1.f, 1.f);
582 a.setDuration(TransitionAnimation.DEFAULT_APP_TRANSITION_DURATION);
583 } else if (type == TRANSIT_RELAUNCH) {
584 a = mTransitionAnimation.createRelaunchAnimation(endBounds, mInsets, endBounds);
585 } else if (overrideType == ANIM_CUSTOM
586 && (canCustomContainer || options.getOverrideTaskTransition())) {
587 a = mTransitionAnimation.loadAnimationRes(options.getPackageName(), enter
588 ? options.getEnterResId() : options.getExitResId());
589 } else if (overrideType == ANIM_OPEN_CROSS_PROFILE_APPS && enter) {
590 a = mTransitionAnimation.loadCrossProfileAppEnterAnimation();
591 } else if (overrideType == ANIM_CLIP_REVEAL) {
592 a = mTransitionAnimation.createClipRevealAnimationLocked(type, wallpaperTransit, enter,
593 endBounds, endBounds, options.getTransitionBounds());
594 } else if (overrideType == ANIM_SCALE_UP) {
595 a = mTransitionAnimation.createScaleUpAnimationLocked(type, wallpaperTransit, enter,
596 endBounds, options.getTransitionBounds());
597 } else if (overrideType == ANIM_THUMBNAIL_SCALE_UP
598 || overrideType == ANIM_THUMBNAIL_SCALE_DOWN) {
599 final boolean scaleUp = overrideType == ANIM_THUMBNAIL_SCALE_UP;
600 a = mTransitionAnimation.createThumbnailEnterExitAnimationLocked(enter, scaleUp,
601 endBounds, type, wallpaperTransit, options.getThumbnail(),
602 options.getTransitionBounds());
603 } else if ((changeFlags & FLAG_STARTING_WINDOW_TRANSFER_RECIPIENT) != 0 && isOpeningType) {
604 // This received a transferred starting window, so don't animate
605 return null;
606 } else {
607 a = loadAttributeAnimation(info, change, wallpaperTransit, mTransitionAnimation);
608 }
609
610 if (a != null) {
611 if (!a.isInitialized()) {
612 final int width = endBounds.width();
613 final int height = endBounds.height();
614 a.initialize(width, height, width, height);
615 }
616 a.restrictDuration(MAX_ANIMATION_DURATION);
617 a.scaleCurrentDuration(mTransitionAnimationScaleSetting);
618 }
619 return a;
620 }
621
622 static void startSurfaceAnimation(@NonNull ArrayList<Animator> animations,
623 @NonNull Animation anim, @NonNull SurfaceControl leash,
624 @NonNull Runnable finishCallback, @NonNull TransactionPool pool,
625 @NonNull ShellExecutor mainExecutor, @NonNull ShellExecutor animExecutor,
626 @Nullable Point position, float cornerRadius, @Nullable Rect clipRect) {
627 final SurfaceControl.Transaction transaction = pool.acquire();
628 final ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
629 final Transformation transformation = new Transformation();
630 final float[] matrix = new float[9];
631 // Animation length is already expected to be scaled.
632 va.overrideDurationScale(1.0f);
633 va.setDuration(anim.computeDurationHint());
634 final ValueAnimator.AnimatorUpdateListener updateListener = animation -> {
635 final long currentPlayTime = Math.min(va.getDuration(), va.getCurrentPlayTime());
636
637 applyTransformation(currentPlayTime, transaction, leash, anim, transformation, matrix,
638 position, cornerRadius, clipRect);
639 };
640 va.addUpdateListener(updateListener);
641
642 final Runnable finisher = () -> {
643 applyTransformation(va.getDuration(), transaction, leash, anim, transformation, matrix,
644 position, cornerRadius, clipRect);
645
646 pool.release(transaction);
647 mainExecutor.execute(() -> {
648 animations.remove(va);
649 finishCallback.run();
650 });
651 };
652 va.addListener(new AnimatorListenerAdapter() {
653 // It is possible for the end/cancel to be called more than once, which may cause
654 // issues if the animating surface has already been released. Track the finished
655 // state here to skip duplicate callbacks. See b/252872225.
656 private boolean mFinished = false;
657
658 @Override
659 public void onAnimationEnd(Animator animation) {
660 onFinish();
661 }
662
663 @Override
664 public void onAnimationCancel(Animator animation) {
665 onFinish();
666 }
667
668 private void onFinish() {
669 if (mFinished) return;
670 mFinished = true;
671 finisher.run();
672 // The update listener can continue to be called after the animation has ended if
673 // end() is called manually again before the finisher removes the animation.
674 // Remove it manually here to prevent animating a released surface.
675 // See b/252872225.
676 va.removeUpdateListener(updateListener);
677 }
678 });
679 animations.add(va);
680 animExecutor.execute(va::start);
681 }
682
683 private void attachThumbnail(@NonNull ArrayList<Animator> animations,
684 @NonNull Runnable finishCallback, TransitionInfo.Change change,
685 TransitionInfo.AnimationOptions options, float cornerRadius) {
686 final boolean isOpen = Transitions.isOpeningType(change.getMode());
687 final boolean isClose = Transitions.isClosingType(change.getMode());
688 if (isOpen) {
689 if (options.getType() == ANIM_OPEN_CROSS_PROFILE_APPS) {
690 attachCrossProfileThumbnailAnimation(animations, finishCallback, change,
691 cornerRadius);
692 } else if (options.getType() == ANIM_THUMBNAIL_SCALE_UP) {
693 attachThumbnailAnimation(animations, finishCallback, change, options, cornerRadius);
694 }
695 } else if (isClose && options.getType() == ANIM_THUMBNAIL_SCALE_DOWN) {
696 attachThumbnailAnimation(animations, finishCallback, change, options, cornerRadius);
697 }
698 }
699
700 private void attachCrossProfileThumbnailAnimation(@NonNull ArrayList<Animator> animations,
701 @NonNull Runnable finishCallback, TransitionInfo.Change change, float cornerRadius) {
702 final Rect bounds = change.getEndAbsBounds();
703 // Show the right drawable depending on the user we're transitioning to.
704 final Drawable thumbnailDrawable = change.hasFlags(FLAG_CROSS_PROFILE_OWNER_THUMBNAIL)
705 ? mContext.getDrawable(R.drawable.ic_account_circle)
706 : change.hasFlags(FLAG_CROSS_PROFILE_WORK_THUMBNAIL)
707 ? mEnterpriseThumbnailDrawable : null;
708 if (thumbnailDrawable == null) {
709 return;
710 }
711 final HardwareBuffer thumbnail = mTransitionAnimation.createCrossProfileAppsThumbnail(
712 thumbnailDrawable, bounds);
713 if (thumbnail == null) {
714 return;
715 }
716
717 final SurfaceControl.Transaction transaction = mTransactionPool.acquire();
718 final WindowThumbnail wt = WindowThumbnail.createAndAttach(mSurfaceSession,
719 change.getLeash(), thumbnail, transaction);
720 final Animation a =
721 mTransitionAnimation.createCrossProfileAppsThumbnailAnimationLocked(bounds);
722 if (a == null) {
723 return;
724 }
725
726 final Runnable finisher = () -> {
727 wt.destroy(transaction);
728 mTransactionPool.release(transaction);
729
730 finishCallback.run();
731 };
732 a.restrictDuration(MAX_ANIMATION_DURATION);
733 a.scaleCurrentDuration(mTransitionAnimationScaleSetting);
734 startSurfaceAnimation(animations, a, wt.getSurface(), finisher, mTransactionPool,
735 mMainExecutor, mAnimExecutor, change.getEndRelOffset(),
736 cornerRadius, change.getEndAbsBounds());
737 }
738
739 private void attachThumbnailAnimation(@NonNull ArrayList<Animator> animations,
740 @NonNull Runnable finishCallback, TransitionInfo.Change change,
741 TransitionInfo.AnimationOptions options, float cornerRadius) {
742 final SurfaceControl.Transaction transaction = mTransactionPool.acquire();
743 final WindowThumbnail wt = WindowThumbnail.createAndAttach(mSurfaceSession,
744 change.getLeash(), options.getThumbnail(), transaction);
745 final Rect bounds = change.getEndAbsBounds();
746 final int orientation = mContext.getResources().getConfiguration().orientation;
747 final Animation a = mTransitionAnimation.createThumbnailAspectScaleAnimationLocked(bounds,
748 mInsets, options.getThumbnail(), orientation, null /* startRect */,
749 options.getTransitionBounds(), options.getType() == ANIM_THUMBNAIL_SCALE_UP);
750
751 final Runnable finisher = () -> {
752 wt.destroy(transaction);
753 mTransactionPool.release(transaction);
754
755 finishCallback.run();
756 };
757 a.restrictDuration(MAX_ANIMATION_DURATION);
758 a.scaleCurrentDuration(mTransitionAnimationScaleSetting);
759 startSurfaceAnimation(animations, a, wt.getSurface(), finisher, mTransactionPool,
760 mMainExecutor, mAnimExecutor, change.getEndRelOffset(),
761 cornerRadius, change.getEndAbsBounds());
762 }
763
764 private static int getWallpaperTransitType(TransitionInfo info) {
765 boolean hasOpenWallpaper = false;
766 boolean hasCloseWallpaper = false;
767
768 for (int i = info.getChanges().size() - 1; i >= 0; --i) {
769 final TransitionInfo.Change change = info.getChanges().get(i);
770 if ((change.getFlags() & FLAG_SHOW_WALLPAPER) != 0) {
771 if (Transitions.isOpeningType(change.getMode())) {
772 hasOpenWallpaper = true;
773 } else if (Transitions.isClosingType(change.getMode())) {
774 hasCloseWallpaper = true;
775 }
776 }
777 }
778
779 if (hasOpenWallpaper && hasCloseWallpaper) {
780 return Transitions.isOpeningType(info.getType())
781 ? WALLPAPER_TRANSITION_INTRA_OPEN : WALLPAPER_TRANSITION_INTRA_CLOSE;
782 } else if (hasOpenWallpaper) {
783 return WALLPAPER_TRANSITION_OPEN;
784 } else if (hasCloseWallpaper) {
785 return WALLPAPER_TRANSITION_CLOSE;
786 } else {
787 return WALLPAPER_TRANSITION_NONE;
788 }
789 }
790
791 private static void applyTransformation(long time, SurfaceControl.Transaction t,
792 SurfaceControl leash, Animation anim, Transformation transformation, float[] matrix,
793 Point position, float cornerRadius, @Nullable Rect immutableClipRect) {
794 anim.getTransformation(time, transformation);
795 if (position != null) {
796 transformation.getMatrix().postTranslate(position.x, position.y);
797 }
798 t.setMatrix(leash, transformation.getMatrix(), matrix);
799 t.setAlpha(leash, transformation.getAlpha());
800
801 final Rect clipRect = immutableClipRect == null ? null : new Rect(immutableClipRect);
802 Insets extensionInsets = Insets.min(transformation.getInsets(), Insets.NONE);
803 if (!extensionInsets.equals(Insets.NONE) && clipRect != null && !clipRect.isEmpty()) {
804 // Clip out any overflowing edge extension
805 clipRect.inset(extensionInsets);
806 t.setCrop(leash, clipRect);
807 }
808
809 if (anim.hasRoundedCorners() && cornerRadius > 0 && clipRect != null) {
810 // We can only apply rounded corner if a crop is set
811 t.setCrop(leash, clipRect);
812 t.setCornerRadius(leash, cornerRadius);
813 }
814
815 t.setFrameTimelineVsync(Choreographer.getInstance().getVsyncId());
816 t.apply();
817 }
818 }