Debian Codegraph @

libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java

raw symbols SCIP
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 com.android.wm.shell.pip;
18
19 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
20 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
21 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
22 import static android.util.RotationUtils.deltaRotation;
23 import static android.util.RotationUtils.rotateBounds;
24
25 import static com.android.wm.shell.ShellTaskOrganizer.TASK_LISTENER_TYPE_PIP;
26 import static com.android.wm.shell.ShellTaskOrganizer.taskListenerTypeToString;
27 import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
28 import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
29 import static com.android.wm.shell.pip.PipAnimationController.ANIM_TYPE_ALPHA;
30 import static com.android.wm.shell.pip.PipAnimationController.ANIM_TYPE_BOUNDS;
31 import static com.android.wm.shell.pip.PipAnimationController.FRACTION_START;
32 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_EXPAND_OR_UNEXPAND;
33 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_LEAVE_PIP;
34 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_LEAVE_PIP_TO_SPLIT_SCREEN;
35 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_NONE;
36 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_REMOVE_STACK;
37 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_SAME;
38 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_SNAP_AFTER_RESIZE;
39 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_TO_PIP;
40 import static com.android.wm.shell.pip.PipAnimationController.TRANSITION_DIRECTION_USER_RESIZE;
41 import static com.android.wm.shell.pip.PipAnimationController.isInPipDirection;
42 import static com.android.wm.shell.pip.PipAnimationController.isOutPipDirection;
43 import static com.android.wm.shell.pip.PipAnimationController.isRemovePipDirection;
44 import static com.android.wm.shell.transition.Transitions.ENABLE_SHELL_TRANSITIONS;
45 import static com.android.wm.shell.transition.Transitions.TRANSIT_EXIT_PIP;
46 import static com.android.wm.shell.transition.Transitions.TRANSIT_EXIT_PIP_TO_SPLIT;
47 import static com.android.wm.shell.transition.Transitions.TRANSIT_REMOVE_PIP;
48
49 import android.animation.Animator;
50 import android.animation.AnimatorListenerAdapter;
51 import android.animation.ValueAnimator;
52 import android.annotation.NonNull;
53 import android.annotation.Nullable;
54 import android.app.ActivityManager;
55 import android.app.ActivityTaskManager;
56 import android.app.PictureInPictureParams;
57 import android.app.TaskInfo;
58 import android.content.ComponentName;
59 import android.content.Context;
60 import android.content.pm.ActivityInfo;
61 import android.content.res.Configuration;
62 import android.graphics.Rect;
63 import android.os.RemoteException;
64 import android.os.SystemClock;
65 import android.util.Log;
66 import android.view.Choreographer;
67 import android.view.Display;
68 import android.view.Surface;
69 import android.view.SurfaceControl;
70 import android.window.TaskOrganizer;
71 import android.window.TaskSnapshot;
72 import android.window.WindowContainerToken;
73 import android.window.WindowContainerTransaction;
74
75 import com.android.internal.annotations.VisibleForTesting;
76 import com.android.internal.protolog.common.ProtoLog;
77 import com.android.wm.shell.R;
78 import com.android.wm.shell.ShellTaskOrganizer;
79 import com.android.wm.shell.animation.Interpolators;
80 import com.android.wm.shell.common.DisplayController;
81 import com.android.wm.shell.common.ScreenshotUtils;
82 import com.android.wm.shell.common.ShellExecutor;
83 import com.android.wm.shell.common.SyncTransactionQueue;
84 import com.android.wm.shell.common.annotations.ShellMainThread;
85 import com.android.wm.shell.pip.phone.PipMotionHelper;
86 import com.android.wm.shell.protolog.ShellProtoLogGroup;
87 import com.android.wm.shell.splitscreen.SplitScreenController;
88 import com.android.wm.shell.transition.Transitions;
89
90 import java.io.PrintWriter;
91 import java.util.Objects;
92 import java.util.Optional;
93 import java.util.function.Consumer;
94 import java.util.function.IntConsumer;
95
96 /**
97 * Manages PiP tasks such as resize and offset.
98 *
99 * This class listens on {@link TaskOrganizer} callbacks for windowing mode change
100 * both to and from PiP and issues corresponding animation if applicable.
101 * Normally, we apply series of {@link SurfaceControl.Transaction} when the animator is running
102 * and files a final {@link WindowContainerTransaction} at the end of the transition.
103 *
104 * This class is also responsible for general resize/offset PiP operations within SysUI component,
105 * see also {@link PipMotionHelper}.
106 */
107 public class PipTaskOrganizer implements ShellTaskOrganizer.TaskListener,
108 DisplayController.OnDisplaysChangedListener, ShellTaskOrganizer.FocusListener {
109 private static final String TAG = PipTaskOrganizer.class.getSimpleName();
110 private static final boolean DEBUG = false;
111 /**
112 * The alpha type is set for swiping to home. But the swiped task may not enter PiP. And if
113 * another task enters PiP by non-swipe ways, e.g. call API in foreground or switch to 3-button
114 * navigation, then the alpha type is unexpected.
115 */
116 private static final int ONE_SHOT_ALPHA_ANIMATION_TIMEOUT_MS = 1000;
117
118 /**
119 * The fixed start delay in ms when fading out the content overlay from bounds animation.
120 * This is to overcome the flicker caused by configuration change when rotating from landscape
121 * to portrait PiP in button navigation mode.
122 */
123 private static final int CONTENT_OVERLAY_FADE_OUT_DELAY_MS = 500;
124
125 private final Context mContext;
126 private final SyncTransactionQueue mSyncTransactionQueue;
127 private final PipBoundsState mPipBoundsState;
128 private final PipBoundsAlgorithm mPipBoundsAlgorithm;
129 private final @NonNull PipMenuController mPipMenuController;
130 private final PipAnimationController mPipAnimationController;
131 protected final PipTransitionController mPipTransitionController;
132 protected final PipParamsChangedForwarder mPipParamsChangedForwarder;
133 private final PipUiEventLogger mPipUiEventLoggerLogger;
134 private final int mEnterAnimationDuration;
135 private final int mExitAnimationDuration;
136 private final int mCrossFadeAnimationDuration;
137 private final PipSurfaceTransactionHelper mSurfaceTransactionHelper;
138 private final Optional<SplitScreenController> mSplitScreenOptional;
139 protected final ShellTaskOrganizer mTaskOrganizer;
140 protected final ShellExecutor mMainExecutor;
141
142 // These callbacks are called on the update thread
143 private final PipAnimationController.PipAnimationCallback mPipAnimationCallback =
144 new PipAnimationController.PipAnimationCallback() {
145 @Override
146 public void onPipAnimationStart(TaskInfo taskInfo,
147 PipAnimationController.PipTransitionAnimator animator) {
148 final int direction = animator.getTransitionDirection();
149 sendOnPipTransitionStarted(direction);
150 }
151
152 @Override
153 public void onPipAnimationEnd(TaskInfo taskInfo, SurfaceControl.Transaction tx,
154 PipAnimationController.PipTransitionAnimator animator) {
155 final int direction = animator.getTransitionDirection();
156 final int animationType = animator.getAnimationType();
157 final Rect destinationBounds = animator.getDestinationBounds();
158 if (isInPipDirection(direction) && animator.getContentOverlayLeash() != null) {
159 fadeOutAndRemoveOverlay(animator.getContentOverlayLeash(),
160 animator::clearContentOverlay, true /* withStartDelay*/);
161 }
162 if (mWaitForFixedRotation && animationType == ANIM_TYPE_BOUNDS
163 && direction == TRANSITION_DIRECTION_TO_PIP) {
164 // Notify the display to continue the deferred orientation change.
165 final WindowContainerTransaction wct = new WindowContainerTransaction();
166 wct.scheduleFinishEnterPip(mToken, destinationBounds);
167 mTaskOrganizer.applyTransaction(wct);
168 // The final task bounds will be applied by onFixedRotationFinished so that all
169 // coordinates are in new rotation.
170 mSurfaceTransactionHelper.round(tx, mLeash, isInPip());
171 mDeferredAnimEndTransaction = tx;
172 return;
173 }
174 final boolean isExitPipDirection = isOutPipDirection(direction)
175 || isRemovePipDirection(direction);
176 if (mPipTransitionState.getTransitionState() != PipTransitionState.EXITING_PIP
177 || isExitPipDirection) {
178 // Finish resize as long as we're not exiting PIP, or, if we are, only if this is
179 // the end of an exit PIP animation.
180 // This is necessary in case there was a resize animation ongoing when exit PIP
181 // started, in which case the first resize will be skipped to let the exit
182 // operation handle the final resize out of PIP mode. See b/185306679.
183 finishResizeDelayedIfNeeded(() -> {
184 finishResize(tx, destinationBounds, direction, animationType);
185 sendOnPipTransitionFinished(direction);
186 });
187 }
188 }
189
190 @Override
191 public void onPipAnimationCancel(TaskInfo taskInfo,
192 PipAnimationController.PipTransitionAnimator animator) {
193 final int direction = animator.getTransitionDirection();
194 if (isInPipDirection(direction) && animator.getContentOverlayLeash() != null) {
195 fadeOutAndRemoveOverlay(animator.getContentOverlayLeash(),
196 animator::clearContentOverlay, true /* withStartDelay */);
197 }
198 sendOnPipTransitionCancelled(direction);
199 }
200 };
201
202 /**
203 * Finishes resizing the PiP, delaying the operation if it has to be synced with the PiP menu.
204 *
205 * This is done to avoid a race condition between the last transaction applied in
206 * onPipAnimationUpdate and the finishResize in onPipAnimationEnd. The transaction in
207 * onPipAnimationUpdate is applied directly from WmShell, while onPipAnimationEnd creates a
208 * WindowContainerTransaction in finishResize, which is to be applied by WmCore later. Normally,
209 * the WCT should be the last transaction to finish the animation. However, it may happen that
210 * it gets applied *before* the transaction created by the last onPipAnimationUpdate. This
211 * happens only when the PiP surface transaction has to be synced with the PiP menu due to the
212 * necessity for a delay when syncing the PiP surface animation with the PiP menu surface
213 * animation and redrawing the PiP menu contents. As a result, the PiP surface gets scaled after
214 * the new bounds are applied by WmCore, which makes the PiP surface have unexpected bounds.
215 *
216 * To avoid this, we delay the finishResize operation until
217 * the next frame. This aligns the last onAnimationUpdate transaction with the WCT application.
218 */
219 private void finishResizeDelayedIfNeeded(Runnable finishResizeRunnable) {
220 if (!shouldSyncPipTransactionWithMenu()) {
221 finishResizeRunnable.run();
222 return;
223 }
224
225 // Delay the finishResize to the next frame
226 Choreographer.getInstance().postCallback(Choreographer.CALLBACK_COMMIT, () -> {
227 mMainExecutor.execute(finishResizeRunnable);
228 }, null);
229 }
230
231 private boolean shouldSyncPipTransactionWithMenu() {
232 return mPipMenuController.isMenuVisible();
233 }
234
235 @VisibleForTesting
236 final PipTransitionController.PipTransitionCallback mPipTransitionCallback =
237 new PipTransitionController.PipTransitionCallback() {
238 @Override
239 public void onPipTransitionStarted(int direction, Rect pipBounds) {}
240
241 @Override
242 public void onPipTransitionFinished(int direction) {
243 // Apply the deferred RunningTaskInfo if applicable after all proper callbacks
244 // are sent.
245 if (direction == TRANSITION_DIRECTION_TO_PIP && mDeferredTaskInfo != null) {
246 onTaskInfoChanged(mDeferredTaskInfo);
247 mDeferredTaskInfo = null;
248 }
249 }
250
251 @Override
252 public void onPipTransitionCanceled(int direction) {}
253 };
254
255 private final PipAnimationController.PipTransactionHandler mPipTransactionHandler =
256 new PipAnimationController.PipTransactionHandler() {
257 @Override
258 public boolean handlePipTransaction(SurfaceControl leash,
259 SurfaceControl.Transaction tx, Rect destinationBounds) {
260 if (shouldSyncPipTransactionWithMenu()) {
261 mPipMenuController.movePipMenu(leash, tx, destinationBounds);
262 return true;
263 }
264 return false;
265 }
266 };
267
268 private ActivityManager.RunningTaskInfo mTaskInfo;
269 // To handle the edge case that onTaskInfoChanged callback is received during the entering
270 // PiP transition, where we do not want to intercept the transition but still want to apply the
271 // changed RunningTaskInfo when it finishes.
272 private ActivityManager.RunningTaskInfo mDeferredTaskInfo;
273 private WindowContainerToken mToken;
274 private SurfaceControl mLeash;
275 protected PipTransitionState mPipTransitionState;
276 private @PipAnimationController.AnimationType int mOneShotAnimationType = ANIM_TYPE_BOUNDS;
277 private long mLastOneShotAlphaAnimationTime;
278 private PipSurfaceTransactionHelper.SurfaceControlTransactionFactory
279 mSurfaceControlTransactionFactory;
280 protected PictureInPictureParams mPictureInPictureParams;
281 private IntConsumer mOnDisplayIdChangeCallback;
282 /**
283 * The end transaction of PiP animation for switching between PiP and fullscreen with
284 * orientation change. The transaction should be applied after the display is rotated.
285 */
286 private SurfaceControl.Transaction mDeferredAnimEndTransaction;
287 /** Whether the existing PiP is hidden by alpha. */
288 private boolean mHasFadeOut;
289
290 /**
291 * If set to {@code true}, the entering animation will be skipped and we will wait for
292 * {@link #onFixedRotationFinished(int)} callback to actually enter PiP.
293 */
294 private boolean mWaitForFixedRotation;
295
296 /**
297 * The rotation that the display will apply after expanding PiP to fullscreen. This is only
298 * meaningful if {@link #mWaitForFixedRotation} is true.
299 */
300 private @Surface.Rotation int mNextRotation;
301
302 private @Surface.Rotation int mCurrentRotation;
303
304 /**
305 * An optional overlay used to mask content changing between an app in/out of PiP, only set if
306 * {@link PipTransitionState#getInSwipePipToHomeTransition()} is true.
307 */
308 @Nullable
309 SurfaceControl mSwipePipToHomeOverlay;
310
311 public PipTaskOrganizer(Context context,
312 @NonNull SyncTransactionQueue syncTransactionQueue,
313 @NonNull PipTransitionState pipTransitionState,
314 @NonNull PipBoundsState pipBoundsState,
315 @NonNull PipBoundsAlgorithm boundsHandler,
316 @NonNull PipMenuController pipMenuController,
317 @NonNull PipAnimationController pipAnimationController,
318 @NonNull PipSurfaceTransactionHelper surfaceTransactionHelper,
319 @NonNull PipTransitionController pipTransitionController,
320 @NonNull PipParamsChangedForwarder pipParamsChangedForwarder,
321 Optional<SplitScreenController> splitScreenOptional,
322 @NonNull DisplayController displayController,
323 @NonNull PipUiEventLogger pipUiEventLogger,
324 @NonNull ShellTaskOrganizer shellTaskOrganizer,
325 @ShellMainThread ShellExecutor mainExecutor) {
326 mContext = context;
327 mSyncTransactionQueue = syncTransactionQueue;
328 mPipTransitionState = pipTransitionState;
329 mPipBoundsState = pipBoundsState;
330 mPipBoundsAlgorithm = boundsHandler;
331 mPipMenuController = pipMenuController;
332 mPipTransitionController = pipTransitionController;
333 mPipParamsChangedForwarder = pipParamsChangedForwarder;
334 mEnterAnimationDuration = context.getResources()
335 .getInteger(R.integer.config_pipEnterAnimationDuration);
336 mExitAnimationDuration = context.getResources()
337 .getInteger(R.integer.config_pipExitAnimationDuration);
338 mCrossFadeAnimationDuration = context.getResources()
339 .getInteger(R.integer.config_pipCrossfadeAnimationDuration);
340 mSurfaceTransactionHelper = surfaceTransactionHelper;
341 mPipAnimationController = pipAnimationController;
342 mPipUiEventLoggerLogger = pipUiEventLogger;
343 mSurfaceControlTransactionFactory =
344 new PipSurfaceTransactionHelper.VsyncSurfaceControlTransactionFactory();
345 mSplitScreenOptional = splitScreenOptional;
346 mTaskOrganizer = shellTaskOrganizer;
347 mMainExecutor = mainExecutor;
348
349 // TODO: Can be removed once wm components are created on the shell-main thread
350 mMainExecutor.execute(() -> {
351 mTaskOrganizer.addListenerForType(this, TASK_LISTENER_TYPE_PIP);
352 });
353 mTaskOrganizer.addFocusListener(this);
354 mPipTransitionController.setPipOrganizer(this);
355 displayController.addDisplayWindowListener(this);
356 pipTransitionController.registerPipTransitionCallback(mPipTransitionCallback);
357 }
358
359 public PipTransitionController getTransitionController() {
360 return mPipTransitionController;
361 }
362
363 public Rect getCurrentOrAnimatingBounds() {
364 PipAnimationController.PipTransitionAnimator animator =
365 mPipAnimationController.getCurrentAnimator();
366 if (animator != null && animator.isRunning()) {
367 return new Rect(animator.getDestinationBounds());
368 }
369 return mPipBoundsState.getBounds();
370 }
371
372 public boolean isInPip() {
373 return mPipTransitionState.isInPip();
374 }
375
376 private boolean isLaunchIntoPipTask() {
377 return mPictureInPictureParams != null && mPictureInPictureParams.isLaunchIntoPip();
378 }
379
380 /**
381 * Returns whether the entry animation is waiting to be started.
382 */
383 public boolean isEntryScheduled() {
384 return mPipTransitionState.getTransitionState() == PipTransitionState.ENTRY_SCHEDULED;
385 }
386
387 /**
388 * Registers a callback when a display change has been detected when we enter PiP.
389 */
390 public void registerOnDisplayIdChangeCallback(IntConsumer onDisplayIdChangeCallback) {
391 mOnDisplayIdChangeCallback = onDisplayIdChangeCallback;
392 }
393
394 /**
395 * Sets the preferred animation type for one time.
396 * This is typically used to set the animation type to
397 * {@link PipAnimationController#ANIM_TYPE_ALPHA}.
398 */
399 public void setOneShotAnimationType(@PipAnimationController.AnimationType int animationType) {
400 mOneShotAnimationType = animationType;
401 if (animationType == ANIM_TYPE_ALPHA) {
402 mLastOneShotAlphaAnimationTime = SystemClock.uptimeMillis();
403 }
404 }
405
406 /**
407 * Callback when Launcher starts swipe-pip-to-home operation.
408 * @return {@link Rect} for destination bounds.
409 */
410 public Rect startSwipePipToHome(ComponentName componentName, ActivityInfo activityInfo,
411 PictureInPictureParams pictureInPictureParams) {
412 mPipTransitionState.setInSwipePipToHomeTransition(true);
413 sendOnPipTransitionStarted(TRANSITION_DIRECTION_TO_PIP);
414 setBoundsStateForEntry(componentName, pictureInPictureParams, activityInfo);
415 return mPipBoundsAlgorithm.getEntryDestinationBounds();
416 }
417
418 /**
419 * Callback when launcher finishes swipe-pip-to-home operation.
420 * Expect {@link #onTaskAppeared(ActivityManager.RunningTaskInfo, SurfaceControl)} afterwards.
421 */
422 public void stopSwipePipToHome(int taskId, ComponentName componentName, Rect destinationBounds,
423 SurfaceControl overlay) {
424 // do nothing if there is no startSwipePipToHome being called before
425 if (!mPipTransitionState.getInSwipePipToHomeTransition()) {
426 return;
427 }
428 mPipBoundsState.setBounds(destinationBounds);
429 mSwipePipToHomeOverlay = overlay;
430 if (ENABLE_SHELL_TRANSITIONS && overlay != null) {
431 // With Shell transition, the overlay was attached to the remote transition leash, which
432 // will be removed when the current transition is finished, so we need to reparent it
433 // to the actual Task surface now.
434 // PipTransition is responsible to fade it out and cleanup when finishing the enter PIP
435 // transition.
436 final SurfaceControl.Transaction t = new SurfaceControl.Transaction();
437 mTaskOrganizer.reparentChildSurfaceToTask(taskId, overlay, t);
438 t.setLayer(overlay, Integer.MAX_VALUE);
439 t.apply();
440 }
441 }
442
443 public ActivityManager.RunningTaskInfo getTaskInfo() {
444 return mTaskInfo;
445 }
446
447 public SurfaceControl getSurfaceControl() {
448 return mLeash;
449 }
450
451 private void setBoundsStateForEntry(ComponentName componentName,
452 PictureInPictureParams params, ActivityInfo activityInfo) {
453 mPipBoundsState.setBoundsStateForEntry(componentName, activityInfo, params,
454 mPipBoundsAlgorithm);
455 }
456
457 /**
458 * Expands PiP to the previous bounds, this is done in two phases using
459 * {@link WindowContainerTransaction}
460 * - setActivityWindowingMode to either fullscreen or split-secondary at beginning of the
461 * transaction. without changing the windowing mode of the Task itself. This makes sure the
462 * activity render it's final configuration while the Task is still in PiP.
463 * - setWindowingMode to undefined at the end of transition
464 * @param animationDurationMs duration in millisecond for the exiting PiP transition
465 * @param requestEnterSplit whether the enterSplit button is pressed on PiP or not.
466 * Indicate the user wishes to directly put PiP into split screen
467 * mode.
468 */
469 public void exitPip(int animationDurationMs, boolean requestEnterSplit) {
470 if (!mPipTransitionState.isInPip()
471 || mPipTransitionState.getTransitionState() == PipTransitionState.EXITING_PIP
472 || mToken == null) {
473 ProtoLog.wtf(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
474 "%s: Not allowed to exitPip in current state"
475 + " mState=%d mToken=%s", TAG, mPipTransitionState.getTransitionState(),
476 mToken);
477 return;
478 }
479
480 final WindowContainerTransaction wct = new WindowContainerTransaction();
481 if (isLaunchIntoPipTask()) {
482 exitLaunchIntoPipTask(wct);
483 return;
484 }
485
486 if (ENABLE_SHELL_TRANSITIONS) {
487 if (requestEnterSplit && mSplitScreenOptional.isPresent()) {
488 mSplitScreenOptional.get().prepareEnterSplitScreen(wct, mTaskInfo,
489 isPipTopLeft()
490 ? SPLIT_POSITION_TOP_OR_LEFT : SPLIT_POSITION_BOTTOM_OR_RIGHT);
491 mPipTransitionController.startExitTransition(
492 TRANSIT_EXIT_PIP_TO_SPLIT, wct, null /* destinationBounds */);
493 return;
494 }
495 }
496
497 final Rect destinationBounds = getExitDestinationBounds();
498 final int direction = syncWithSplitScreenBounds(destinationBounds, requestEnterSplit)
499 ? TRANSITION_DIRECTION_LEAVE_PIP_TO_SPLIT_SCREEN
500 : TRANSITION_DIRECTION_LEAVE_PIP;
501
502 if (Transitions.ENABLE_SHELL_TRANSITIONS && direction == TRANSITION_DIRECTION_LEAVE_PIP) {
503 // When exit to fullscreen with Shell transition enabled, we update the Task windowing
504 // mode directly so that it can also trigger display rotation and visibility update in
505 // the same transition if there will be any.
506 wct.setWindowingMode(mToken, getOutPipWindowingMode());
507 // We can inherit the parent bounds as it is going to be fullscreen. The
508 // destinationBounds calculated above will be incorrect if this is with rotation.
509 wct.setBounds(mToken, null);
510 } else {
511 final SurfaceControl.Transaction tx =
512 mSurfaceControlTransactionFactory.getTransaction();
513 mSurfaceTransactionHelper.scale(tx, mLeash, destinationBounds,
514 mPipBoundsState.getBounds());
515 tx.setWindowCrop(mLeash, destinationBounds.width(), destinationBounds.height());
516 // We set to fullscreen here for now, but later it will be set to UNDEFINED for
517 // the proper windowing mode to take place. See #applyWindowingModeChangeOnExit.
518 wct.setActivityWindowingMode(mToken, WINDOWING_MODE_FULLSCREEN);
519 wct.setBounds(mToken, destinationBounds);
520 wct.setBoundsChangeTransaction(mToken, tx);
521 }
522
523 // Cancel the existing animator if there is any.
524 // TODO(b/232439933): this is disabled temporarily to unblock b/234502692.
525 // cancelCurrentAnimator();
526
527 // Set the exiting state first so if there is fixed rotation later, the running animation
528 // won't be interrupted by alpha animation for existing PiP.
529 mPipTransitionState.setTransitionState(PipTransitionState.EXITING_PIP);
530
531 if (Transitions.ENABLE_SHELL_TRANSITIONS) {
532 mPipTransitionController.startExitTransition(TRANSIT_EXIT_PIP, wct, destinationBounds);
533 return;
534 }
535 mSyncTransactionQueue.queue(wct);
536 mSyncTransactionQueue.runInSync(t -> {
537 // Make sure to grab the latest source hint rect as it could have been
538 // updated right after applying the windowing mode change.
539 final Rect sourceHintRect = PipBoundsAlgorithm.getValidSourceHintRect(
540 mPictureInPictureParams, destinationBounds);
541 final PipAnimationController.PipTransitionAnimator<?> animator =
542 animateResizePip(mPipBoundsState.getBounds(), destinationBounds, sourceHintRect,
543 direction, animationDurationMs, 0 /* startingAngle */);
544 if (animator != null) {
545 // Even though the animation was started above, re-apply the transaction for the
546 // first frame using the SurfaceControl.Transaction supplied by the
547 // SyncTransactionQueue. This is necessary because the initial surface transform
548 // may not be applied until the next frame if a different Transaction than the one
549 // supplied is used, resulting in 1 frame not being cropped to the source rect
550 // hint during expansion that causes a visible jank/flash. See b/184166183.
551 animator.applySurfaceControlTransaction(mLeash, t, FRACTION_START);
552 }
553 });
554 }
555
556 /** Returns the bounds to restore to when exiting PIP mode. */
557 public Rect getExitDestinationBounds() {
558 return mPipBoundsState.getDisplayBounds();
559 }
560
561 private void exitLaunchIntoPipTask(WindowContainerTransaction wct) {
562 wct.startTask(mTaskInfo.launchIntoPipHostTaskId, null /* ActivityOptions */);
563 mTaskOrganizer.applyTransaction(wct);
564
565 // Remove the PiP with fade-out animation right after the host Task is brought to front.
566 removePip();
567 }
568
569 private void applyWindowingModeChangeOnExit(WindowContainerTransaction wct, int direction) {
570 // Reset the final windowing mode.
571 wct.setWindowingMode(mToken, getOutPipWindowingMode());
572 // Simply reset the activity mode set prior to the animation running.
573 wct.setActivityWindowingMode(mToken, WINDOWING_MODE_UNDEFINED);
574 }
575
576 /**
577 * Removes PiP immediately.
578 */
579 public void removePip() {
580 if (!mPipTransitionState.isInPip() || mToken == null) {
581 ProtoLog.wtf(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
582 "%s: Not allowed to removePip in current state"
583 + " mState=%d mToken=%s", TAG, mPipTransitionState.getTransitionState(),
584 mToken);
585 return;
586 }
587
588 // removePipImmediately is expected when the following animation finishes.
589 ValueAnimator animator = mPipAnimationController
590 .getAnimator(mTaskInfo, mLeash, mPipBoundsState.getBounds(),
591 1f /* alphaStart */, 0f /* alphaEnd */)
592 .setTransitionDirection(TRANSITION_DIRECTION_REMOVE_STACK)
593 .setPipTransactionHandler(mPipTransactionHandler)
594 .setPipAnimationCallback(mPipAnimationCallback);
595 animator.setDuration(mExitAnimationDuration);
596 animator.setInterpolator(Interpolators.ALPHA_OUT);
597 animator.start();
598 mPipTransitionState.setTransitionState(PipTransitionState.EXITING_PIP);
599 }
600
601 private void removePipImmediately() {
602 if (Transitions.ENABLE_SHELL_TRANSITIONS) {
603 final WindowContainerTransaction wct = new WindowContainerTransaction();
604 wct.setBounds(mToken, null);
605 wct.setWindowingMode(mToken, getOutPipWindowingMode());
606 wct.reorder(mToken, false);
607 mPipTransitionController.startExitTransition(TRANSIT_REMOVE_PIP, wct,
608 null /* destinationBounds */);
609 return;
610 }
611
612 try {
613 // Reset the task bounds first to ensure the activity configuration is reset as well
614 final WindowContainerTransaction wct = new WindowContainerTransaction();
615 wct.setBounds(mToken, null);
616 mTaskOrganizer.applyTransaction(wct);
617
618 ActivityTaskManager.getService().removeRootTasksInWindowingModes(
619 new int[]{ WINDOWING_MODE_PINNED });
620 } catch (RemoteException e) {
621 ProtoLog.e(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
622 "%s: Failed to remove PiP, %s",
623 TAG, e);
624 }
625 }
626
627 @Override
628 public void onTaskAppeared(ActivityManager.RunningTaskInfo info, SurfaceControl leash) {
629 Objects.requireNonNull(info, "Requires RunningTaskInfo");
630 mTaskInfo = info;
631 mToken = mTaskInfo.token;
632 mPipTransitionState.setTransitionState(PipTransitionState.TASK_APPEARED);
633 mLeash = leash;
634 mPictureInPictureParams = mTaskInfo.pictureInPictureParams;
635 setBoundsStateForEntry(mTaskInfo.topActivity, mPictureInPictureParams,
636 mTaskInfo.topActivityInfo);
637 if (mPictureInPictureParams != null) {
638 mPipParamsChangedForwarder.notifyActionsChanged(mPictureInPictureParams.getActions(),
639 mPictureInPictureParams.getCloseAction());
640 mPipParamsChangedForwarder.notifyTitleChanged(
641 mPictureInPictureParams.getTitle());
642 mPipParamsChangedForwarder.notifySubtitleChanged(
643 mPictureInPictureParams.getSubtitle());
644 }
645
646 mPipUiEventLoggerLogger.setTaskInfo(mTaskInfo);
647 mPipUiEventLoggerLogger.log(PipUiEventLogger.PipUiEventEnum.PICTURE_IN_PICTURE_ENTER);
648
649 // If the displayId of the task is different than what PipBoundsHandler has, then update
650 // it. This is possible if we entered PiP on an external display.
651 if (info.displayId != mPipBoundsState.getDisplayId()
652 && mOnDisplayIdChangeCallback != null) {
653 mOnDisplayIdChangeCallback.accept(info.displayId);
654 }
655
656 if (mPipTransitionState.getInSwipePipToHomeTransition()) {
657 if (!mWaitForFixedRotation) {
658 onEndOfSwipePipToHomeTransition();
659 } else {
660 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
661 "%s: Defer onTaskAppeared-SwipePipToHome until end of fixed rotation.",
662 TAG);
663 }
664 return;
665 }
666
667 if (mOneShotAnimationType == ANIM_TYPE_ALPHA
668 && SystemClock.uptimeMillis() - mLastOneShotAlphaAnimationTime
669 > ONE_SHOT_ALPHA_ANIMATION_TIMEOUT_MS) {
670 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
671 "%s: Alpha animation is expired. Use bounds animation.", TAG);
672 mOneShotAnimationType = ANIM_TYPE_BOUNDS;
673 }
674
675 if (Transitions.ENABLE_SHELL_TRANSITIONS) {
676 // For Shell transition, we will animate the window in PipTransition#startAnimation
677 // instead of #onTaskAppeared.
678 return;
679 }
680
681 if (mWaitForFixedRotation) {
682 onTaskAppearedWithFixedRotation();
683 return;
684 }
685
686 final Rect destinationBounds = mPipBoundsAlgorithm.getEntryDestinationBounds();
687 Objects.requireNonNull(destinationBounds, "Missing destination bounds");
688 final Rect currentBounds = mTaskInfo.configuration.windowConfiguration.getBounds();
689
690 if (mOneShotAnimationType == ANIM_TYPE_BOUNDS) {
691 mPipMenuController.attach(mLeash);
692 final Rect sourceHintRect = PipBoundsAlgorithm.getValidSourceHintRect(
693 info.pictureInPictureParams, currentBounds);
694 scheduleAnimateResizePip(currentBounds, destinationBounds, 0 /* startingAngle */,
695 sourceHintRect, TRANSITION_DIRECTION_TO_PIP, mEnterAnimationDuration,
696 null /* updateBoundsCallback */);
697 mPipTransitionState.setTransitionState(PipTransitionState.ENTERING_PIP);
698 } else if (mOneShotAnimationType == ANIM_TYPE_ALPHA) {
699 enterPipWithAlphaAnimation(destinationBounds, mEnterAnimationDuration);
700 mOneShotAnimationType = ANIM_TYPE_BOUNDS;
701 } else {
702 throw new RuntimeException("Unrecognized animation type: " + mOneShotAnimationType);
703 }
704 }
705
706 private void onTaskAppearedWithFixedRotation() {
707 if (mOneShotAnimationType == ANIM_TYPE_ALPHA) {
708 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
709 "%s: Defer entering PiP alpha animation, fixed rotation is ongoing", TAG);
710 // If deferred, hside the surface till fixed rotation is completed.
711 final SurfaceControl.Transaction tx =
712 mSurfaceControlTransactionFactory.getTransaction();
713 tx.setAlpha(mLeash, 0f);
714 tx.show(mLeash);
715 tx.apply();
716 mOneShotAnimationType = ANIM_TYPE_BOUNDS;
717 return;
718 }
719 final Rect currentBounds = mTaskInfo.configuration.windowConfiguration.getBounds();
720 final Rect sourceHintRect = PipBoundsAlgorithm.getValidSourceHintRect(
721 mPictureInPictureParams, currentBounds);
722 final Rect destinationBounds = mPipBoundsAlgorithm.getEntryDestinationBounds();
723 animateResizePip(currentBounds, destinationBounds, sourceHintRect,
724 TRANSITION_DIRECTION_TO_PIP, mEnterAnimationDuration, 0 /* startingAngle */);
725 mPipTransitionState.setTransitionState(PipTransitionState.ENTERING_PIP);
726 }
727
728 /**
729 * Called when the display rotation handling is skipped (e.g. when rotation happens while in
730 * the middle of an entry transition).
731 */
732 public void onDisplayRotationSkipped() {
733 if (isEntryScheduled()) {
734 // The PIP animation is scheduled to start with the previous orientation's bounds,
735 // re-calculate the entry bounds and restart the alpha animation.
736 final Rect destinationBounds = mPipBoundsAlgorithm.getEntryDestinationBounds();
737 enterPipWithAlphaAnimation(destinationBounds, mEnterAnimationDuration);
738 }
739 }
740
741 @VisibleForTesting
742 void enterPipWithAlphaAnimation(Rect destinationBounds, long durationMs) {
743 // If we are fading the PIP in, then we should move the pip to the final location as
744 // soon as possible, but set the alpha immediately since the transaction can take a
745 // while to process
746 final SurfaceControl.Transaction tx =
747 mSurfaceControlTransactionFactory.getTransaction();
748 tx.setAlpha(mLeash, 0f);
749 tx.apply();
750
751 // When entering PiP this transaction will be applied within WindowContainerTransaction and
752 // ensure that the PiP has rounded corners.
753 final SurfaceControl.Transaction boundsChangeTx =
754 mSurfaceControlTransactionFactory.getTransaction();
755 mSurfaceTransactionHelper
756 .crop(boundsChangeTx, mLeash, destinationBounds)
757 .round(boundsChangeTx, mLeash, true /* applyCornerRadius */);
758
759 mPipTransitionState.setTransitionState(PipTransitionState.ENTRY_SCHEDULED);
760 applyEnterPipSyncTransaction(destinationBounds, () -> {
761 mPipAnimationController
762 .getAnimator(mTaskInfo, mLeash, destinationBounds, 0f, 1f)
763 .setTransitionDirection(TRANSITION_DIRECTION_TO_PIP)
764 .setPipAnimationCallback(mPipAnimationCallback)
765 .setPipTransactionHandler(mPipTransactionHandler)
766 .setDuration(durationMs)
767 .start();
768 // mState is set right after the animation is kicked off to block any resize
769 // requests such as offsetPip that may have been called prior to the transition.
770 mPipTransitionState.setTransitionState(PipTransitionState.ENTERING_PIP);
771 }, boundsChangeTx);
772 }
773
774 private void onEndOfSwipePipToHomeTransition() {
775 if (Transitions.ENABLE_SHELL_TRANSITIONS) {
776 return;
777 }
778
779 final Rect destinationBounds = mPipBoundsState.getBounds();
780 final SurfaceControl swipeToHomeOverlay = mSwipePipToHomeOverlay;
781 final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
782 mSurfaceTransactionHelper
783 .resetScale(tx, mLeash, destinationBounds)
784 .crop(tx, mLeash, destinationBounds)
785 .round(tx, mLeash, isInPip());
786 // The animation is finished in the Launcher and here we directly apply the final touch.
787 applyEnterPipSyncTransaction(destinationBounds, () -> {
788 // Ensure menu's settled in its final bounds first.
789 finishResizeForMenu(destinationBounds);
790 sendOnPipTransitionFinished(TRANSITION_DIRECTION_TO_PIP);
791
792 // Remove the swipe to home overlay
793 if (swipeToHomeOverlay != null) {
794 fadeOutAndRemoveOverlay(swipeToHomeOverlay,
795 null /* callback */, false /* withStartDelay */);
796 }
797 }, tx);
798 mPipTransitionState.setInSwipePipToHomeTransition(false);
799 mSwipePipToHomeOverlay = null;
800 }
801
802 private void applyEnterPipSyncTransaction(Rect destinationBounds, Runnable runnable,
803 @Nullable SurfaceControl.Transaction boundsChangeTransaction) {
804 // PiP menu is attached late in the process here to avoid any artifacts on the leash
805 // caused by addShellRoot when in gesture navigation mode.
806 mPipMenuController.attach(mLeash);
807 final WindowContainerTransaction wct = new WindowContainerTransaction();
808 wct.setActivityWindowingMode(mToken, WINDOWING_MODE_UNDEFINED);
809 wct.setBounds(mToken, destinationBounds);
810 if (boundsChangeTransaction != null) {
811 wct.setBoundsChangeTransaction(mToken, boundsChangeTransaction);
812 }
813 mSyncTransactionQueue.queue(wct);
814 if (runnable != null) {
815 mSyncTransactionQueue.runInSync(t -> runnable.run());
816 }
817 }
818
819 private void sendOnPipTransitionStarted(
820 @PipAnimationController.TransitionDirection int direction) {
821 if (direction == TRANSITION_DIRECTION_TO_PIP) {
822 mPipTransitionState.setTransitionState(PipTransitionState.ENTERING_PIP);
823 }
824 mPipTransitionController.sendOnPipTransitionStarted(direction);
825 }
826
827 @VisibleForTesting
828 void sendOnPipTransitionFinished(
829 @PipAnimationController.TransitionDirection int direction) {
830 if (direction == TRANSITION_DIRECTION_TO_PIP) {
831 mPipTransitionState.setTransitionState(PipTransitionState.ENTERED_PIP);
832 }
833 mPipTransitionController.sendOnPipTransitionFinished(direction);
834 }
835
836 private void sendOnPipTransitionCancelled(
837 @PipAnimationController.TransitionDirection int direction) {
838 mPipTransitionController.sendOnPipTransitionCancelled(direction);
839 }
840
841 /**
842 * Note that dismissing PiP is now originated from SystemUI, see {@link #exitPip(int, boolean)}.
843 * Meanwhile this callback is invoked whenever the task is removed. For instance:
844 * - as a result of removeRootTasksInWindowingModes from WM
845 * - activity itself is died
846 * Nevertheless, we simply update the internal state here as all the heavy lifting should
847 * have been done in WM.
848 */
849 @Override
850 public void onTaskVanished(ActivityManager.RunningTaskInfo info) {
851 if (mPipTransitionState.getTransitionState() == PipTransitionState.UNDEFINED) {
852 return;
853 }
854 if (Transitions.ENABLE_SHELL_TRANSITIONS
855 && mPipTransitionState.getTransitionState() == PipTransitionState.EXITING_PIP) {
856 // With Shell transition, we do the cleanup in PipTransition after exiting PIP.
857 return;
858 }
859 final WindowContainerToken token = info.token;
860 Objects.requireNonNull(token, "Requires valid WindowContainerToken");
861 if (token.asBinder() != mToken.asBinder()) {
862 ProtoLog.wtf(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
863 "%s: Unrecognized token: %s", TAG, token);
864 return;
865 }
866
867 cancelCurrentAnimator();
868 onExitPipFinished(info);
869
870 if (Transitions.ENABLE_SHELL_TRANSITIONS) {
871 mPipTransitionController.forceFinishTransition();
872 }
873 }
874
875 @Override
876 public void onTaskInfoChanged(ActivityManager.RunningTaskInfo info) {
877 Objects.requireNonNull(mToken, "onTaskInfoChanged requires valid existing mToken");
878 if (mPipTransitionState.getTransitionState() != PipTransitionState.ENTERED_PIP
879 && mPipTransitionState.getTransitionState() != PipTransitionState.EXITING_PIP) {
880 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
881 "%s: Defer onTaskInfoChange in current state: %d", TAG,
882 mPipTransitionState.getTransitionState());
883 // Defer applying PiP parameters if the task is entering PiP to avoid disturbing
884 // the animation.
885 mDeferredTaskInfo = info;
886 return;
887 }
888 mPipBoundsState.setLastPipComponentName(info.topActivity);
889 mPipBoundsState.setOverrideMinSize(
890 mPipBoundsAlgorithm.getMinimalSize(info.topActivityInfo));
891 final PictureInPictureParams newParams = info.pictureInPictureParams;
892
893 // mPictureInPictureParams is only null if there is no PiP
894 if (newParams == null || mPictureInPictureParams == null) {
895 return;
896 }
897 applyNewPictureInPictureParams(newParams);
898 mPictureInPictureParams = newParams;
899 }
900
901 @Override
902 public void onFocusTaskChanged(ActivityManager.RunningTaskInfo taskInfo) {
903 mPipMenuController.onFocusTaskChanged(taskInfo);
904 }
905
906 @Override
907 public boolean supportCompatUI() {
908 // PIP doesn't support compat.
909 return false;
910 }
911
912 @Override
913 public void attachChildSurfaceToTask(int taskId, SurfaceControl.Builder b) {
914 b.setParent(findTaskSurface(taskId));
915 }
916
917 @Override
918 public void reparentChildSurfaceToTask(int taskId, SurfaceControl sc,
919 SurfaceControl.Transaction t) {
920 t.reparent(sc, findTaskSurface(taskId));
921 }
922
923 private SurfaceControl findTaskSurface(int taskId) {
924 if (mTaskInfo == null || mLeash == null || mTaskInfo.taskId != taskId) {
925 throw new IllegalArgumentException("There is no surface for taskId=" + taskId);
926 }
927 return mLeash;
928 }
929
930 @Override
931 public void onFixedRotationStarted(int displayId, int newRotation) {
932 mNextRotation = newRotation;
933 mWaitForFixedRotation = true;
934
935 if (Transitions.ENABLE_SHELL_TRANSITIONS) {
936 // The fixed rotation will also be included in the transition info. However, if it is
937 // not a PIP transition (such as open another app to different orientation),
938 // PIP transition handler may not be aware of the fixed rotation start.
939 // Notify the PIP transition handler so that it can fade out the PIP window early for
940 // fixed transition of other windows.
941 mPipTransitionController.onFixedRotationStarted();
942 return;
943 }
944
945 if (mPipTransitionState.isInPip()) {
946 // Fade out the existing PiP to avoid jump cut during seamless rotation.
947 fadeExistingPip(false /* show */);
948 }
949 }
950
951 @Override
952 public void onFixedRotationFinished(int displayId) {
953 if (!mWaitForFixedRotation) {
954 return;
955 }
956 if (Transitions.ENABLE_SHELL_TRANSITIONS) {
957 clearWaitForFixedRotation();
958 return;
959 }
960 if (mPipTransitionState.getTransitionState() == PipTransitionState.TASK_APPEARED) {
961 if (mPipTransitionState.getInSwipePipToHomeTransition()) {
962 onEndOfSwipePipToHomeTransition();
963 } else {
964 // Schedule a regular animation to ensure all the callbacks are still being sent.
965 enterPipWithAlphaAnimation(mPipBoundsAlgorithm.getEntryDestinationBounds(),
966 mEnterAnimationDuration);
967 }
968 } else if (mPipTransitionState.getTransitionState() == PipTransitionState.ENTERED_PIP
969 && mHasFadeOut) {
970 fadeExistingPip(true /* show */);
971 } else if (mPipTransitionState.getTransitionState() == PipTransitionState.ENTERING_PIP
972 && mDeferredAnimEndTransaction != null) {
973 final PipAnimationController.PipTransitionAnimator<?> animator =
974 mPipAnimationController.getCurrentAnimator();
975 final Rect destinationBounds = animator.getDestinationBounds();
976 mPipBoundsState.setBounds(destinationBounds);
977 applyEnterPipSyncTransaction(destinationBounds, () -> {
978 finishResizeForMenu(destinationBounds);
979 sendOnPipTransitionFinished(TRANSITION_DIRECTION_TO_PIP);
980 }, mDeferredAnimEndTransaction);
981 }
982 clearWaitForFixedRotation();
983 }
984
985 /** Called when exiting PIP transition is finished to do the state cleanup. */
986 void onExitPipFinished(TaskInfo info) {
987 if (mLeash == null) {
988 // TODO(239461594): Remove once the double call to onExitPipFinished() is fixed
989 Log.w(TAG, "Warning, onExitPipFinished() called multiple times in the same sessino");
990 return;
991 }
992
993 clearWaitForFixedRotation();
994 if (mSwipePipToHomeOverlay != null) {
995 removeContentOverlay(mSwipePipToHomeOverlay, null /* callback */);
996 mSwipePipToHomeOverlay = null;
997 }
998 resetShadowRadius();
999 mPipTransitionState.setInSwipePipToHomeTransition(false);
1000 mPictureInPictureParams = null;
1001 mPipTransitionState.setTransitionState(PipTransitionState.UNDEFINED);
1002 // Re-set the PIP bounds to none.
1003 mPipBoundsState.setBounds(new Rect());
1004 mPipUiEventLoggerLogger.setTaskInfo(null);
1005 mPipMenuController.detach();
1006 mLeash = null;
1007
1008 if (info.displayId != Display.DEFAULT_DISPLAY && mOnDisplayIdChangeCallback != null) {
1009 mOnDisplayIdChangeCallback.accept(Display.DEFAULT_DISPLAY);
1010 }
1011 }
1012
1013 private void fadeExistingPip(boolean show) {
1014 if (mLeash == null || !mLeash.isValid()) {
1015 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1016 "%s: Invalid leash on fadeExistingPip: %s", TAG, mLeash);
1017 return;
1018 }
1019 final float alphaStart = show ? 0 : 1;
1020 final float alphaEnd = show ? 1 : 0;
1021 mPipAnimationController
1022 .getAnimator(mTaskInfo, mLeash, mPipBoundsState.getBounds(), alphaStart, alphaEnd)
1023 .setTransitionDirection(TRANSITION_DIRECTION_SAME)
1024 .setPipTransactionHandler(mPipTransactionHandler)
1025 .setDuration(show ? mEnterAnimationDuration : mExitAnimationDuration)
1026 .start();
1027 mHasFadeOut = !show;
1028 }
1029
1030 private void clearWaitForFixedRotation() {
1031 mWaitForFixedRotation = false;
1032 mDeferredAnimEndTransaction = null;
1033 }
1034
1035 /** Explicitly set the visibility of PiP window. */
1036 public void setPipVisibility(boolean visible) {
1037 if (!isInPip()) {
1038 return;
1039 }
1040 if (mLeash == null || !mLeash.isValid()) {
1041 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1042 "%s: Invalid leash on setPipVisibility: %s", TAG, mLeash);
1043 return;
1044 }
1045 final SurfaceControl.Transaction tx =
1046 mSurfaceControlTransactionFactory.getTransaction();
1047 mSurfaceTransactionHelper.alpha(tx, mLeash, visible ? 1f : 0f);
1048 tx.apply();
1049 }
1050
1051 @Override
1052 public void onDisplayConfigurationChanged(int displayId, Configuration newConfig) {
1053 mCurrentRotation = newConfig.windowConfiguration.getRotation();
1054 }
1055
1056 /**
1057 * Called when display size or font size of settings changed
1058 */
1059 public void onDensityOrFontScaleChanged(Context context) {
1060 mSurfaceTransactionHelper.onDensityOrFontScaleChanged(context);
1061 }
1062
1063 /**
1064 * TODO(b/152809058): consolidate the display info handling logic in SysUI
1065 *
1066 * @param destinationBoundsOut the current destination bounds will be populated to this param
1067 */
1068 @SuppressWarnings("unchecked")
1069 public void onMovementBoundsChanged(Rect destinationBoundsOut, boolean fromRotation,
1070 boolean fromImeAdjustment, boolean fromShelfAdjustment,
1071 WindowContainerTransaction wct) {
1072 // note that this can be called when swipe-to-home or fixed-rotation is happening.
1073 // Skip this entirely if that's the case.
1074 final boolean waitForFixedRotationOnEnteringPip = mWaitForFixedRotation
1075 && (mPipTransitionState.getTransitionState() != PipTransitionState.ENTERED_PIP);
1076 if ((mPipTransitionState.getInSwipePipToHomeTransition()
1077 || waitForFixedRotationOnEnteringPip) && fromRotation) {
1078 if (DEBUG) {
1079 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1080 "%s: Skip onMovementBoundsChanged on rotation change"
1081 + " InSwipePipToHomeTransition=%b"
1082 + " mWaitForFixedRotation=%b"
1083 + " getTransitionState=%d", TAG,
1084 mPipTransitionState.getInSwipePipToHomeTransition(), mWaitForFixedRotation,
1085 mPipTransitionState.getTransitionState());
1086 }
1087 return;
1088 }
1089 final PipAnimationController.PipTransitionAnimator animator =
1090 mPipAnimationController.getCurrentAnimator();
1091 if (animator == null || !animator.isRunning()
1092 || animator.getTransitionDirection() != TRANSITION_DIRECTION_TO_PIP) {
1093 final boolean rotatingPip = mPipTransitionState.isInPip() && fromRotation;
1094 if (rotatingPip && Transitions.ENABLE_SHELL_TRANSITIONS) {
1095 // The animation and surface update will be handled by the shell transition handler.
1096 mPipBoundsState.setBounds(destinationBoundsOut);
1097 } else if (rotatingPip && mWaitForFixedRotation && mHasFadeOut) {
1098 // The position will be used by fade-in animation when the fixed rotation is done.
1099 mPipBoundsState.setBounds(destinationBoundsOut);
1100 } else if (rotatingPip) {
1101 // Update bounds state to final destination first. It's important to do this
1102 // before finishing & cancelling the transition animation so that the MotionHelper
1103 // bounds are synchronized to the destination bounds when the animation ends.
1104 mPipBoundsState.setBounds(destinationBoundsOut);
1105 // If we are rotating while there is a current animation, immediately cancel the
1106 // animation (remove the listeners so we don't trigger the normal finish resize
1107 // call that should only happen on the update thread)
1108 int direction = TRANSITION_DIRECTION_NONE;
1109 if (animator != null) {
1110 direction = animator.getTransitionDirection();
1111 PipAnimationController.quietCancel(animator);
1112 // Do notify the listeners that this was canceled
1113 sendOnPipTransitionCancelled(direction);
1114 sendOnPipTransitionFinished(direction);
1115 }
1116
1117 // Create a reset surface transaction for the new bounds and update the window
1118 // container transaction
1119 final SurfaceControl.Transaction tx = createFinishResizeSurfaceTransaction(
1120 destinationBoundsOut);
1121 prepareFinishResizeTransaction(destinationBoundsOut, direction, tx, wct);
1122 } else {
1123 // There could be an animation on-going. If there is one on-going, last-reported
1124 // bounds isn't yet updated. We'll use the animator's bounds instead.
1125 if (animator != null && animator.isRunning()) {
1126 if (!animator.getDestinationBounds().isEmpty()) {
1127 destinationBoundsOut.set(animator.getDestinationBounds());
1128 }
1129 } else {
1130 if (!mPipBoundsState.getBounds().isEmpty()) {
1131 destinationBoundsOut.set(mPipBoundsState.getBounds());
1132 }
1133 }
1134 }
1135 return;
1136 }
1137
1138 final Rect currentDestinationBounds = animator.getDestinationBounds();
1139 destinationBoundsOut.set(currentDestinationBounds);
1140 if (!fromImeAdjustment && !fromShelfAdjustment
1141 && mPipBoundsState.getDisplayBounds().contains(currentDestinationBounds)) {
1142 // no need to update the destination bounds, bail early
1143 return;
1144 }
1145
1146 final Rect newDestinationBounds = mPipBoundsAlgorithm.getEntryDestinationBounds();
1147 if (newDestinationBounds.equals(currentDestinationBounds)) return;
1148 if (animator.getAnimationType() == ANIM_TYPE_BOUNDS) {
1149 if (mWaitForFixedRotation) {
1150 // The new destination bounds are in next rotation (DisplayLayout has been rotated
1151 // in computeRotatedBounds). The animation runs in previous rotation so the end
1152 // bounds need to be transformed.
1153 final Rect displayBounds = mPipBoundsState.getDisplayBounds();
1154 final Rect rotatedEndBounds = new Rect(newDestinationBounds);
1155 rotateBounds(rotatedEndBounds, displayBounds, mNextRotation, mCurrentRotation);
1156 animator.updateEndValue(rotatedEndBounds);
1157 } else {
1158 animator.updateEndValue(newDestinationBounds);
1159 }
1160 }
1161 animator.setDestinationBounds(newDestinationBounds);
1162 destinationBoundsOut.set(newDestinationBounds);
1163 }
1164
1165 /**
1166 * Handles all changes to the PictureInPictureParams.
1167 */
1168 protected void applyNewPictureInPictureParams(@NonNull PictureInPictureParams params) {
1169 if (mDeferredTaskInfo != null || PipUtils.aspectRatioChanged(params.getAspectRatioFloat(),
1170 mPictureInPictureParams.getAspectRatioFloat())) {
1171 mPipParamsChangedForwarder.notifyAspectRatioChanged(params.getAspectRatioFloat());
1172 }
1173 if (mDeferredTaskInfo != null
1174 || PipUtils.remoteActionsChanged(params.getActions(),
1175 mPictureInPictureParams.getActions())
1176 || !PipUtils.remoteActionsMatch(params.getCloseAction(),
1177 mPictureInPictureParams.getCloseAction())) {
1178 mPipParamsChangedForwarder.notifyActionsChanged(params.getActions(),
1179 params.getCloseAction());
1180 }
1181 }
1182
1183 /**
1184 * Animates resizing of the pinned stack given the duration.
1185 */
1186 public void scheduleAnimateResizePip(Rect toBounds, int duration,
1187 Consumer<Rect> updateBoundsCallback) {
1188 scheduleAnimateResizePip(toBounds, duration, TRANSITION_DIRECTION_NONE,
1189 updateBoundsCallback);
1190 }
1191
1192 /**
1193 * Animates resizing of the pinned stack given the duration.
1194 */
1195 public void scheduleAnimateResizePip(Rect toBounds, int duration,
1196 @PipAnimationController.TransitionDirection int direction,
1197 Consumer<Rect> updateBoundsCallback) {
1198 if (mWaitForFixedRotation) {
1199 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1200 "%s: skip scheduleAnimateResizePip, entering pip deferred", TAG);
1201 return;
1202 }
1203 scheduleAnimateResizePip(mPipBoundsState.getBounds(), toBounds, 0 /* startingAngle */,
1204 null /* sourceHintRect */, direction, duration, updateBoundsCallback);
1205 }
1206
1207 /**
1208 * Animates resizing of the pinned stack given the duration and start bounds.
1209 * This is used when the starting bounds is not the current PiP bounds.
1210 */
1211 public void scheduleAnimateResizePip(Rect fromBounds, Rect toBounds, int duration,
1212 float startingAngle, Consumer<Rect> updateBoundsCallback) {
1213 if (mWaitForFixedRotation) {
1214 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1215 "%s: skip scheduleAnimateResizePip, entering pip deferred", TAG);
1216 return;
1217 }
1218 scheduleAnimateResizePip(fromBounds, toBounds, startingAngle, null /* sourceHintRect */,
1219 TRANSITION_DIRECTION_SNAP_AFTER_RESIZE, duration, updateBoundsCallback);
1220 }
1221
1222 /**
1223 * Animates resizing of the pinned stack given the duration and start bounds.
1224 * This always animates the angle to zero from the starting angle.
1225 */
1226 private @Nullable PipAnimationController.PipTransitionAnimator<?> scheduleAnimateResizePip(
1227 Rect currentBounds, Rect destinationBounds, float startingAngle, Rect sourceHintRect,
1228 @PipAnimationController.TransitionDirection int direction, int durationMs,
1229 Consumer<Rect> updateBoundsCallback) {
1230 if (!mPipTransitionState.isInPip()) {
1231 // TODO: tend to use shouldBlockResizeRequest here as well but need to consider
1232 // the fact that when in exitPip, scheduleAnimateResizePip is executed in the window
1233 // container transaction callback and we want to set the mState immediately.
1234 return null;
1235 }
1236
1237 final PipAnimationController.PipTransitionAnimator<?> animator = animateResizePip(
1238 currentBounds, destinationBounds, sourceHintRect, direction, durationMs,
1239 startingAngle);
1240 if (updateBoundsCallback != null) {
1241 updateBoundsCallback.accept(destinationBounds);
1242 }
1243 return animator;
1244 }
1245
1246 /**
1247 * Directly perform manipulation/resize on the leash. This will not perform any
1248 * {@link WindowContainerTransaction} until {@link #scheduleFinishResizePip} is called.
1249 */
1250 public void scheduleResizePip(Rect toBounds, Consumer<Rect> updateBoundsCallback) {
1251 // Could happen when exitPip
1252 if (mToken == null || mLeash == null) {
1253 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1254 "%s: Abort animation, invalid leash", TAG);
1255 return;
1256 }
1257 mPipBoundsState.setBounds(toBounds);
1258 final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
1259 mSurfaceTransactionHelper
1260 .crop(tx, mLeash, toBounds)
1261 .round(tx, mLeash, mPipTransitionState.isInPip());
1262 if (shouldSyncPipTransactionWithMenu()) {
1263 mPipMenuController.resizePipMenu(mLeash, tx, toBounds);
1264 } else {
1265 tx.apply();
1266 }
1267 if (updateBoundsCallback != null) {
1268 updateBoundsCallback.accept(toBounds);
1269 }
1270 }
1271
1272 /**
1273 * Directly perform manipulation/resize on the leash, along with rotation. This will not perform
1274 * any {@link WindowContainerTransaction} until {@link #scheduleFinishResizePip} is called.
1275 */
1276 public void scheduleUserResizePip(Rect startBounds, Rect toBounds,
1277 Consumer<Rect> updateBoundsCallback) {
1278 scheduleUserResizePip(startBounds, toBounds, 0 /* degrees */, updateBoundsCallback);
1279 }
1280
1281 /**
1282 * Directly perform a scaled matrix transformation on the leash. This will not perform any
1283 * {@link WindowContainerTransaction} until {@link #scheduleFinishResizePip} is called.
1284 */
1285 public void scheduleUserResizePip(Rect startBounds, Rect toBounds, float degrees,
1286 Consumer<Rect> updateBoundsCallback) {
1287 // Could happen when exitPip
1288 if (mToken == null || mLeash == null) {
1289 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1290 "%s: Abort animation, invalid leash", TAG);
1291 return;
1292 }
1293
1294 if (startBounds.isEmpty() || toBounds.isEmpty()) {
1295 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1296 "%s: Attempted to user resize PIP to or from empty bounds, aborting.", TAG);
1297 return;
1298 }
1299
1300 final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
1301 mSurfaceTransactionHelper
1302 .scale(tx, mLeash, startBounds, toBounds, degrees)
1303 .round(tx, mLeash, startBounds, toBounds);
1304 if (shouldSyncPipTransactionWithMenu()) {
1305 mPipMenuController.movePipMenu(mLeash, tx, toBounds);
1306 } else {
1307 tx.apply();
1308 }
1309 if (updateBoundsCallback != null) {
1310 updateBoundsCallback.accept(toBounds);
1311 }
1312 }
1313
1314 /**
1315 * Finish an intermediate resize operation. This is expected to be called after
1316 * {@link #scheduleResizePip}.
1317 */
1318 public void scheduleFinishResizePip(Rect destinationBounds) {
1319 scheduleFinishResizePip(destinationBounds, null /* updateBoundsCallback */);
1320 }
1321
1322 /**
1323 * Same as {@link #scheduleFinishResizePip} but with a callback.
1324 */
1325 public void scheduleFinishResizePip(Rect destinationBounds,
1326 Consumer<Rect> updateBoundsCallback) {
1327 scheduleFinishResizePip(destinationBounds, TRANSITION_DIRECTION_NONE, updateBoundsCallback);
1328 }
1329
1330 /**
1331 * Finish an intermediate resize operation. This is expected to be called after
1332 * {@link #scheduleResizePip}.
1333 *
1334 * @param destinationBounds the final bounds of the PIP after resizing
1335 * @param direction the transition direction
1336 * @param updateBoundsCallback a callback to invoke after finishing the resize
1337 */
1338 public void scheduleFinishResizePip(Rect destinationBounds,
1339 @PipAnimationController.TransitionDirection int direction,
1340 Consumer<Rect> updateBoundsCallback) {
1341 if (mPipTransitionState.shouldBlockResizeRequest()) {
1342 return;
1343 }
1344
1345 if (mLeash == null || !mLeash.isValid()) {
1346 Log.e(TAG, String.format("scheduleFinishResizePip with null leash! mState=%d",
1347 mPipTransitionState.getTransitionState()));
1348 return;
1349 }
1350
1351 finishResize(createFinishResizeSurfaceTransaction(destinationBounds), destinationBounds,
1352 direction, -1);
1353 if (updateBoundsCallback != null) {
1354 updateBoundsCallback.accept(destinationBounds);
1355 }
1356 }
1357
1358 private SurfaceControl.Transaction createFinishResizeSurfaceTransaction(
1359 Rect destinationBounds) {
1360 final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
1361 mSurfaceTransactionHelper
1362 .crop(tx, mLeash, destinationBounds)
1363 .resetScale(tx, mLeash, destinationBounds)
1364 .round(tx, mLeash, mPipTransitionState.isInPip());
1365 return tx;
1366 }
1367
1368 /**
1369 * Offset the PiP window by a given offset on Y-axis, triggered also from screen rotation.
1370 */
1371 public void scheduleOffsetPip(Rect originalBounds, int offset, int duration,
1372 Consumer<Rect> updateBoundsCallback) {
1373 if (mPipTransitionState.shouldBlockResizeRequest()
1374 || mPipTransitionState.getInSwipePipToHomeTransition()) {
1375 return;
1376 }
1377 if (mWaitForFixedRotation) {
1378 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1379 "%s: skip scheduleOffsetPip, entering pip deferred", TAG);
1380 return;
1381 }
1382 offsetPip(originalBounds, 0 /* xOffset */, offset, duration);
1383 Rect toBounds = new Rect(originalBounds);
1384 toBounds.offset(0, offset);
1385 if (updateBoundsCallback != null) {
1386 updateBoundsCallback.accept(toBounds);
1387 }
1388 }
1389
1390 private void offsetPip(Rect originalBounds, int xOffset, int yOffset, int durationMs) {
1391 if (mTaskInfo == null) {
1392 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE, "%s: mTaskInfo is not set",
1393 TAG);
1394 return;
1395 }
1396 final Rect destinationBounds = new Rect(originalBounds);
1397 destinationBounds.offset(xOffset, yOffset);
1398 animateResizePip(originalBounds, destinationBounds, null /* sourceHintRect */,
1399 TRANSITION_DIRECTION_SAME, durationMs, 0);
1400 }
1401
1402 private void finishResize(SurfaceControl.Transaction tx, Rect destinationBounds,
1403 @PipAnimationController.TransitionDirection int direction,
1404 @PipAnimationController.AnimationType int type) {
1405 final Rect preResizeBounds = new Rect(mPipBoundsState.getBounds());
1406 final boolean isPipTopLeft = isPipTopLeft();
1407 mPipBoundsState.setBounds(destinationBounds);
1408 if (direction == TRANSITION_DIRECTION_REMOVE_STACK) {
1409 removePipImmediately();
1410 return;
1411 } else if (isInPipDirection(direction) && type == ANIM_TYPE_ALPHA) {
1412 // TODO: Synchronize this correctly in #applyEnterPipSyncTransaction
1413 finishResizeForMenu(destinationBounds);
1414 return;
1415 }
1416
1417 WindowContainerTransaction wct = new WindowContainerTransaction();
1418 prepareFinishResizeTransaction(destinationBounds, direction, tx, wct);
1419
1420 // Only corner drag, pinch or expand/un-expand resizing may lead to animating the finish
1421 // resize operation.
1422 final boolean mayAnimateFinishResize = direction == TRANSITION_DIRECTION_USER_RESIZE
1423 || direction == TRANSITION_DIRECTION_SNAP_AFTER_RESIZE
1424 || direction == TRANSITION_DIRECTION_EXPAND_OR_UNEXPAND;
1425 // Animate with a cross-fade if enabled and seamless resize is disables by the app.
1426 final boolean animateCrossFadeResize = mayAnimateFinishResize
1427 && mPictureInPictureParams != null
1428 && !mPictureInPictureParams.isSeamlessResizeEnabled();
1429 if (animateCrossFadeResize) {
1430 // Take a snapshot of the PIP task and show it. We'll fade it out after the wct
1431 // transaction is applied and the activity is laid out again.
1432 preResizeBounds.offsetTo(0, 0);
1433 final Rect snapshotDest = new Rect(0, 0, destinationBounds.width(),
1434 destinationBounds.height());
1435 // Note: Put this at layer=MAX_VALUE-2 since the input consumer for PIP is placed at
1436 // MAX_VALUE-1
1437 final SurfaceControl snapshotSurface = ScreenshotUtils.takeScreenshot(
1438 mSurfaceControlTransactionFactory.getTransaction(), mLeash, preResizeBounds,
1439 Integer.MAX_VALUE - 2);
1440 if (snapshotSurface != null) {
1441 mSyncTransactionQueue.queue(wct);
1442 mSyncTransactionQueue.runInSync(t -> {
1443 // Scale the snapshot from its pre-resize bounds to the post-resize bounds.
1444 mSurfaceTransactionHelper.scale(t, snapshotSurface, preResizeBounds,
1445 snapshotDest);
1446
1447 // Start animation to fade out the snapshot.
1448 fadeOutAndRemoveOverlay(snapshotSurface,
1449 null /* callback */, false /* withStartDelay */);
1450 });
1451 } else {
1452 applyFinishBoundsResize(wct, direction, isPipTopLeft);
1453 }
1454 } else {
1455 applyFinishBoundsResize(wct, direction, isPipTopLeft);
1456 }
1457
1458 finishResizeForMenu(destinationBounds);
1459 }
1460
1461 /** Moves the PiP menu to the destination bounds. */
1462 public void finishResizeForMenu(Rect destinationBounds) {
1463 if (!isInPip()) {
1464 return;
1465 }
1466 mPipMenuController.movePipMenu(null, null, destinationBounds);
1467 mPipMenuController.updateMenuBounds(destinationBounds);
1468 }
1469
1470 private void prepareFinishResizeTransaction(Rect destinationBounds,
1471 @PipAnimationController.TransitionDirection int direction,
1472 SurfaceControl.Transaction tx,
1473 WindowContainerTransaction wct) {
1474 final Rect taskBounds;
1475 if (isInPipDirection(direction)) {
1476 // If we are animating from fullscreen using a bounds animation, then reset the
1477 // activity windowing mode set by WM, and set the task bounds to the final bounds
1478 taskBounds = destinationBounds;
1479 wct.setActivityWindowingMode(mToken, WINDOWING_MODE_UNDEFINED);
1480 } else if (isOutPipDirection(direction)) {
1481 // If we are animating to fullscreen or split screen, then we need to reset the
1482 // override bounds on the task to ensure that the task "matches" the parent's bounds.
1483 taskBounds = null;
1484 applyWindowingModeChangeOnExit(wct, direction);
1485 } else {
1486 // Just a resize in PIP
1487 taskBounds = destinationBounds;
1488 }
1489 mSurfaceTransactionHelper.round(tx, mLeash, isInPip());
1490
1491 wct.setBounds(mToken, taskBounds);
1492 wct.setBoundsChangeTransaction(mToken, tx);
1493 }
1494
1495 /**
1496 * Applies the window container transaction to finish a bounds resize.
1497 *
1498 * Called by {@link #finishResize(SurfaceControl.Transaction, Rect, int, int)}} once it has
1499 * finished preparing the transaction. It allows subclasses to modify the transaction before
1500 * applying it.
1501 */
1502 public void applyFinishBoundsResize(@NonNull WindowContainerTransaction wct,
1503 @PipAnimationController.TransitionDirection int direction, boolean wasPipTopLeft) {
1504 if (direction == TRANSITION_DIRECTION_LEAVE_PIP_TO_SPLIT_SCREEN) {
1505 mSplitScreenOptional.ifPresent(splitScreenController ->
1506 splitScreenController.enterSplitScreen(mTaskInfo.taskId, wasPipTopLeft, wct));
1507 } else {
1508 mTaskOrganizer.applyTransaction(wct);
1509 }
1510 }
1511
1512 private boolean isPipTopLeft() {
1513 if (!mSplitScreenOptional.isPresent()) {
1514 return false;
1515 }
1516 final Rect topLeft = new Rect();
1517 final Rect bottomRight = new Rect();
1518 mSplitScreenOptional.get().getStageBounds(topLeft, bottomRight);
1519
1520 return topLeft.contains(mPipBoundsState.getBounds());
1521 }
1522
1523 /**
1524 * The windowing mode to restore to when resizing out of PIP direction. Defaults to undefined
1525 * and can be overridden to restore to an alternate windowing mode.
1526 */
1527 public int getOutPipWindowingMode() {
1528 // By default, simply reset the windowing mode to undefined.
1529 return WINDOWING_MODE_UNDEFINED;
1530 }
1531
1532 private @Nullable PipAnimationController.PipTransitionAnimator<?> animateResizePip(
1533 Rect currentBounds, Rect destinationBounds, Rect sourceHintRect,
1534 @PipAnimationController.TransitionDirection int direction, int durationMs,
1535 float startingAngle) {
1536 // Could happen when exitPip
1537 if (mToken == null || mLeash == null) {
1538 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1539 "%s: Abort animation, invalid leash", TAG);
1540 return null;
1541 }
1542 if (isInPipDirection(direction)
1543 && !isSourceRectHintValidForEnterPip(sourceHintRect, destinationBounds)) {
1544 // The given source rect hint is too small for enter PiP animation, reset it to null.
1545 sourceHintRect = null;
1546 }
1547 final int rotationDelta = mWaitForFixedRotation
1548 ? deltaRotation(mCurrentRotation, mNextRotation)
1549 : Surface.ROTATION_0;
1550 if (rotationDelta != Surface.ROTATION_0) {
1551 sourceHintRect = computeRotatedBounds(rotationDelta, direction, destinationBounds,
1552 sourceHintRect);
1553 }
1554 Rect baseBounds = direction == TRANSITION_DIRECTION_SNAP_AFTER_RESIZE
1555 ? mPipBoundsState.getBounds() : currentBounds;
1556 final boolean existingAnimatorRunning = mPipAnimationController.getCurrentAnimator() != null
1557 && mPipAnimationController.getCurrentAnimator().isRunning();
1558 final PipAnimationController.PipTransitionAnimator<?> animator = mPipAnimationController
1559 .getAnimator(mTaskInfo, mLeash, baseBounds, currentBounds, destinationBounds,
1560 sourceHintRect, direction, startingAngle, rotationDelta);
1561 animator.setTransitionDirection(direction)
1562 .setPipTransactionHandler(mPipTransactionHandler)
1563 .setDuration(durationMs);
1564 if (!existingAnimatorRunning) {
1565 animator.setPipAnimationCallback(mPipAnimationCallback);
1566 }
1567 if (isInPipDirection(direction)) {
1568 // Similar to auto-enter-pip transition, we use content overlay when there is no
1569 // source rect hint to enter PiP use bounds animation.
1570 if (sourceHintRect == null) {
1571 animator.setColorContentOverlay(mContext);
1572 } else {
1573 final TaskSnapshot snapshot = PipUtils.getTaskSnapshot(
1574 mTaskInfo.launchIntoPipHostTaskId, false /* isLowResolution */);
1575 if (snapshot != null) {
1576 // use the task snapshot during the animation, this is for
1577 // launch-into-pip aka. content-pip use case.
1578 animator.setSnapshotContentOverlay(snapshot, sourceHintRect);
1579 }
1580 }
1581 // The destination bounds are used for the end rect of animation and the final bounds
1582 // after animation finishes. So after the animation is started, the destination bounds
1583 // can be updated to new rotation (computeRotatedBounds has changed the DisplayLayout
1584 // without affecting the animation.
1585 if (rotationDelta != Surface.ROTATION_0) {
1586 animator.setDestinationBounds(mPipBoundsAlgorithm.getEntryDestinationBounds());
1587 }
1588 }
1589 animator.start();
1590 return animator;
1591 }
1592
1593 /** Computes destination bounds in old rotation and returns source hint rect if available. */
1594 private @Nullable Rect computeRotatedBounds(int rotationDelta, int direction,
1595 Rect outDestinationBounds, Rect sourceHintRect) {
1596 if (direction == TRANSITION_DIRECTION_TO_PIP) {
1597 mPipBoundsState.getDisplayLayout().rotateTo(mContext.getResources(), mNextRotation);
1598 final Rect displayBounds = mPipBoundsState.getDisplayBounds();
1599 outDestinationBounds.set(mPipBoundsAlgorithm.getEntryDestinationBounds());
1600 // Transform the destination bounds to current display coordinates.
1601 rotateBounds(outDestinationBounds, displayBounds, mNextRotation, mCurrentRotation);
1602 // When entering PiP (from button navigation mode), adjust the source rect hint by
1603 // display cutout if applicable.
1604 if (sourceHintRect != null && mTaskInfo.displayCutoutInsets != null) {
1605 if (rotationDelta == Surface.ROTATION_270) {
1606 sourceHintRect.offset(mTaskInfo.displayCutoutInsets.left,
1607 mTaskInfo.displayCutoutInsets.top);
1608 }
1609 }
1610 } else if (direction == TRANSITION_DIRECTION_LEAVE_PIP) {
1611 final Rect rotatedDestinationBounds = new Rect(outDestinationBounds);
1612 rotateBounds(rotatedDestinationBounds, mPipBoundsState.getDisplayBounds(),
1613 rotationDelta);
1614 return PipBoundsAlgorithm.getValidSourceHintRect(mPictureInPictureParams,
1615 rotatedDestinationBounds);
1616 }
1617 return sourceHintRect;
1618 }
1619
1620 /**
1621 * This is a situation in which the source rect hint on at least one axis is smaller
1622 * than the destination bounds, which represents a problem because we would have to scale
1623 * up that axis to fit the bounds. So instead, just fallback to the non-source hint
1624 * animation in this case.
1625 *
1626 * @return {@code false} if the given source is too small to use for the entering animation.
1627 */
1628 private boolean isSourceRectHintValidForEnterPip(Rect sourceRectHint, Rect destinationBounds) {
1629 return sourceRectHint != null
1630 && sourceRectHint.width() > destinationBounds.width()
1631 && sourceRectHint.height() > destinationBounds.height();
1632 }
1633
1634 /**
1635 * Sync with {@link SplitScreenController} on destination bounds if PiP is going to
1636 * split screen.
1637 *
1638 * @param destinationBoundsOut contain the updated destination bounds if applicable
1639 * @return {@code true} if destinationBounds is altered for split screen
1640 */
1641 private boolean syncWithSplitScreenBounds(Rect destinationBoundsOut, boolean enterSplit) {
1642 if (!enterSplit || !mSplitScreenOptional.isPresent()) {
1643 return false;
1644 }
1645 final Rect topLeft = new Rect();
1646 final Rect bottomRight = new Rect();
1647 mSplitScreenOptional.get().getStageBounds(topLeft, bottomRight);
1648 final boolean isPipTopLeft = isPipTopLeft();
1649 destinationBoundsOut.set(isPipTopLeft ? topLeft : bottomRight);
1650 return true;
1651 }
1652
1653 /**
1654 * Fades out and removes an overlay surface.
1655 */
1656 void fadeOutAndRemoveOverlay(SurfaceControl surface, Runnable callback,
1657 boolean withStartDelay) {
1658 if (surface == null || !surface.isValid()) {
1659 return;
1660 }
1661
1662 final ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f);
1663 animator.setDuration(mCrossFadeAnimationDuration);
1664 animator.addUpdateListener(animation -> {
1665 if (mPipTransitionState.getTransitionState() == PipTransitionState.UNDEFINED) {
1666 // Could happen if onTaskVanished happens during the animation since we may have
1667 // set a start delay on this animation.
1668 ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1669 "%s: Task vanished, skip fadeOutAndRemoveOverlay", TAG);
1670 PipAnimationController.quietCancel(animation);
1671 } else if (surface.isValid()) {
1672 final float alpha = (float) animation.getAnimatedValue();
1673 final SurfaceControl.Transaction transaction =
1674 mSurfaceControlTransactionFactory.getTransaction();
1675 transaction.setAlpha(surface, alpha);
1676 transaction.apply();
1677 }
1678 });
1679 animator.addListener(new AnimatorListenerAdapter() {
1680 @Override
1681 public void onAnimationEnd(Animator animation) {
1682 removeContentOverlay(surface, callback);
1683 }
1684 });
1685 animator.setStartDelay(withStartDelay ? CONTENT_OVERLAY_FADE_OUT_DELAY_MS : 0);
1686 animator.start();
1687 }
1688
1689 private void removeContentOverlay(SurfaceControl surface, Runnable callback) {
1690 if (mPipTransitionState.getTransitionState() == PipTransitionState.UNDEFINED) {
1691 // Avoid double removal, which is fatal.
1692 return;
1693 }
1694 if (surface == null || !surface.isValid()) {
1695 ProtoLog.w(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
1696 "%s: trying to remove invalid content overlay (%s)", TAG, surface);
1697 return;
1698 }
1699 final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
1700 tx.remove(surface);
1701 tx.apply();
1702 if (callback != null) callback.run();
1703 }
1704
1705 private void resetShadowRadius() {
1706 if (mPipTransitionState.getTransitionState() == PipTransitionState.UNDEFINED) {
1707 // mLeash is undefined when in PipTransitionState.UNDEFINED
1708 return;
1709 }
1710 final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
1711 tx.setShadowRadius(mLeash, 0f);
1712 tx.apply();
1713 }
1714
1715 private void cancelCurrentAnimator() {
1716 final PipAnimationController.PipTransitionAnimator<?> animator =
1717 mPipAnimationController.getCurrentAnimator();
1718 if (animator != null) {
1719 if (animator.getContentOverlayLeash() != null) {
1720 removeContentOverlay(animator.getContentOverlayLeash(),
1721 animator::clearContentOverlay);
1722 }
1723 PipAnimationController.quietCancel(animator);
1724 }
1725 }
1726
1727 @VisibleForTesting
1728 public void setSurfaceControlTransactionFactory(
1729 PipSurfaceTransactionHelper.SurfaceControlTransactionFactory factory) {
1730 mSurfaceControlTransactionFactory = factory;
1731 }
1732
1733 /**
1734 * Dumps internal states.
1735 */
1736 @Override
1737 public void dump(PrintWriter pw, String prefix) {
1738 final String innerPrefix = prefix + " ";
1739 pw.println(prefix + TAG);
1740 pw.println(innerPrefix + "mTaskInfo=" + mTaskInfo);
1741 pw.println(innerPrefix + "mToken=" + mToken
1742 + " binder=" + (mToken != null ? mToken.asBinder() : null));
1743 pw.println(innerPrefix + "mLeash=" + mLeash);
1744 pw.println(innerPrefix + "mState=" + mPipTransitionState.getTransitionState());
1745 pw.println(innerPrefix + "mOneShotAnimationType=" + mOneShotAnimationType);
1746 pw.println(innerPrefix + "mPictureInPictureParams=" + mPictureInPictureParams);
1747 }
1748
1749 @Override
1750 public String toString() {
1751 return TAG + ":" + taskListenerTypeToString(TASK_LISTENER_TYPE_PIP);
1752 }
1753 }