Debian Codegraph @

libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.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.bubbles;
18
19 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
20 import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
21
22 import static com.android.wm.shell.animation.Interpolators.ALPHA_IN;
23 import static com.android.wm.shell.animation.Interpolators.ALPHA_OUT;
24 import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_GESTURE;
25 import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_STACK_VIEW;
26 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
27 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
28 import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING;
29
30 import android.animation.Animator;
31 import android.animation.AnimatorListenerAdapter;
32 import android.animation.AnimatorSet;
33 import android.animation.ObjectAnimator;
34 import android.animation.ValueAnimator;
35 import android.annotation.SuppressLint;
36 import android.app.ActivityManager;
37 import android.content.ContentResolver;
38 import android.content.Context;
39 import android.content.Intent;
40 import android.content.res.Resources;
41 import android.content.res.TypedArray;
42 import android.graphics.Outline;
43 import android.graphics.PointF;
44 import android.graphics.Rect;
45 import android.graphics.RectF;
46 import android.graphics.drawable.ColorDrawable;
47 import android.os.Bundle;
48 import android.os.SystemProperties;
49 import android.provider.Settings;
50 import android.util.Log;
51 import android.view.Choreographer;
52 import android.view.LayoutInflater;
53 import android.view.MotionEvent;
54 import android.view.SurfaceControl;
55 import android.view.SurfaceHolder;
56 import android.view.SurfaceView;
57 import android.view.View;
58 import android.view.ViewGroup;
59 import android.view.ViewOutlineProvider;
60 import android.view.ViewTreeObserver;
61 import android.view.WindowManagerPolicyConstants;
62 import android.view.accessibility.AccessibilityNodeInfo;
63 import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
64 import android.widget.FrameLayout;
65 import android.widget.ImageView;
66 import android.widget.TextView;
67
68 import androidx.annotation.NonNull;
69 import androidx.annotation.Nullable;
70 import androidx.dynamicanimation.animation.DynamicAnimation;
71 import androidx.dynamicanimation.animation.FloatPropertyCompat;
72 import androidx.dynamicanimation.animation.SpringAnimation;
73 import androidx.dynamicanimation.animation.SpringForce;
74
75 import com.android.internal.annotations.VisibleForTesting;
76 import com.android.internal.policy.ScreenDecorationsUtils;
77 import com.android.internal.util.FrameworkStatsLog;
78 import com.android.wm.shell.R;
79 import com.android.wm.shell.animation.Interpolators;
80 import com.android.wm.shell.animation.PhysicsAnimator;
81 import com.android.wm.shell.bubbles.BubblesNavBarMotionEventHandler.MotionEventListener;
82 import com.android.wm.shell.bubbles.animation.AnimatableScaleMatrix;
83 import com.android.wm.shell.bubbles.animation.ExpandedAnimationController;
84 import com.android.wm.shell.bubbles.animation.ExpandedViewAnimationController;
85 import com.android.wm.shell.bubbles.animation.ExpandedViewAnimationControllerImpl;
86 import com.android.wm.shell.bubbles.animation.PhysicsAnimationLayout;
87 import com.android.wm.shell.bubbles.animation.StackAnimationController;
88 import com.android.wm.shell.common.FloatingContentCoordinator;
89 import com.android.wm.shell.common.ShellExecutor;
90 import com.android.wm.shell.common.magnetictarget.MagnetizedObject;
91
92 import java.io.PrintWriter;
93 import java.math.BigDecimal;
94 import java.math.RoundingMode;
95 import java.util.ArrayList;
96 import java.util.Collections;
97 import java.util.List;
98 import java.util.Objects;
99 import java.util.function.Consumer;
100 import java.util.stream.Collectors;
101
102 /**
103 * Renders bubbles in a stack and handles animating expanded and collapsed states.
104 */
105 public class BubbleStackView extends FrameLayout
106 implements ViewTreeObserver.OnComputeInternalInsetsListener {
107
108 public static final boolean ENABLE_FLING_TO_DISMISS_BUBBLE =
109 SystemProperties.getBoolean("persist.wm.debug.fling_to_dismiss_bubble", true);
110
111 private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleStackView" : TAG_BUBBLES;
112
113 /** How far the flyout needs to be dragged before it's dismissed regardless of velocity. */
114 static final float FLYOUT_DRAG_PERCENT_DISMISS = 0.25f;
115
116 /** Velocity required to dismiss the flyout via drag. */
117 private static final float FLYOUT_DISMISS_VELOCITY = 2000f;
118
119 /**
120 * Factor for attenuating translation when the flyout is overscrolled (8f = flyout moves 1 pixel
121 * for every 8 pixels overscrolled).
122 */
123 private static final float FLYOUT_OVERSCROLL_ATTENUATION_FACTOR = 8f;
124
125 private static final int FADE_IN_DURATION = 320;
126
127 /** How long to wait, in milliseconds, before hiding the flyout. */
128 @VisibleForTesting
129 static final int FLYOUT_HIDE_AFTER = 5000;
130
131 private static final float EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT = 0.1f;
132
133 private static final int EXPANDED_VIEW_ALPHA_ANIMATION_DURATION = 150;
134
135 private static final float SCRIM_ALPHA = 0.6f;
136
137 /** Minimum alpha value for scrim when alpha is being changed via drag */
138 private static final float MIN_SCRIM_ALPHA_FOR_DRAG = 0.2f;
139
140 /**
141 * How long to wait to animate the stack temporarily invisible after a drag/flyout hide
142 * animation ends, if we are in fact temporarily invisible.
143 */
144 private static final int ANIMATE_TEMPORARILY_INVISIBLE_DELAY = 1000;
145
146 private static final PhysicsAnimator.SpringConfig FLYOUT_IME_ANIMATION_SPRING_CONFIG =
147 new PhysicsAnimator.SpringConfig(
148 StackAnimationController.IME_ANIMATION_STIFFNESS,
149 StackAnimationController.DEFAULT_BOUNCINESS);
150
151 private final PhysicsAnimator.SpringConfig mScaleInSpringConfig =
152 new PhysicsAnimator.SpringConfig(300f, 0.9f);
153
154 private final PhysicsAnimator.SpringConfig mScaleOutSpringConfig =
155 new PhysicsAnimator.SpringConfig(900f, 1f);
156
157 private final PhysicsAnimator.SpringConfig mTranslateSpringConfig =
158 new PhysicsAnimator.SpringConfig(
159 SpringForce.STIFFNESS_VERY_LOW, SpringForce.DAMPING_RATIO_NO_BOUNCY);
160
161 /**
162 * Handler to use for all delayed animations - this way, we can easily cancel them before
163 * starting a new animation.
164 */
165 private final ShellExecutor mMainExecutor;
166 private Runnable mDelayedAnimation;
167
168 /**
169 * Interface to synchronize {@link View} state and the screen.
170 *
171 * {@hide}
172 */
173 public interface SurfaceSynchronizer {
174 /**
175 * Wait until requested change on a {@link View} is reflected on the screen.
176 *
177 * @param callback callback to run after the change is reflected on the screen.
178 */
179 void syncSurfaceAndRun(Runnable callback);
180 }
181
182 private static final SurfaceSynchronizer DEFAULT_SURFACE_SYNCHRONIZER =
183 new SurfaceSynchronizer() {
184 @Override
185 public void syncSurfaceAndRun(Runnable callback) {
186 Choreographer.FrameCallback frameCallback = new Choreographer.FrameCallback() {
187 // Just wait 2 frames. There is no guarantee, but this is usually enough
188 // time that the requested change is reflected on the screen.
189 // TODO: Once SurfaceFlinger provide APIs to sync the state of
190 // {@code View} and surfaces, rewrite this logic with them.
191 private int mFrameWait = 2;
192
193 @Override
194 public void doFrame(long frameTimeNanos) {
195 if (--mFrameWait > 0) {
196 Choreographer.getInstance().postFrameCallback(this);
197 } else {
198 callback.run();
199 }
200 }
201 };
202 Choreographer.getInstance().postFrameCallback(frameCallback);
203 }
204 };
205 private final BubbleController mBubbleController;
206 private final BubbleData mBubbleData;
207 private StackViewState mStackViewState = new StackViewState();
208
209 private final ValueAnimator mDismissBubbleAnimator;
210
211 private PhysicsAnimationLayout mBubbleContainer;
212 private StackAnimationController mStackAnimationController;
213 private ExpandedAnimationController mExpandedAnimationController;
214 private ExpandedViewAnimationController mExpandedViewAnimationController;
215
216 private View mScrim;
217 private boolean mScrimAnimating;
218 private View mManageMenuScrim;
219 private FrameLayout mExpandedViewContainer;
220
221 /** Matrix used to scale the expanded view container with a given pivot point. */
222 private final AnimatableScaleMatrix mExpandedViewContainerMatrix = new AnimatableScaleMatrix();
223
224 /**
225 * SurfaceView that we draw screenshots of animating-out bubbles into. This allows us to animate
226 * between bubble activities without needing both to be alive at the same time.
227 */
228 private SurfaceView mAnimatingOutSurfaceView;
229 private boolean mAnimatingOutSurfaceReady;
230
231 /** Container for the animating-out SurfaceView. */
232 private FrameLayout mAnimatingOutSurfaceContainer;
233
234 /** Animator for animating the alpha value of the animating out SurfaceView. */
235 private final ValueAnimator mAnimatingOutSurfaceAlphaAnimator = ValueAnimator.ofFloat(0f, 1f);
236
237 /**
238 * Buffer containing a screenshot of the animating-out bubble. This is drawn into the
239 * SurfaceView during animations.
240 */
241 private SurfaceControl.ScreenshotHardwareBuffer mAnimatingOutBubbleBuffer;
242
243 private BubbleFlyoutView mFlyout;
244 /** Runnable that fades out the flyout and then sets it to GONE. */
245 private Runnable mHideFlyout = () -> animateFlyoutCollapsed(true, 0 /* velX */);
246 /**
247 * Callback to run after the flyout hides. Also called if a new flyout is shown before the
248 * previous one animates out.
249 */
250 private Runnable mAfterFlyoutHidden;
251 /**
252 * Set when the flyout is tapped, so that we can expand the bubble associated with the flyout
253 * once it collapses.
254 */
255 @Nullable
256 private BubbleViewProvider mBubbleToExpandAfterFlyoutCollapse = null;
257
258 /** Layout change listener that moves the stack to the nearest valid position on rotation. */
259 private OnLayoutChangeListener mOrientationChangedListener;
260
261 @Nullable private RelativeStackPosition mRelativeStackPositionBeforeRotation;
262
263 private int mBubbleSize;
264 private int mBubbleElevation;
265 private int mBubbleTouchPadding;
266 private int mExpandedViewPadding;
267 private int mCornerRadius;
268 @Nullable private BubbleViewProvider mExpandedBubble;
269 private boolean mIsExpanded;
270
271 /** Whether the stack is currently on the left side of the screen, or animating there. */
272 private boolean mStackOnLeftOrWillBe = true;
273
274 /** Whether a touch gesture, such as a stack/bubble drag or flyout drag, is in progress. */
275 private boolean mIsGestureInProgress = false;
276
277 /** Whether or not the stack is temporarily invisible off the side of the screen. */
278 private boolean mTemporarilyInvisible = false;
279
280 /** Whether we're in the middle of dragging the stack around by touch. */
281 private boolean mIsDraggingStack = false;
282
283 /** Whether the expanded view has been hidden, because we are dragging out a bubble. */
284 private boolean mExpandedViewTemporarilyHidden = false;
285
286 /** Animator for animating the expanded view's alpha (including the TaskView inside it). */
287 private final ValueAnimator mExpandedViewAlphaAnimator = ValueAnimator.ofFloat(0f, 1f);
288
289 /**
290 * The pointer index of the ACTION_DOWN event we received prior to an ACTION_UP. We'll ignore
291 * touches from other pointer indices.
292 */
293 private int mPointerIndexDown = -1;
294
295 @Nullable
296 private BubblesNavBarGestureTracker mBubblesNavBarGestureTracker;
297
298 /** Description of current animation controller state. */
299 public void dump(PrintWriter pw) {
300 pw.println("Stack view state:");
301
302 String bubblesOnScreen = BubbleDebugConfig.formatBubblesString(
303 getBubblesOnScreen(), getExpandedBubble());
304 pw.print(" bubbles on screen: "); pw.println(bubblesOnScreen);
305 pw.print(" gestureInProgress: "); pw.println(mIsGestureInProgress);
306 pw.print(" showingDismiss: "); pw.println(mDismissView.isShowing());
307 pw.print(" isExpansionAnimating: "); pw.println(mIsExpansionAnimating);
308 pw.print(" expandedContainerVis: "); pw.println(mExpandedViewContainer.getVisibility());
309 pw.print(" expandedContainerAlpha: "); pw.println(mExpandedViewContainer.getAlpha());
310 pw.print(" expandedContainerMatrix: ");
311 pw.println(mExpandedViewContainer.getAnimationMatrix());
312
313 mStackAnimationController.dump(pw);
314 mExpandedAnimationController.dump(pw);
315
316 if (mExpandedBubble != null) {
317 pw.println("Expanded bubble state:");
318 pw.println(" expandedBubbleKey: " + mExpandedBubble.getKey());
319
320 final BubbleExpandedView expandedView = mExpandedBubble.getExpandedView();
321
322 if (expandedView != null) {
323 pw.println(" expandedViewVis: " + expandedView.getVisibility());
324 pw.println(" expandedViewAlpha: " + expandedView.getAlpha());
325 pw.println(" expandedViewTaskId: " + expandedView.getTaskId());
326
327 final View av = expandedView.getTaskView();
328
329 if (av != null) {
330 pw.println(" activityViewVis: " + av.getVisibility());
331 pw.println(" activityViewAlpha: " + av.getAlpha());
332 } else {
333 pw.println(" activityView is null");
334 }
335 } else {
336 pw.println("Expanded bubble view state: expanded bubble view is null");
337 }
338 } else {
339 pw.println("Expanded bubble state: expanded bubble is null");
340 }
341 }
342
343 private Bubbles.BubbleExpandListener mExpandListener;
344
345 /** Callback to run when we want to unbubble the given notification's conversation. */
346 private Consumer<String> mUnbubbleConversationCallback;
347
348 private boolean mViewUpdatedRequested = false;
349 private boolean mIsExpansionAnimating = false;
350 private boolean mIsBubbleSwitchAnimating = false;
351
352 /** The view to shrink and apply alpha to when magneted to the dismiss target. */
353 @Nullable private View mViewBeingDismissed;
354
355 private Rect mTempRect = new Rect();
356
357 private final List<Rect> mSystemGestureExclusionRects = Collections.singletonList(new Rect());
358
359 private ViewTreeObserver.OnPreDrawListener mViewUpdater =
360 new ViewTreeObserver.OnPreDrawListener() {
361 @Override
362 public boolean onPreDraw() {
363 getViewTreeObserver().removeOnPreDrawListener(mViewUpdater);
364 updateExpandedView();
365 mViewUpdatedRequested = false;
366 return true;
367 }
368 };
369
370 private ViewTreeObserver.OnDrawListener mSystemGestureExcludeUpdater =
371 this::updateSystemGestureExcludeRects;
372
373 /** Float property that 'drags' the flyout. */
374 private final FloatPropertyCompat mFlyoutCollapseProperty =
375 new FloatPropertyCompat("FlyoutCollapseSpring") {
376 @Override
377 public float getValue(Object o) {
378 return mFlyoutDragDeltaX;
379 }
380
381 @Override
382 public void setValue(Object o, float v) {
383 setFlyoutStateForDragLength(v);
384 }
385 };
386
387 /** SpringAnimation that springs the flyout collapsed via onFlyoutDragged. */
388 private final SpringAnimation mFlyoutTransitionSpring =
389 new SpringAnimation(this, mFlyoutCollapseProperty);
390
391 /** Distance the flyout has been dragged in the X axis. */
392 private float mFlyoutDragDeltaX = 0f;
393
394 /**
395 * Runnable that animates in the flyout. This reference is needed to cancel delayed postings.
396 */
397 private Runnable mAnimateInFlyout;
398
399 /**
400 * End listener for the flyout spring that either posts a runnable to hide the flyout, or hides
401 * it immediately.
402 */
403 private final DynamicAnimation.OnAnimationEndListener mAfterFlyoutTransitionSpring =
404 (dynamicAnimation, b, v, v1) -> {
405 if (mFlyoutDragDeltaX == 0) {
406 mFlyout.postDelayed(mHideFlyout, FLYOUT_HIDE_AFTER);
407 } else {
408 mFlyout.hideFlyout();
409 }
410 };
411
412 @NonNull
413 private final SurfaceSynchronizer mSurfaceSynchronizer;
414
415 /**
416 * The currently magnetized object, which is being dragged and will be attracted to the magnetic
417 * dismiss target.
418 *
419 * This is either the stack itself, or an individual bubble.
420 */
421 private MagnetizedObject<?> mMagnetizedObject;
422
423 /**
424 * The MagneticTarget instance for our circular dismiss view. This is added to the
425 * MagnetizedObject instances for the stack and any dragged-out bubbles.
426 */
427 private MagnetizedObject.MagneticTarget mMagneticTarget;
428
429 /** Magnet listener that handles animating and dismissing individual dragged-out bubbles. */
430 private final MagnetizedObject.MagnetListener mIndividualBubbleMagnetListener =
431 new MagnetizedObject.MagnetListener() {
432 @Override
433 public void onStuckToTarget(@NonNull MagnetizedObject.MagneticTarget target) {
434 if (mExpandedAnimationController.getDraggedOutBubble() == null) {
435 return;
436 }
437 animateDismissBubble(
438 mExpandedAnimationController.getDraggedOutBubble(), true);
439 }
440
441 @Override
442 public void onUnstuckFromTarget(@NonNull MagnetizedObject.MagneticTarget target,
443 float velX, float velY, boolean wasFlungOut) {
444 if (mExpandedAnimationController.getDraggedOutBubble() == null) {
445 return;
446 }
447 animateDismissBubble(
448 mExpandedAnimationController.getDraggedOutBubble(), false);
449
450 if (wasFlungOut) {
451 mExpandedAnimationController.snapBubbleBack(
452 mExpandedAnimationController.getDraggedOutBubble(), velX, velY);
453 mDismissView.hide();
454 } else {
455 mExpandedAnimationController.onUnstuckFromTarget();
456 }
457 }
458
459 @Override
460 public void onReleasedInTarget(@NonNull MagnetizedObject.MagneticTarget target) {
461 if (mExpandedAnimationController.getDraggedOutBubble() == null) {
462 return;
463 }
464
465 mExpandedAnimationController.dismissDraggedOutBubble(
466 mExpandedAnimationController.getDraggedOutBubble() /* bubble */,
467 mDismissView.getHeight() /* translationYBy */,
468 BubbleStackView.this::dismissMagnetizedObject /* after */);
469 mDismissView.hide();
470 }
471 };
472
473 /** Magnet listener that handles animating and dismissing the entire stack. */
474 private final MagnetizedObject.MagnetListener mStackMagnetListener =
475 new MagnetizedObject.MagnetListener() {
476 @Override
477 public void onStuckToTarget(
478 @NonNull MagnetizedObject.MagneticTarget target) {
479 animateDismissBubble(mBubbleContainer, true);
480 }
481
482 @Override
483 public void onUnstuckFromTarget(@NonNull MagnetizedObject.MagneticTarget target,
484 float velX, float velY, boolean wasFlungOut) {
485 animateDismissBubble(mBubbleContainer, false);
486 if (wasFlungOut) {
487 mStackAnimationController.flingStackThenSpringToEdge(
488 mStackAnimationController.getStackPosition().x, velX, velY);
489 mDismissView.hide();
490 } else {
491 mStackAnimationController.onUnstuckFromTarget();
492 }
493 }
494
495 @Override
496 public void onReleasedInTarget(@NonNull MagnetizedObject.MagneticTarget target) {
497 mStackAnimationController.animateStackDismissal(
498 mDismissView.getHeight() /* translationYBy */,
499 () -> {
500 resetDismissAnimator();
501 dismissMagnetizedObject();
502 }
503 );
504 mDismissView.hide();
505 }
506 };
507
508 /**
509 * Click listener set on each bubble view. When collapsed, clicking a bubble expands the stack.
510 * When expanded, clicking a bubble either expands that bubble, or collapses the stack.
511 */
512 private OnClickListener mBubbleClickListener = new OnClickListener() {
513 @Override
514 public void onClick(View view) {
515 mIsDraggingStack = false; // If the touch ended in a click, we're no longer dragging.
516
517 // Bubble clicks either trigger expansion/collapse or a bubble switch, both of which we
518 // shouldn't interrupt. These are quick transitions, so it's not worth trying to adjust
519 // the animations inflight.
520 if (mIsExpansionAnimating || mIsBubbleSwitchAnimating) {
521 return;
522 }
523
524 final Bubble clickedBubble = mBubbleData.getBubbleWithView(view);
525
526 // If the bubble has since left us, ignore the click.
527 if (clickedBubble == null) {
528 return;
529 }
530
531 final boolean clickedBubbleIsCurrentlyExpandedBubble =
532 clickedBubble.getKey().equals(mExpandedBubble.getKey());
533
534 if (isExpanded()) {
535 mExpandedAnimationController.onGestureFinished();
536 }
537
538 if (isExpanded() && !clickedBubbleIsCurrentlyExpandedBubble) {
539 if (clickedBubble != mBubbleData.getSelectedBubble()) {
540 // Select the clicked bubble.
541 mBubbleData.setSelectedBubble(clickedBubble);
542 } else {
543 // If the clicked bubble is the selected bubble (but not the expanded bubble),
544 // that means overflow was previously expanded. Set the selected bubble
545 // internally without going through BubbleData (which would ignore it since it's
546 // already selected).
547 setSelectedBubble(clickedBubble);
548 }
549 } else {
550 // Otherwise, we either tapped the stack (which means we're collapsed
551 // and should expand) or the currently selected bubble (we're expanded
552 // and should collapse).
553 if (!maybeShowStackEdu() && !mShowedUserEducationInTouchListenerActive) {
554 mBubbleData.setExpanded(!mBubbleData.isExpanded());
555 }
556 mShowedUserEducationInTouchListenerActive = false;
557 }
558 }
559 };
560
561 /**
562 * Touch listener set on each bubble view. This enables dragging and dismissing the stack (when
563 * collapsed), or individual bubbles (when expanded).
564 */
565 private RelativeTouchListener mBubbleTouchListener = new RelativeTouchListener() {
566
567 @Override
568 public boolean onDown(@NonNull View v, @NonNull MotionEvent ev) {
569 // If we're expanding or collapsing, consume but ignore all touch events.
570 if (mIsExpansionAnimating) {
571 return true;
572 }
573
574 mShowedUserEducationInTouchListenerActive = false;
575 if (maybeShowStackEdu()) {
576 mShowedUserEducationInTouchListenerActive = true;
577 return true;
578 } else if (isStackEduShowing()) {
579 mStackEduView.hide(false /* fromExpansion */);
580 }
581
582 // If the manage menu is visible, just hide it.
583 if (mShowingManage) {
584 showManageMenu(false /* show */);
585 }
586
587 if (mBubbleData.isExpanded()) {
588 if (mManageEduView != null) {
589 mManageEduView.hide();
590 }
591
592 // If we're expanded, tell the animation controller to prepare to drag this bubble,
593 // dispatching to the individual bubble magnet listener.
594 mExpandedAnimationController.prepareForBubbleDrag(
595 v /* bubble */,
596 mMagneticTarget,
597 mIndividualBubbleMagnetListener);
598
599 hideCurrentInputMethod();
600
601 // Save the magnetized individual bubble so we can dispatch touch events to it.
602 mMagnetizedObject = mExpandedAnimationController.getMagnetizedBubbleDraggingOut();
603 } else {
604 // If we're collapsed, prepare to drag the stack. Cancel active animations, set the
605 // animation controller, and hide the flyout.
606 mStackAnimationController.cancelStackPositionAnimations();
607 mBubbleContainer.setActiveController(mStackAnimationController);
608 hideFlyoutImmediate();
609
610 // Save the magnetized stack so we can dispatch touch events to it.
611 mMagnetizedObject = mStackAnimationController.getMagnetizedStack();
612 mMagnetizedObject.clearAllTargets();
613 mMagnetizedObject.addTarget(mMagneticTarget);
614 mMagnetizedObject.setMagnetListener(mStackMagnetListener);
615
616 mIsDraggingStack = true;
617
618 // Cancel animations to make the stack temporarily invisible, since we're now
619 // dragging it.
620 updateTemporarilyInvisibleAnimation(false /* hideImmediately */);
621 }
622
623 passEventToMagnetizedObject(ev);
624
625 // Bubbles are always interested in all touch events!
626 return true;
627 }
628
629 @Override
630 public void onMove(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
631 float viewInitialY, float dx, float dy) {
632 // If we're expanding or collapsing, ignore all touch events.
633 if (mIsExpansionAnimating || mShowedUserEducationInTouchListenerActive) {
634 return;
635 }
636
637 // Show the dismiss target, if we haven't already.
638 mDismissView.show();
639
640 if (mIsExpanded && mExpandedBubble != null && v.equals(mExpandedBubble.getIconView())) {
641 // Hide the expanded view if we're dragging out the expanded bubble, and we haven't
642 // already hidden it.
643 hideExpandedViewIfNeeded();
644 }
645
646 // First, see if the magnetized object consumes the event - if so, we shouldn't move the
647 // bubble since it's stuck to the target.
648 if (!passEventToMagnetizedObject(ev)) {
649 updateBubbleShadows(true /* showForAllBubbles */);
650 if (mBubbleData.isExpanded()) {
651 mExpandedAnimationController.dragBubbleOut(
652 v, viewInitialX + dx, viewInitialY + dy);
653 } else {
654 if (isStackEduShowing()) {
655 mStackEduView.hide(false /* fromExpansion */);
656 }
657 mStackAnimationController.moveStackFromTouch(
658 viewInitialX + dx, viewInitialY + dy);
659 }
660 }
661 }
662
663 @Override
664 public void onUp(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
665 float viewInitialY, float dx, float dy, float velX, float velY) {
666 // If we're expanding or collapsing, ignore all touch events.
667 if (mIsExpansionAnimating) {
668 return;
669 }
670 if (mShowedUserEducationInTouchListenerActive) {
671 mShowedUserEducationInTouchListenerActive = false;
672 return;
673 }
674
675 // First, see if the magnetized object consumes the event - if so, the bubble was
676 // released in the target or flung out of it, and we should ignore the event.
677 if (!passEventToMagnetizedObject(ev)) {
678 if (mBubbleData.isExpanded()) {
679 mExpandedAnimationController.snapBubbleBack(v, velX, velY);
680
681 // Re-show the expanded view if we hid it.
682 showExpandedViewIfNeeded();
683 } else if (mPositioner.showingInTaskbar()) {
684 mStackAnimationController.snapStackBack();
685 } else {
686 // Fling the stack to the edge, and save whether or not it's going to end up on
687 // the left side of the screen.
688 final boolean oldOnLeft = mStackOnLeftOrWillBe;
689 mStackOnLeftOrWillBe =
690 mStackAnimationController.flingStackThenSpringToEdge(
691 viewInitialX + dx, velX, velY) <= 0;
692 final boolean updateForCollapsedStack = oldOnLeft != mStackOnLeftOrWillBe;
693 updateBadges(updateForCollapsedStack);
694 logBubbleEvent(null /* no bubble associated with bubble stack move */,
695 FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__STACK_MOVED);
696 }
697 mDismissView.hide();
698 }
699
700 mIsDraggingStack = false;
701
702 // Hide the stack after a delay, if needed.
703 updateTemporarilyInvisibleAnimation(false /* hideImmediately */);
704 }
705 };
706
707 /** Touch listener set on the whole view that forwards event to the swipe up listener. */
708 private final RelativeTouchListener mContainerSwipeListener = new RelativeTouchListener() {
709 @Override
710 public boolean onDown(@NonNull View v, @NonNull MotionEvent ev) {
711 // Pass move event on to swipe listener
712 mSwipeUpListener.onDown(ev.getX(), ev.getY());
713 return true;
714 }
715
716 @Override
717 public void onMove(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
718 float viewInitialY, float dx, float dy) {
719 // Pass move event on to swipe listener
720 mSwipeUpListener.onMove(dx, dy);
721 }
722
723 @Override
724 public void onUp(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
725 float viewInitialY, float dx, float dy, float velX, float velY) {
726 // Pass up even on to swipe listener
727 mSwipeUpListener.onUp(velX, velY);
728 }
729 };
730
731 /** MotionEventListener that listens from home gesture swipe event. */
732 private final MotionEventListener mSwipeUpListener = new MotionEventListener() {
733 @Override
734 public void onDown(float x, float y) {}
735
736 @Override
737 public void onMove(float dx, float dy) {
738 if ((mManageEduView != null && mManageEduView.getVisibility() == VISIBLE)
739 || isStackEduShowing()) {
740 return;
741 }
742
743 if (mShowingManage) {
744 showManageMenu(false /* show */);
745 }
746 // Only allow up, normalize for up direction
747 float collapsed = -Math.min(dy, 0);
748 mExpandedViewAnimationController.updateDrag((int) collapsed);
749
750 // Update scrim
751 if (!mScrimAnimating) {
752 mScrim.setAlpha(getScrimAlphaForDrag(collapsed));
753 }
754 }
755
756 @Override
757 public void onCancel() {
758 mExpandedViewAnimationController.animateBackToExpanded();
759 }
760
761 @Override
762 public void onUp(float velX, float velY) {
763 mExpandedViewAnimationController.setSwipeVelocity(velY);
764 if (mExpandedViewAnimationController.shouldCollapse()) {
765 // Update data first and start the animation when we are processing change
766 mBubbleData.setExpanded(false);
767 } else {
768 mExpandedViewAnimationController.animateBackToExpanded();
769
770 // Update scrim
771 if (!mScrimAnimating) {
772 showScrim(true);
773 }
774 }
775 }
776
777 private float getScrimAlphaForDrag(float dragAmount) {
778 // dragAmount should be negative as we allow scroll up only
779 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
780 float alphaRange = SCRIM_ALPHA - MIN_SCRIM_ALPHA_FOR_DRAG;
781
782 int dragMax = mExpandedBubble.getExpandedView().getContentHeight();
783 float dragFraction = dragAmount / dragMax;
784
785 return Math.max(SCRIM_ALPHA - alphaRange * dragFraction, MIN_SCRIM_ALPHA_FOR_DRAG);
786 }
787 return SCRIM_ALPHA;
788 }
789 };
790
791 /** Click listener set on the flyout, which expands the stack when the flyout is tapped. */
792 private OnClickListener mFlyoutClickListener = new OnClickListener() {
793 @Override
794 public void onClick(View view) {
795 if (maybeShowStackEdu()) {
796 // If we're showing user education, don't open the bubble show the education first
797 mBubbleToExpandAfterFlyoutCollapse = null;
798 } else {
799 mBubbleToExpandAfterFlyoutCollapse = mBubbleData.getSelectedBubble();
800 }
801
802 mFlyout.removeCallbacks(mHideFlyout);
803 mHideFlyout.run();
804 }
805 };
806
807 /** Touch listener for the flyout. This enables the drag-to-dismiss gesture on the flyout. */
808 private RelativeTouchListener mFlyoutTouchListener = new RelativeTouchListener() {
809
810 @Override
811 public boolean onDown(@NonNull View v, @NonNull MotionEvent ev) {
812 mFlyout.removeCallbacks(mHideFlyout);
813 return true;
814 }
815
816 @Override
817 public void onMove(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
818 float viewInitialY, float dx, float dy) {
819 setFlyoutStateForDragLength(dx);
820 }
821
822 @Override
823 public void onUp(@NonNull View v, @NonNull MotionEvent ev, float viewInitialX,
824 float viewInitialY, float dx, float dy, float velX, float velY) {
825 final boolean onLeft = mStackAnimationController.isStackOnLeftSide();
826 final boolean metRequiredVelocity =
827 onLeft ? velX < -FLYOUT_DISMISS_VELOCITY : velX > FLYOUT_DISMISS_VELOCITY;
828 final boolean metRequiredDeltaX =
829 onLeft
830 ? dx < -mFlyout.getWidth() * FLYOUT_DRAG_PERCENT_DISMISS
831 : dx > mFlyout.getWidth() * FLYOUT_DRAG_PERCENT_DISMISS;
832 final boolean isCancelFling = onLeft ? velX > 0 : velX < 0;
833 final boolean shouldDismiss = metRequiredVelocity
834 || (metRequiredDeltaX && !isCancelFling);
835
836 mFlyout.removeCallbacks(mHideFlyout);
837 animateFlyoutCollapsed(shouldDismiss, velX);
838
839 maybeShowStackEdu();
840 }
841 };
842
843 private BubbleOverflow mBubbleOverflow;
844 private StackEducationView mStackEduView;
845 private ManageEducationView mManageEduView;
846 private DismissView mDismissView;
847
848 private ViewGroup mManageMenu;
849 private ImageView mManageSettingsIcon;
850 private TextView mManageSettingsText;
851 private boolean mShowingManage = false;
852 private boolean mShowedUserEducationInTouchListenerActive = false;
853 private PhysicsAnimator.SpringConfig mManageSpringConfig = new PhysicsAnimator.SpringConfig(
854 SpringForce.STIFFNESS_MEDIUM, SpringForce.DAMPING_RATIO_LOW_BOUNCY);
855 private BubblePositioner mPositioner;
856
857 @SuppressLint("ClickableViewAccessibility")
858 public BubbleStackView(Context context, BubbleController bubbleController,
859 BubbleData data, @Nullable SurfaceSynchronizer synchronizer,
860 FloatingContentCoordinator floatingContentCoordinator,
861 ShellExecutor mainExecutor) {
862 super(context);
863
864 mMainExecutor = mainExecutor;
865 mBubbleController = bubbleController;
866 mBubbleData = data;
867
868 Resources res = getResources();
869 mBubbleSize = res.getDimensionPixelSize(R.dimen.bubble_size);
870 mBubbleElevation = res.getDimensionPixelSize(R.dimen.bubble_elevation);
871 mBubbleTouchPadding = res.getDimensionPixelSize(R.dimen.bubble_touch_padding);
872
873 mExpandedViewPadding = res.getDimensionPixelSize(R.dimen.bubble_expanded_view_padding);
874 int elevation = res.getDimensionPixelSize(R.dimen.bubble_elevation);
875
876 mPositioner = mBubbleController.getPositioner();
877
878 final TypedArray ta = mContext.obtainStyledAttributes(
879 new int[]{android.R.attr.dialogCornerRadius});
880 mCornerRadius = ta.getDimensionPixelSize(0, 0);
881 ta.recycle();
882
883 final Runnable onBubbleAnimatedOut = () -> {
884 if (getBubbleCount() == 0) {
885 mBubbleController.onAllBubblesAnimatedOut();
886 }
887 };
888 mStackAnimationController = new StackAnimationController(
889 floatingContentCoordinator, this::getBubbleCount, onBubbleAnimatedOut,
890 this::animateShadows /* onStackAnimationFinished */, mPositioner);
891
892 mExpandedAnimationController = new ExpandedAnimationController(mPositioner,
893 onBubbleAnimatedOut, this);
894
895 mExpandedViewAnimationController =
896 new ExpandedViewAnimationControllerImpl(context, mPositioner);
897
898 mSurfaceSynchronizer = synchronizer != null ? synchronizer : DEFAULT_SURFACE_SYNCHRONIZER;
899
900 // Force LTR by default since most of the Bubbles UI is positioned manually by the user, or
901 // is centered. It greatly simplifies translation positioning/animations. Views that will
902 // actually lay out differently in RTL, such as the flyout and expanded view, will set their
903 // layout direction to LOCALE.
904 setLayoutDirection(LAYOUT_DIRECTION_LTR);
905
906 mBubbleContainer = new PhysicsAnimationLayout(context);
907 mBubbleContainer.setActiveController(mStackAnimationController);
908 mBubbleContainer.setElevation(elevation);
909 mBubbleContainer.setClipChildren(false);
910 addView(mBubbleContainer, new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
911
912 mExpandedViewContainer = new FrameLayout(context);
913 mExpandedViewContainer.setElevation(elevation);
914 mExpandedViewContainer.setClipChildren(false);
915 addView(mExpandedViewContainer);
916
917 mAnimatingOutSurfaceContainer = new FrameLayout(getContext());
918 mAnimatingOutSurfaceContainer.setLayoutParams(
919 new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
920 addView(mAnimatingOutSurfaceContainer);
921
922 mAnimatingOutSurfaceView = new SurfaceView(getContext());
923 mAnimatingOutSurfaceView.setUseAlpha();
924 mAnimatingOutSurfaceView.setZOrderOnTop(true);
925 boolean supportsRoundedCorners = ScreenDecorationsUtils.supportsRoundedCornersOnWindows(
926 mContext.getResources());
927 mAnimatingOutSurfaceView.setCornerRadius(supportsRoundedCorners ? mCornerRadius : 0);
928 mAnimatingOutSurfaceView.setLayoutParams(new ViewGroup.LayoutParams(0, 0));
929 mAnimatingOutSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
930 @Override
931 public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {}
932
933 @Override
934 public void surfaceCreated(SurfaceHolder surfaceHolder) {
935 mAnimatingOutSurfaceReady = true;
936 }
937
938 @Override
939 public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
940 mAnimatingOutSurfaceReady = false;
941 }
942 });
943 mAnimatingOutSurfaceContainer.addView(mAnimatingOutSurfaceView);
944
945 mAnimatingOutSurfaceContainer.setPadding(
946 mExpandedViewContainer.getPaddingLeft(),
947 mExpandedViewContainer.getPaddingTop(),
948 mExpandedViewContainer.getPaddingRight(),
949 mExpandedViewContainer.getPaddingBottom());
950
951 setUpManageMenu();
952
953 setUpFlyout();
954 mFlyoutTransitionSpring.setSpring(new SpringForce()
955 .setStiffness(SpringForce.STIFFNESS_LOW)
956 .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY));
957 mFlyoutTransitionSpring.addEndListener(mAfterFlyoutTransitionSpring);
958
959 setUpDismissView();
960
961 setClipChildren(false);
962 setFocusable(true);
963 mBubbleContainer.bringToFront();
964
965 mBubbleOverflow = mBubbleData.getOverflow();
966 mBubbleContainer.addView(mBubbleOverflow.getIconView(),
967 mBubbleContainer.getChildCount() /* index */,
968 new FrameLayout.LayoutParams(mPositioner.getBubbleSize(),
969 mPositioner.getBubbleSize()));
970 updateOverflow();
971 mBubbleOverflow.getIconView().setOnClickListener((View v) -> {
972 mBubbleData.setShowingOverflow(true);
973 mBubbleData.setSelectedBubble(mBubbleOverflow);
974 mBubbleData.setExpanded(true);
975 });
976
977 mScrim = new View(getContext());
978 mScrim.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
979 mScrim.setBackgroundDrawable(new ColorDrawable(
980 getResources().getColor(android.R.color.system_neutral1_1000)));
981 addView(mScrim);
982 mScrim.setAlpha(0f);
983
984 mManageMenuScrim = new View(getContext());
985 mManageMenuScrim.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
986 mManageMenuScrim.setBackgroundDrawable(new ColorDrawable(
987 getResources().getColor(android.R.color.system_neutral1_1000)));
988 addView(mManageMenuScrim, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
989 mManageMenuScrim.setAlpha(0f);
990 mManageMenuScrim.setVisibility(INVISIBLE);
991
992 mOrientationChangedListener =
993 (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
994 mPositioner.update();
995 onDisplaySizeChanged();
996 mExpandedAnimationController.updateResources();
997 mStackAnimationController.updateResources();
998 mBubbleOverflow.updateResources();
999
1000 if (!isStackEduShowing() && mRelativeStackPositionBeforeRotation != null) {
1001 mStackAnimationController.setStackPosition(
1002 mRelativeStackPositionBeforeRotation);
1003 mRelativeStackPositionBeforeRotation = null;
1004 }
1005
1006 if (mIsExpanded) {
1007 // Re-draw bubble row and pointer for new orientation.
1008 beforeExpandedViewAnimation();
1009 updateOverflowVisibility();
1010 updatePointerPosition(false /* forIme */);
1011 mExpandedAnimationController.expandFromStack(() -> {
1012 afterExpandedViewAnimation();
1013 showManageMenu(mShowingManage);
1014 } /* after */);
1015 PointF p = mPositioner.getExpandedBubbleXY(getBubbleIndex(mExpandedBubble),
1016 getState());
1017 final float translationY = mPositioner.getExpandedViewY(mExpandedBubble,
1018 mPositioner.showBubblesVertically() ? p.y : p.x);
1019 mExpandedViewContainer.setTranslationX(0f);
1020 mExpandedViewContainer.setTranslationY(translationY);
1021 mExpandedViewContainer.setAlpha(1f);
1022 }
1023 removeOnLayoutChangeListener(mOrientationChangedListener);
1024 };
1025 final float maxDismissSize = getResources().getDimensionPixelSize(
1026 R.dimen.dismiss_circle_size);
1027 final float minDismissSize = getResources().getDimensionPixelSize(
1028 R.dimen.dismiss_circle_small);
1029 final float sizePercent = minDismissSize / maxDismissSize;
1030 mDismissBubbleAnimator = ValueAnimator.ofFloat(1f, 0f);
1031 mDismissBubbleAnimator.addUpdateListener(animation -> {
1032 final float animatedValue = (float) animation.getAnimatedValue();
1033 if (mDismissView != null) {
1034 mDismissView.setPivotX((mDismissView.getRight() - mDismissView.getLeft()) / 2f);
1035 mDismissView.setPivotY((mDismissView.getBottom() - mDismissView.getTop()) / 2f);
1036 final float scaleValue = Math.max(animatedValue, sizePercent);
1037 mDismissView.getCircle().setScaleX(scaleValue);
1038 mDismissView.getCircle().setScaleY(scaleValue);
1039 }
1040 if (mViewBeingDismissed != null) {
1041 mViewBeingDismissed.setAlpha(Math.max(animatedValue, 0.7f));
1042 }
1043 });
1044
1045 // If the stack itself is clicked, it means none of its touchable views (bubbles, flyouts,
1046 // TaskView, etc.) were touched. Collapse the stack if it's expanded.
1047 setOnClickListener(view -> {
1048 if (mShowingManage) {
1049 showManageMenu(false /* show */);
1050 } else if (mManageEduView != null && mManageEduView.getVisibility() == VISIBLE) {
1051 mManageEduView.hide();
1052 } else if (isStackEduShowing()) {
1053 mStackEduView.hide(false /* isExpanding */);
1054 } else if (mBubbleData.isExpanded()) {
1055 mBubbleData.setExpanded(false);
1056 } else {
1057 maybeShowStackEdu();
1058 }
1059 });
1060
1061 animate()
1062 .setInterpolator(Interpolators.PANEL_CLOSE_ACCELERATED)
1063 .setDuration(FADE_IN_DURATION);
1064
1065 mExpandedViewAlphaAnimator.setDuration(EXPANDED_VIEW_ALPHA_ANIMATION_DURATION);
1066 mExpandedViewAlphaAnimator.setInterpolator(Interpolators.PANEL_CLOSE_ACCELERATED);
1067 mExpandedViewAlphaAnimator.addListener(new AnimatorListenerAdapter() {
1068 @Override
1069 public void onAnimationStart(Animator animation) {
1070 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
1071 // We need to be Z ordered on top in order for alpha animations to work.
1072 mExpandedBubble.getExpandedView().setSurfaceZOrderedOnTop(true);
1073 mExpandedBubble.getExpandedView().setAnimating(true);
1074 }
1075 }
1076
1077 @Override
1078 public void onAnimationEnd(Animator animation) {
1079 if (mExpandedBubble != null
1080 && mExpandedBubble.getExpandedView() != null
1081 // The surface needs to be Z ordered on top for alpha values to work on the
1082 // TaskView, and if we're temporarily hidden, we are still on the screen
1083 // with alpha = 0f until we animate back. Stay Z ordered on top so the alpha
1084 // = 0f remains in effect.
1085 && !mExpandedViewTemporarilyHidden) {
1086 mExpandedBubble.getExpandedView().setSurfaceZOrderedOnTop(false);
1087 mExpandedBubble.getExpandedView().setAnimating(false);
1088 }
1089 }
1090 });
1091 mExpandedViewAlphaAnimator.addUpdateListener(valueAnimator -> {
1092 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
1093 float alpha = (float) valueAnimator.getAnimatedValue();
1094 mExpandedBubble.getExpandedView().setContentAlpha(alpha);
1095 mExpandedBubble.getExpandedView().setBackgroundAlpha(alpha);
1096 }
1097 });
1098
1099 mAnimatingOutSurfaceAlphaAnimator.setDuration(EXPANDED_VIEW_ALPHA_ANIMATION_DURATION);
1100 mAnimatingOutSurfaceAlphaAnimator.setInterpolator(Interpolators.PANEL_CLOSE_ACCELERATED);
1101 mAnimatingOutSurfaceAlphaAnimator.addUpdateListener(valueAnimator -> {
1102 if (!mExpandedViewTemporarilyHidden) {
1103 mAnimatingOutSurfaceView.setAlpha((float) valueAnimator.getAnimatedValue());
1104 }
1105 });
1106 mAnimatingOutSurfaceAlphaAnimator.addListener(new AnimatorListenerAdapter() {
1107 @Override
1108 public void onAnimationEnd(Animator animation) {
1109 releaseAnimatingOutBubbleBuffer();
1110 }
1111 });
1112 }
1113
1114 /**
1115 * Sets whether or not the stack should become temporarily invisible by moving off the side of
1116 * the screen.
1117 *
1118 * If a flyout comes in while it's invisible, it will animate back in while the flyout is
1119 * showing but disappear again when the flyout is gone.
1120 */
1121 public void setTemporarilyInvisible(boolean invisible) {
1122 mTemporarilyInvisible = invisible;
1123
1124 // If we are animating out, hide immediately if possible so we animate out with the status
1125 // bar.
1126 updateTemporarilyInvisibleAnimation(invisible /* hideImmediately */);
1127 }
1128
1129 /**
1130 * Animates the stack to be temporarily invisible, if needed.
1131 *
1132 * If we're currently dragging the stack, or a flyout is visible, the stack will remain visible.
1133 * regardless of the value of {@link #mTemporarilyInvisible}. This method is called on ACTION_UP
1134 * as well as whenever a flyout hides, so we will animate invisible at that point if needed.
1135 */
1136 private void updateTemporarilyInvisibleAnimation(boolean hideImmediately) {
1137 removeCallbacks(mAnimateTemporarilyInvisibleImmediate);
1138
1139 if (mIsDraggingStack) {
1140 // If we're dragging the stack, don't animate it invisible.
1141 return;
1142 }
1143
1144 final boolean shouldHide =
1145 mTemporarilyInvisible && mFlyout.getVisibility() != View.VISIBLE;
1146
1147 postDelayed(mAnimateTemporarilyInvisibleImmediate,
1148 shouldHide && !hideImmediately ? ANIMATE_TEMPORARILY_INVISIBLE_DELAY : 0);
1149 }
1150
1151 private final Runnable mAnimateTemporarilyInvisibleImmediate = () -> {
1152 if (mTemporarilyInvisible && mFlyout.getVisibility() != View.VISIBLE) {
1153 // To calculate a distance, bubble stack needs to be moved to become hidden,
1154 // we need to take into account that the bubble stack is positioned on the edge
1155 // of the available screen rect, which can be offset by system bars and cutouts.
1156 if (mStackAnimationController.isStackOnLeftSide()) {
1157 int availableRectOffsetX =
1158 mPositioner.getAvailableRect().left - mPositioner.getScreenRect().left;
1159 animate().translationX(-(mBubbleSize + availableRectOffsetX)).start();
1160 } else {
1161 int availableRectOffsetX =
1162 mPositioner.getAvailableRect().right - mPositioner.getScreenRect().right;
1163 animate().translationX(mBubbleSize - availableRectOffsetX).start();
1164 }
1165 } else {
1166 animate().translationX(0).start();
1167 }
1168 };
1169
1170 private void setUpDismissView() {
1171 if (mDismissView != null) {
1172 removeView(mDismissView);
1173 }
1174 mDismissView = new DismissView(getContext());
1175 int elevation = getResources().getDimensionPixelSize(R.dimen.bubble_elevation);
1176
1177 addView(mDismissView);
1178 mDismissView.setElevation(elevation);
1179
1180 final ContentResolver contentResolver = getContext().getContentResolver();
1181 final int dismissRadius = Settings.Secure.getInt(
1182 contentResolver, "bubble_dismiss_radius", mBubbleSize * 2 /* default */);
1183
1184 // Save the MagneticTarget instance for the newly set up view - we'll add this to the
1185 // MagnetizedObjects when the dismiss view gets shown.
1186 mMagneticTarget = new MagnetizedObject.MagneticTarget(
1187 mDismissView.getCircle(), dismissRadius);
1188 mBubbleContainer.bringToFront();
1189 }
1190
1191 // TODO: Create ManageMenuView and move setup / animations there
1192 private void setUpManageMenu() {
1193 if (mManageMenu != null) {
1194 removeView(mManageMenu);
1195 }
1196
1197 mManageMenu = (ViewGroup) LayoutInflater.from(getContext()).inflate(
1198 R.layout.bubble_manage_menu, this, false);
1199 mManageMenu.setVisibility(View.INVISIBLE);
1200
1201 PhysicsAnimator.getInstance(mManageMenu).setDefaultSpringConfig(mManageSpringConfig);
1202
1203 mManageMenu.setOutlineProvider(new ViewOutlineProvider() {
1204 @Override
1205 public void getOutline(View view, Outline outline) {
1206 outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), mCornerRadius);
1207 }
1208 });
1209 mManageMenu.setClipToOutline(true);
1210
1211 mManageMenu.findViewById(R.id.bubble_manage_menu_dismiss_container).setOnClickListener(
1212 view -> {
1213 showManageMenu(false /* show */);
1214 dismissBubbleIfExists(mBubbleData.getSelectedBubble());
1215 });
1216
1217 mManageMenu.findViewById(R.id.bubble_manage_menu_dont_bubble_container).setOnClickListener(
1218 view -> {
1219 showManageMenu(false /* show */);
1220 mUnbubbleConversationCallback.accept(mBubbleData.getSelectedBubble().getKey());
1221 });
1222
1223 mManageMenu.findViewById(R.id.bubble_manage_menu_settings_container).setOnClickListener(
1224 view -> {
1225 showManageMenu(false /* show */);
1226 final BubbleViewProvider bubble = mBubbleData.getSelectedBubble();
1227 if (bubble != null && mBubbleData.hasBubbleInStackWithKey(bubble.getKey())) {
1228 // If it's in the stack it's a proper Bubble.
1229 final Intent intent = ((Bubble) bubble).getSettingsIntent(mContext);
1230 mBubbleData.setExpanded(false);
1231 mContext.startActivityAsUser(intent, ((Bubble) bubble).getUser());
1232 logBubbleEvent(bubble,
1233 FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__HEADER_GO_TO_SETTINGS);
1234 }
1235 });
1236
1237 mManageSettingsIcon = mManageMenu.findViewById(R.id.bubble_manage_menu_settings_icon);
1238 mManageSettingsText = mManageMenu.findViewById(R.id.bubble_manage_menu_settings_name);
1239
1240 // The menu itself should respect locale direction so the icons are on the correct side.
1241 mManageMenu.setLayoutDirection(LAYOUT_DIRECTION_LOCALE);
1242 addView(mManageMenu);
1243 updateManageButtonListener();
1244 }
1245
1246 /**
1247 * Whether the educational view should show for the expanded view "manage" menu.
1248 */
1249 private boolean shouldShowManageEdu() {
1250 if (ActivityManager.isRunningInTestHarness()) {
1251 return false;
1252 }
1253 final boolean seen = getPrefBoolean(ManageEducationViewKt.PREF_MANAGED_EDUCATION);
1254 final boolean shouldShow = (!seen || BubbleDebugConfig.forceShowUserEducation(mContext))
1255 && mExpandedBubble != null && mExpandedBubble.getExpandedView() != null;
1256 if (BubbleDebugConfig.DEBUG_USER_EDUCATION) {
1257 Log.d(TAG, "Show manage edu: " + shouldShow);
1258 }
1259 return shouldShow;
1260 }
1261
1262 private void maybeShowManageEdu() {
1263 if (!shouldShowManageEdu()) {
1264 return;
1265 }
1266 if (mManageEduView == null) {
1267 mManageEduView = new ManageEducationView(mContext, mPositioner);
1268 addView(mManageEduView);
1269 }
1270 mManageEduView.show(mExpandedBubble.getExpandedView());
1271 }
1272
1273 /**
1274 * Whether education view should show for the collapsed stack.
1275 */
1276 private boolean shouldShowStackEdu() {
1277 if (ActivityManager.isRunningInTestHarness()) {
1278 return false;
1279 }
1280 final boolean seen = getPrefBoolean(StackEducationViewKt.PREF_STACK_EDUCATION);
1281 final boolean shouldShow = !seen || BubbleDebugConfig.forceShowUserEducation(mContext);
1282 if (BubbleDebugConfig.DEBUG_USER_EDUCATION) {
1283 Log.d(TAG, "Show stack edu: " + shouldShow);
1284 }
1285 return shouldShow;
1286 }
1287
1288 private boolean getPrefBoolean(String key) {
1289 return mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE)
1290 .getBoolean(key, false /* default */);
1291 }
1292
1293 /**
1294 * @return true if education view for collapsed stack should show and was not showing before.
1295 */
1296 private boolean maybeShowStackEdu() {
1297 if (!shouldShowStackEdu() || isExpanded()) {
1298 return false;
1299 }
1300 if (mStackEduView == null) {
1301 mStackEduView = new StackEducationView(mContext, mPositioner, mBubbleController);
1302 addView(mStackEduView);
1303 }
1304 mBubbleContainer.bringToFront();
1305 // Ensure the stack is in the correct spot
1306 mStackAnimationController.setStackPosition(mPositioner.getDefaultStartPosition());
1307 return mStackEduView.show(mPositioner.getDefaultStartPosition());
1308 }
1309
1310 private boolean isStackEduShowing() {
1311 return mStackEduView != null && mStackEduView.getVisibility() == VISIBLE;
1312 }
1313
1314 // Recreates & shows the education views. Call when a theme/config change happens.
1315 private void updateUserEdu() {
1316 if (isStackEduShowing()) {
1317 removeView(mStackEduView);
1318 mStackEduView = new StackEducationView(mContext, mPositioner, mBubbleController);
1319 addView(mStackEduView);
1320 mBubbleContainer.bringToFront(); // Stack appears on top of the stack education
1321 // Ensure the stack is in the correct spot
1322 mStackAnimationController.setStackPosition(mPositioner.getDefaultStartPosition());
1323 mStackEduView.show(mPositioner.getDefaultStartPosition());
1324 }
1325 if (mManageEduView != null && mManageEduView.getVisibility() == VISIBLE) {
1326 removeView(mManageEduView);
1327 mManageEduView = new ManageEducationView(mContext, mPositioner);
1328 addView(mManageEduView);
1329 mManageEduView.show(mExpandedBubble.getExpandedView());
1330 }
1331 }
1332
1333 @SuppressLint("ClickableViewAccessibility")
1334 private void setUpFlyout() {
1335 if (mFlyout != null) {
1336 removeView(mFlyout);
1337 }
1338 mFlyout = new BubbleFlyoutView(getContext(), mPositioner);
1339 mFlyout.setVisibility(GONE);
1340 mFlyout.setOnClickListener(mFlyoutClickListener);
1341 mFlyout.setOnTouchListener(mFlyoutTouchListener);
1342 addView(mFlyout, new FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
1343 }
1344
1345 void updateFontScale() {
1346 setUpManageMenu();
1347 mFlyout.updateFontSize();
1348 for (Bubble b : mBubbleData.getBubbles()) {
1349 if (b.getExpandedView() != null) {
1350 b.getExpandedView().updateFontSize();
1351 }
1352 }
1353 if (mBubbleOverflow != null && mBubbleOverflow.getExpandedView() != null) {
1354 mBubbleOverflow.getExpandedView().updateFontSize();
1355 }
1356 }
1357
1358 private void updateOverflow() {
1359 mBubbleOverflow.update();
1360 mBubbleContainer.reorderView(mBubbleOverflow.getIconView(),
1361 mBubbleContainer.getChildCount() - 1 /* index */);
1362 updateOverflowVisibility();
1363 }
1364
1365 void updateOverflowButtonDot() {
1366 for (Bubble b : mBubbleData.getOverflowBubbles()) {
1367 if (b.showDot()) {
1368 mBubbleOverflow.setShowDot(true);
1369 return;
1370 }
1371 }
1372 mBubbleOverflow.setShowDot(false);
1373 }
1374
1375 /**
1376 * Handle theme changes.
1377 */
1378 public void onThemeChanged() {
1379 setUpFlyout();
1380 setUpManageMenu();
1381 setUpDismissView();
1382 updateOverflow();
1383 updateUserEdu();
1384 updateExpandedViewTheme();
1385 mScrim.setBackgroundDrawable(new ColorDrawable(
1386 getResources().getColor(android.R.color.system_neutral1_1000)));
1387 mManageMenuScrim.setBackgroundDrawable(new ColorDrawable(
1388 getResources().getColor(android.R.color.system_neutral1_1000)));
1389 }
1390
1391 /**
1392 * Respond to the phone being rotated by repositioning the stack and hiding any flyouts.
1393 * This is called prior to the rotation occurring, any values that should be updated
1394 * based on the new rotation should occur in {@link #mOrientationChangedListener}.
1395 */
1396 public void onOrientationChanged() {
1397 mRelativeStackPositionBeforeRotation = new RelativeStackPosition(
1398 mPositioner.getRestingPosition(),
1399 mPositioner.getAllowableStackPositionRegion(getBubbleCount()));
1400 addOnLayoutChangeListener(mOrientationChangedListener);
1401 hideFlyoutImmediate();
1402 }
1403
1404 /** Tells the views with locale-dependent layout direction to resolve the new direction. */
1405 public void onLayoutDirectionChanged(int direction) {
1406 mManageMenu.setLayoutDirection(direction);
1407 mFlyout.setLayoutDirection(direction);
1408 if (mStackEduView != null) {
1409 mStackEduView.setLayoutDirection(direction);
1410 }
1411 if (mManageEduView != null) {
1412 mManageEduView.setLayoutDirection(direction);
1413 }
1414 updateExpandedViewDirection(direction);
1415 }
1416
1417 /** Respond to the display size change by recalculating view size and location. */
1418 public void onDisplaySizeChanged() {
1419 updateOverflow();
1420 setUpFlyout();
1421 setUpDismissView();
1422 updateUserEdu();
1423 mBubbleSize = mPositioner.getBubbleSize();
1424 for (Bubble b : mBubbleData.getBubbles()) {
1425 if (b.getIconView() == null) {
1426 Log.d(TAG, "Display size changed. Icon null: " + b);
1427 continue;
1428 }
1429 b.getIconView().setLayoutParams(new LayoutParams(mBubbleSize, mBubbleSize));
1430 if (b.getExpandedView() != null) {
1431 b.getExpandedView().updateDimensions();
1432 }
1433 }
1434 mBubbleOverflow.getIconView().setLayoutParams(new LayoutParams(mBubbleSize, mBubbleSize));
1435 mExpandedAnimationController.updateResources();
1436 mStackAnimationController.updateResources();
1437 mDismissView.updateResources();
1438 mMagneticTarget.setMagneticFieldRadiusPx(mBubbleSize * 2);
1439 if (!isStackEduShowing()) {
1440 mStackAnimationController.setStackPosition(
1441 new RelativeStackPosition(
1442 mPositioner.getRestingPosition(),
1443 mPositioner.getAllowableStackPositionRegion(getBubbleCount())));
1444 }
1445 if (mIsExpanded) {
1446 updateExpandedView();
1447 }
1448 setUpManageMenu();
1449 }
1450
1451 @Override
1452 public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo inoutInfo) {
1453 inoutInfo.setTouchableInsets(ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION);
1454
1455 mTempRect.setEmpty();
1456 getTouchableRegion(mTempRect);
1457 inoutInfo.touchableRegion.set(mTempRect);
1458 }
1459
1460 @Override
1461 protected void onAttachedToWindow() {
1462 super.onAttachedToWindow();
1463 mPositioner.update();
1464 getViewTreeObserver().addOnComputeInternalInsetsListener(this);
1465 getViewTreeObserver().addOnDrawListener(mSystemGestureExcludeUpdater);
1466 }
1467
1468 @Override
1469 protected void onDetachedFromWindow() {
1470 super.onDetachedFromWindow();
1471 getViewTreeObserver().removeOnPreDrawListener(mViewUpdater);
1472 getViewTreeObserver().removeOnDrawListener(mSystemGestureExcludeUpdater);
1473 getViewTreeObserver().removeOnComputeInternalInsetsListener(this);
1474 if (mBubbleOverflow != null) {
1475 mBubbleOverflow.cleanUpExpandedState();
1476 }
1477 }
1478
1479 @Override
1480 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
1481 super.onInitializeAccessibilityNodeInfoInternal(info);
1482 setupLocalMenu(info);
1483 }
1484
1485 void updateExpandedViewTheme() {
1486 final List<Bubble> bubbles = mBubbleData.getBubbles();
1487 if (bubbles.isEmpty()) {
1488 return;
1489 }
1490 bubbles.forEach(bubble -> {
1491 if (bubble.getExpandedView() != null) {
1492 bubble.getExpandedView().applyThemeAttrs();
1493 }
1494 });
1495 }
1496
1497 void updateExpandedViewDirection(int direction) {
1498 final List<Bubble> bubbles = mBubbleData.getBubbles();
1499 if (bubbles.isEmpty()) {
1500 return;
1501 }
1502 bubbles.forEach(bubble -> {
1503 if (bubble.getExpandedView() != null) {
1504 bubble.getExpandedView().setLayoutDirection(direction);
1505 }
1506 });
1507 }
1508
1509 void setupLocalMenu(AccessibilityNodeInfo info) {
1510 Resources res = mContext.getResources();
1511
1512 // Custom local actions.
1513 AccessibilityAction moveTopLeft = new AccessibilityAction(R.id.action_move_top_left,
1514 res.getString(R.string.bubble_accessibility_action_move_top_left));
1515 info.addAction(moveTopLeft);
1516
1517 AccessibilityAction moveTopRight = new AccessibilityAction(R.id.action_move_top_right,
1518 res.getString(R.string.bubble_accessibility_action_move_top_right));
1519 info.addAction(moveTopRight);
1520
1521 AccessibilityAction moveBottomLeft = new AccessibilityAction(R.id.action_move_bottom_left,
1522 res.getString(R.string.bubble_accessibility_action_move_bottom_left));
1523 info.addAction(moveBottomLeft);
1524
1525 AccessibilityAction moveBottomRight = new AccessibilityAction(R.id.action_move_bottom_right,
1526 res.getString(R.string.bubble_accessibility_action_move_bottom_right));
1527 info.addAction(moveBottomRight);
1528
1529 // Default actions.
1530 info.addAction(AccessibilityAction.ACTION_DISMISS);
1531 if (mIsExpanded) {
1532 info.addAction(AccessibilityAction.ACTION_COLLAPSE);
1533 } else {
1534 info.addAction(AccessibilityAction.ACTION_EXPAND);
1535 }
1536 }
1537
1538 @Override
1539 public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
1540 if (super.performAccessibilityActionInternal(action, arguments)) {
1541 return true;
1542 }
1543 final RectF stackBounds = mPositioner.getAllowableStackPositionRegion(getBubbleCount());
1544
1545 // R constants are not final so we cannot use switch-case here.
1546 if (action == AccessibilityNodeInfo.ACTION_DISMISS) {
1547 mBubbleData.dismissAll(Bubbles.DISMISS_ACCESSIBILITY_ACTION);
1548 announceForAccessibility(
1549 getResources().getString(R.string.accessibility_bubble_dismissed));
1550 return true;
1551 } else if (action == AccessibilityNodeInfo.ACTION_COLLAPSE) {
1552 mBubbleData.setExpanded(false);
1553 return true;
1554 } else if (action == AccessibilityNodeInfo.ACTION_EXPAND) {
1555 mBubbleData.setExpanded(true);
1556 return true;
1557 } else if (action == R.id.action_move_top_left) {
1558 mStackAnimationController.springStackAfterFling(stackBounds.left, stackBounds.top);
1559 return true;
1560 } else if (action == R.id.action_move_top_right) {
1561 mStackAnimationController.springStackAfterFling(stackBounds.right, stackBounds.top);
1562 return true;
1563 } else if (action == R.id.action_move_bottom_left) {
1564 mStackAnimationController.springStackAfterFling(stackBounds.left, stackBounds.bottom);
1565 return true;
1566 } else if (action == R.id.action_move_bottom_right) {
1567 mStackAnimationController.springStackAfterFling(stackBounds.right, stackBounds.bottom);
1568 return true;
1569 }
1570 return false;
1571 }
1572
1573 /**
1574 * Update content description for a11y TalkBack.
1575 */
1576 public void updateContentDescription() {
1577 if (mBubbleData.getBubbles().isEmpty()) {
1578 return;
1579 }
1580
1581 for (int i = 0; i < mBubbleData.getBubbles().size(); i++) {
1582 final Bubble bubble = mBubbleData.getBubbles().get(i);
1583 final String appName = bubble.getAppName();
1584
1585 String titleStr = bubble.getTitle();
1586 if (titleStr == null) {
1587 titleStr = getResources().getString(R.string.notification_bubble_title);
1588 }
1589
1590 if (bubble.getIconView() != null) {
1591 if (mIsExpanded || i > 0) {
1592 bubble.getIconView().setContentDescription(getResources().getString(
1593 R.string.bubble_content_description_single, titleStr, appName));
1594 } else {
1595 final int moreCount = mBubbleContainer.getChildCount() - 1;
1596 bubble.getIconView().setContentDescription(getResources().getString(
1597 R.string.bubble_content_description_stack,
1598 titleStr, appName, moreCount));
1599 }
1600 }
1601 }
1602 }
1603
1604 /**
1605 * Update bubbles' icon views accessibility states.
1606 */
1607 public void updateBubblesAcessibillityStates() {
1608 for (int i = 0; i < mBubbleData.getBubbles().size(); i++) {
1609 Bubble prevBubble = i > 0 ? mBubbleData.getBubbles().get(i - 1) : null;
1610 Bubble bubble = mBubbleData.getBubbles().get(i);
1611
1612 View bubbleIconView = bubble.getIconView();
1613 if (bubbleIconView == null) {
1614 continue;
1615 }
1616
1617 if (mIsExpanded) {
1618 // when stack is expanded
1619 // all bubbles are important for accessibility
1620 bubbleIconView
1621 .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
1622
1623 View prevBubbleIconView = prevBubble != null ? prevBubble.getIconView() : null;
1624
1625 if (prevBubbleIconView != null) {
1626 bubbleIconView.setAccessibilityDelegate(new View.AccessibilityDelegate() {
1627 @Override
1628 public void onInitializeAccessibilityNodeInfo(View v,
1629 AccessibilityNodeInfo info) {
1630 super.onInitializeAccessibilityNodeInfo(v, info);
1631 info.setTraversalAfter(prevBubbleIconView);
1632 }
1633 });
1634 }
1635 } else {
1636 // when stack is collapsed, only the top bubble is important for accessibility,
1637 bubbleIconView.setImportantForAccessibility(
1638 i == 0 ? View.IMPORTANT_FOR_ACCESSIBILITY_YES :
1639 View.IMPORTANT_FOR_ACCESSIBILITY_NO);
1640 }
1641 }
1642
1643 if (mIsExpanded) {
1644 // make the overflow bubble last in the accessibility traversal order
1645
1646 View bubbleOverflowIconView =
1647 mBubbleOverflow != null ? mBubbleOverflow.getIconView() : null;
1648 if (bubbleOverflowIconView != null && !mBubbleData.getBubbles().isEmpty()) {
1649 Bubble lastBubble =
1650 mBubbleData.getBubbles().get(mBubbleData.getBubbles().size() - 1);
1651 View lastBubbleIconView = lastBubble.getIconView();
1652 if (lastBubbleIconView != null) {
1653 bubbleOverflowIconView.setAccessibilityDelegate(
1654 new View.AccessibilityDelegate() {
1655 @Override
1656 public void onInitializeAccessibilityNodeInfo(View v,
1657 AccessibilityNodeInfo info) {
1658 super.onInitializeAccessibilityNodeInfo(v, info);
1659 info.setTraversalAfter(lastBubbleIconView);
1660 }
1661 });
1662 }
1663 }
1664 }
1665 }
1666
1667 private void updateSystemGestureExcludeRects() {
1668 // Exclude the region occupied by the first BubbleView in the stack
1669 Rect excludeZone = mSystemGestureExclusionRects.get(0);
1670 if (getBubbleCount() > 0) {
1671 View firstBubble = mBubbleContainer.getChildAt(0);
1672 excludeZone.set(firstBubble.getLeft(), firstBubble.getTop(), firstBubble.getRight(),
1673 firstBubble.getBottom());
1674 excludeZone.offset((int) (firstBubble.getTranslationX() + 0.5f),
1675 (int) (firstBubble.getTranslationY() + 0.5f));
1676 mBubbleContainer.setSystemGestureExclusionRects(mSystemGestureExclusionRects);
1677 } else {
1678 excludeZone.setEmpty();
1679 mBubbleContainer.setSystemGestureExclusionRects(Collections.emptyList());
1680 }
1681 }
1682
1683 /**
1684 * Sets the listener to notify when the bubble stack is expanded.
1685 */
1686 public void setExpandListener(Bubbles.BubbleExpandListener listener) {
1687 mExpandListener = listener;
1688 }
1689
1690 /** Sets the function to call to un-bubble the given conversation. */
1691 public void setUnbubbleConversationCallback(
1692 Consumer<String> unbubbleConversationCallback) {
1693 mUnbubbleConversationCallback = unbubbleConversationCallback;
1694 }
1695
1696 /**
1697 * Whether the stack of bubbles is expanded or not.
1698 */
1699 public boolean isExpanded() {
1700 return mIsExpanded;
1701 }
1702
1703 /**
1704 * Whether the stack of bubbles is animating to or from expansion.
1705 */
1706 public boolean isExpansionAnimating() {
1707 return mIsExpansionAnimating;
1708 }
1709
1710 /**
1711 * Whether the stack of bubbles is animating a switch between bubbles.
1712 */
1713 public boolean isSwitchAnimating() {
1714 return mIsBubbleSwitchAnimating;
1715 }
1716
1717 /**
1718 * The {@link Bubble} that is expanded, null if one does not exist.
1719 */
1720 @VisibleForTesting
1721 @Nullable
1722 public BubbleViewProvider getExpandedBubble() {
1723 return mExpandedBubble;
1724 }
1725
1726 // via BubbleData.Listener
1727 @SuppressLint("ClickableViewAccessibility")
1728 void addBubble(Bubble bubble) {
1729 if (DEBUG_BUBBLE_STACK_VIEW) {
1730 Log.d(TAG, "addBubble: " + bubble);
1731 }
1732
1733 final boolean firstBubble = getBubbleCount() == 0;
1734
1735 if (firstBubble && shouldShowStackEdu()) {
1736 // Override the default stack position if we're showing user education.
1737 mStackAnimationController.setStackPosition(mPositioner.getDefaultStartPosition());
1738 }
1739
1740 if (bubble.getIconView() == null) {
1741 return;
1742 }
1743
1744 mBubbleContainer.addView(bubble.getIconView(), 0,
1745 new FrameLayout.LayoutParams(mPositioner.getBubbleSize(),
1746 mPositioner.getBubbleSize()));
1747
1748 if (firstBubble) {
1749 mStackOnLeftOrWillBe = mStackAnimationController.isStackOnLeftSide();
1750 }
1751 // Set the dot position to the opposite of the side the stack is resting on, since the stack
1752 // resting slightly off-screen would result in the dot also being off-screen.
1753 bubble.getIconView().setDotBadgeOnLeft(!mStackOnLeftOrWillBe /* onLeft */);
1754 bubble.getIconView().setOnClickListener(mBubbleClickListener);
1755 bubble.getIconView().setOnTouchListener(mBubbleTouchListener);
1756 updateBubbleShadows(false /* showForAllBubbles */);
1757 animateInFlyoutForBubble(bubble);
1758 requestUpdate();
1759 logBubbleEvent(bubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__POSTED);
1760 }
1761
1762 // via BubbleData.Listener
1763 void removeBubble(Bubble bubble) {
1764 if (DEBUG_BUBBLE_STACK_VIEW) {
1765 Log.d(TAG, "removeBubble: " + bubble);
1766 }
1767 // Remove it from the views
1768 for (int i = 0; i < getBubbleCount(); i++) {
1769 View v = mBubbleContainer.getChildAt(i);
1770 if (v instanceof BadgedImageView
1771 && ((BadgedImageView) v).getKey().equals(bubble.getKey())) {
1772 mBubbleContainer.removeViewAt(i);
1773 if (mBubbleData.hasOverflowBubbleWithKey(bubble.getKey())) {
1774 bubble.cleanupExpandedView();
1775 } else {
1776 bubble.cleanupViews();
1777 }
1778 updateExpandedView();
1779 if (getBubbleCount() == 0 && !isExpanded()) {
1780 // This is the last bubble and the stack is collapsed
1781 updateStackPosition();
1782 }
1783 logBubbleEvent(bubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__DISMISSED);
1784 return;
1785 }
1786 }
1787 // If a bubble is suppressed, it is not attached to the container. Clean it up.
1788 if (bubble.isSuppressed()) {
1789 bubble.cleanupViews();
1790 } else {
1791 Log.d(TAG, "was asked to remove Bubble, but didn't find the view! " + bubble);
1792 }
1793 }
1794
1795 private void updateOverflowVisibility() {
1796 mBubbleOverflow.setVisible((mIsExpanded || mBubbleData.isShowingOverflow())
1797 ? VISIBLE
1798 : GONE);
1799 }
1800
1801 // via BubbleData.Listener
1802 void updateBubble(Bubble bubble) {
1803 animateInFlyoutForBubble(bubble);
1804 requestUpdate();
1805 logBubbleEvent(bubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__UPDATED);
1806 }
1807
1808 /**
1809 * Update bubble order and pointer position.
1810 */
1811 public void updateBubbleOrder(List<Bubble> bubbles, boolean updatePointerPositoion) {
1812 final Runnable reorder = () -> {
1813 for (int i = 0; i < bubbles.size(); i++) {
1814 Bubble bubble = bubbles.get(i);
1815 mBubbleContainer.reorderView(bubble.getIconView(), i);
1816 }
1817 };
1818 if (mIsExpanded || isExpansionAnimating()) {
1819 reorder.run();
1820 updateBadges(false /* setBadgeForCollapsedStack */);
1821 updateZOrder();
1822 } else if (!isExpansionAnimating()) {
1823 List<View> bubbleViews = bubbles.stream()
1824 .map(b -> b.getIconView()).collect(Collectors.toList());
1825 mStackAnimationController.animateReorder(bubbleViews, reorder);
1826 }
1827
1828 if (updatePointerPositoion) {
1829 updatePointerPosition(false /* forIme */);
1830 }
1831 }
1832
1833 /**
1834 * Changes the currently selected bubble. If the stack is already expanded, the newly selected
1835 * bubble will be shown immediately. This does not change the expanded state or change the
1836 * position of any bubble.
1837 */
1838 // via BubbleData.Listener
1839 public void setSelectedBubble(@Nullable BubbleViewProvider bubbleToSelect) {
1840 if (DEBUG_BUBBLE_STACK_VIEW) {
1841 Log.d(TAG, "setSelectedBubble: " + bubbleToSelect);
1842 }
1843
1844 if (bubbleToSelect == null) {
1845 mBubbleData.setShowingOverflow(false);
1846 return;
1847 }
1848
1849 // Ignore this new bubble only if it is the exact same bubble object. Otherwise, we'll want
1850 // to re-render it even if it has the same key (equals() returns true). If the currently
1851 // expanded bubble is removed and instantly re-added, we'll get back a new Bubble instance
1852 // with the same key (with newly inflated expanded views), and we need to render those new
1853 // views.
1854 if (mExpandedBubble == bubbleToSelect) {
1855 return;
1856 }
1857
1858 if (bubbleToSelect.getKey().equals(BubbleOverflow.KEY)) {
1859 mBubbleData.setShowingOverflow(true);
1860 } else {
1861 mBubbleData.setShowingOverflow(false);
1862 }
1863
1864 if (mIsExpanded && mIsExpansionAnimating) {
1865 // If the bubble selection changed during the expansion animation, the expanding bubble
1866 // probably crashed or immediately removed itself (or, we just got unlucky with a new
1867 // auto-expanding bubble showing up at just the right time). Cancel the animations so we
1868 // can start fresh.
1869 cancelAllExpandCollapseSwitchAnimations();
1870 }
1871 showManageMenu(false /* show */);
1872
1873 // If we're expanded, screenshot the currently expanded bubble (before expanding the newly
1874 // selected bubble) so we can animate it out.
1875 if (mIsExpanded && mExpandedBubble != null && mExpandedBubble.getExpandedView() != null
1876 && !mExpandedViewTemporarilyHidden) {
1877 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
1878 // Before screenshotting, have the real TaskView show on top of other surfaces
1879 // so that the screenshot doesn't flicker on top of it.
1880 mExpandedBubble.getExpandedView().setSurfaceZOrderedOnTop(true);
1881 }
1882
1883 try {
1884 screenshotAnimatingOutBubbleIntoSurface((success) -> {
1885 mAnimatingOutSurfaceContainer.setVisibility(
1886 success ? View.VISIBLE : View.INVISIBLE);
1887 showNewlySelectedBubble(bubbleToSelect);
1888 });
1889 } catch (Exception e) {
1890 showNewlySelectedBubble(bubbleToSelect);
1891 e.printStackTrace();
1892 }
1893 } else {
1894 showNewlySelectedBubble(bubbleToSelect);
1895 }
1896 }
1897
1898 private void showNewlySelectedBubble(BubbleViewProvider bubbleToSelect) {
1899 final BubbleViewProvider previouslySelected = mExpandedBubble;
1900 mExpandedBubble = bubbleToSelect;
1901 mExpandedViewAnimationController.setExpandedView(mExpandedBubble.getExpandedView());
1902
1903 if (mIsExpanded) {
1904 hideCurrentInputMethod();
1905
1906 // Make the container of the expanded view transparent before removing the expanded view
1907 // from it. Otherwise a punch hole created by {@link android.view.SurfaceView} in the
1908 // expanded view becomes visible on the screen. See b/126856255
1909 mExpandedViewContainer.setAlpha(0.0f);
1910 mSurfaceSynchronizer.syncSurfaceAndRun(() -> {
1911 if (previouslySelected != null) {
1912 previouslySelected.setTaskViewVisibility(false);
1913 }
1914
1915 updateExpandedBubble();
1916 requestUpdate();
1917
1918 logBubbleEvent(previouslySelected,
1919 FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__COLLAPSED);
1920 logBubbleEvent(bubbleToSelect,
1921 FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__EXPANDED);
1922 notifyExpansionChanged(previouslySelected, false /* expanded */);
1923 notifyExpansionChanged(bubbleToSelect, true /* expanded */);
1924 });
1925 }
1926 }
1927
1928 /**
1929 * Changes the expanded state of the stack.
1930 * Don't call this directly, call mBubbleData#setExpanded.
1931 *
1932 * @param shouldExpand whether the bubble stack should appear expanded
1933 */
1934 // via BubbleData.Listener
1935 public void setExpanded(boolean shouldExpand) {
1936 if (DEBUG_BUBBLE_STACK_VIEW) {
1937 Log.d(TAG, "setExpanded: " + shouldExpand);
1938 }
1939
1940 if (!shouldExpand) {
1941 // If we're collapsing, release the animating-out surface immediately since we have no
1942 // need for it, and this ensures it cannot remain visible as we collapse.
1943 releaseAnimatingOutBubbleBuffer();
1944 }
1945
1946 if (shouldExpand == mIsExpanded) {
1947 return;
1948 }
1949
1950 boolean wasExpanded = mIsExpanded;
1951
1952 hideCurrentInputMethod();
1953
1954 mBubbleController.getSysuiProxy().onStackExpandChanged(shouldExpand);
1955
1956 if (wasExpanded) {
1957 stopMonitoringSwipeUpGesture();
1958 animateCollapse();
1959 showManageMenu(false);
1960 logBubbleEvent(mExpandedBubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__COLLAPSED);
1961 } else {
1962 animateExpansion();
1963 // TODO: move next line to BubbleData
1964 logBubbleEvent(mExpandedBubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__EXPANDED);
1965 logBubbleEvent(mExpandedBubble,
1966 FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__STACK_EXPANDED);
1967 mBubbleController.isNotificationPanelExpanded(notifPanelExpanded -> {
1968 if (!notifPanelExpanded && mIsExpanded) {
1969 startMonitoringSwipeUpGesture();
1970 }
1971 });
1972 }
1973 notifyExpansionChanged(mExpandedBubble, mIsExpanded);
1974 }
1975
1976 /**
1977 * Monitor for swipe up gesture that is used to collapse expanded view
1978 */
1979 void startMonitoringSwipeUpGesture() {
1980 if (DEBUG_BUBBLE_GESTURE) {
1981 Log.d(TAG, "startMonitoringSwipeUpGesture");
1982 }
1983 stopMonitoringSwipeUpGestureInternal();
1984
1985 if (isGestureNavEnabled()) {
1986 mBubblesNavBarGestureTracker = new BubblesNavBarGestureTracker(mContext, mPositioner);
1987 mBubblesNavBarGestureTracker.start(mSwipeUpListener);
1988 setOnTouchListener(mContainerSwipeListener);
1989 }
1990 }
1991
1992 private boolean isGestureNavEnabled() {
1993 return mContext.getResources().getInteger(
1994 com.android.internal.R.integer.config_navBarInteractionMode)
1995 == WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL;
1996 }
1997
1998 /**
1999 * Stop monitoring for swipe up gesture
2000 */
2001 void stopMonitoringSwipeUpGesture() {
2002 if (DEBUG_BUBBLE_GESTURE) {
2003 Log.d(TAG, "stopMonitoringSwipeUpGesture");
2004 }
2005 stopMonitoringSwipeUpGestureInternal();
2006 }
2007
2008 private void stopMonitoringSwipeUpGestureInternal() {
2009 if (mBubblesNavBarGestureTracker != null) {
2010 mBubblesNavBarGestureTracker.stop();
2011 mBubblesNavBarGestureTracker = null;
2012 setOnTouchListener(null);
2013 }
2014 }
2015
2016 /**
2017 * Called when back press occurs while bubbles are expanded.
2018 */
2019 public void onBackPressed() {
2020 if (mIsExpanded) {
2021 if (mShowingManage) {
2022 showManageMenu(false);
2023 } else if (mManageEduView != null && mManageEduView.getVisibility() == VISIBLE) {
2024 mManageEduView.hide();
2025 } else {
2026 mBubbleData.setExpanded(false);
2027 }
2028 }
2029 }
2030
2031 void setBubbleSuppressed(Bubble bubble, boolean suppressed) {
2032 if (DEBUG_BUBBLE_STACK_VIEW) {
2033 Log.d(TAG, "setBubbleSuppressed: suppressed=" + suppressed + " bubble=" + bubble);
2034 }
2035 if (suppressed) {
2036 int index = getBubbleIndex(bubble);
2037 mBubbleContainer.removeViewAt(index);
2038 updateExpandedView();
2039 } else {
2040 if (bubble.getIconView() == null) {
2041 return;
2042 }
2043 if (bubble.getIconView().getParent() != null) {
2044 Log.e(TAG, "Bubble is already added to parent. Can't unsuppress: " + bubble);
2045 return;
2046 }
2047 int index = mBubbleData.getBubbles().indexOf(bubble);
2048 // Add the view back to the correct position
2049 mBubbleContainer.addView(bubble.getIconView(), index,
2050 new LayoutParams(mPositioner.getBubbleSize(),
2051 mPositioner.getBubbleSize()));
2052 updateBubbleShadows(false /* showForAllBubbles */);
2053 requestUpdate();
2054 }
2055 }
2056
2057 /**
2058 * Asks the BubbleController to hide the IME from anywhere, whether it's focused on Bubbles or
2059 * not.
2060 */
2061 void hideCurrentInputMethod() {
2062 mPositioner.setImeVisible(false, 0);
2063 mBubbleController.hideCurrentInputMethod();
2064 }
2065
2066 /** Set the stack position to whatever the positioner says. */
2067 void updateStackPosition() {
2068 mStackAnimationController.setStackPosition(mPositioner.getRestingPosition());
2069 mDismissView.hide();
2070 }
2071
2072 private void beforeExpandedViewAnimation() {
2073 mIsExpansionAnimating = true;
2074 hideFlyoutImmediate();
2075 updateExpandedBubble();
2076 updateExpandedView();
2077 }
2078
2079 private void afterExpandedViewAnimation() {
2080 mIsExpansionAnimating = false;
2081 updateExpandedView();
2082 requestUpdate();
2083 }
2084
2085 /** Animate the expanded view hidden. This is done while we're dragging out a bubble. */
2086 private void hideExpandedViewIfNeeded() {
2087 if (mExpandedViewTemporarilyHidden
2088 || mExpandedBubble == null
2089 || mExpandedBubble.getExpandedView() == null) {
2090 return;
2091 }
2092
2093 mExpandedViewTemporarilyHidden = true;
2094
2095 // Scale down.
2096 PhysicsAnimator.getInstance(mExpandedViewContainerMatrix)
2097 .spring(AnimatableScaleMatrix.SCALE_X,
2098 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(
2099 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT),
2100 mScaleOutSpringConfig)
2101 .spring(AnimatableScaleMatrix.SCALE_Y,
2102 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(
2103 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT),
2104 mScaleOutSpringConfig)
2105 .addUpdateListener((target, values) ->
2106 mExpandedViewContainer.setAnimationMatrix(mExpandedViewContainerMatrix))
2107 .start();
2108
2109 // Animate alpha from 1f to 0f.
2110 mExpandedViewAlphaAnimator.reverse();
2111 }
2112
2113 /**
2114 * Animate the expanded view visible again. This is done when we're done dragging out a bubble.
2115 */
2116 private void showExpandedViewIfNeeded() {
2117 if (!mExpandedViewTemporarilyHidden) {
2118 return;
2119 }
2120
2121 mExpandedViewTemporarilyHidden = false;
2122
2123 PhysicsAnimator.getInstance(mExpandedViewContainerMatrix)
2124 .spring(AnimatableScaleMatrix.SCALE_X,
2125 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(1f),
2126 mScaleOutSpringConfig)
2127 .spring(AnimatableScaleMatrix.SCALE_Y,
2128 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(1f),
2129 mScaleOutSpringConfig)
2130 .addUpdateListener((target, values) ->
2131 mExpandedViewContainer.setAnimationMatrix(mExpandedViewContainerMatrix))
2132 .start();
2133
2134 mExpandedViewAlphaAnimator.start();
2135 }
2136
2137 private void showScrim(boolean show) {
2138 AnimatorListenerAdapter listener = new AnimatorListenerAdapter() {
2139 @Override
2140 public void onAnimationStart(Animator animation) {
2141 mScrimAnimating = true;
2142 }
2143
2144 @Override
2145 public void onAnimationEnd(Animator animation) {
2146 mScrimAnimating = false;
2147 }
2148 };
2149 if (show) {
2150 mScrim.animate()
2151 .setInterpolator(ALPHA_IN)
2152 .alpha(SCRIM_ALPHA)
2153 .setListener(listener)
2154 .start();
2155 } else {
2156 mScrim.animate()
2157 .alpha(0f)
2158 .setInterpolator(ALPHA_OUT)
2159 .setListener(listener)
2160 .start();
2161 }
2162 }
2163
2164 private void animateExpansion() {
2165 cancelDelayedExpandCollapseSwitchAnimations();
2166 final boolean showVertically = mPositioner.showBubblesVertically();
2167 mIsExpanded = true;
2168 if (isStackEduShowing()) {
2169 mStackEduView.hide(true /* fromExpansion */);
2170 }
2171 beforeExpandedViewAnimation();
2172
2173 showScrim(true);
2174 updateZOrder();
2175 updateBadges(false /* setBadgeForCollapsedStack */);
2176 mBubbleContainer.setActiveController(mExpandedAnimationController);
2177 updateOverflowVisibility();
2178 updatePointerPosition(false /* forIme */);
2179 mExpandedAnimationController.expandFromStack(() -> {
2180 if (mIsExpanded && mExpandedBubble.getExpandedView() != null) {
2181 maybeShowManageEdu();
2182 }
2183 } /* after */);
2184 int index;
2185 if (mExpandedBubble != null && BubbleOverflow.KEY.equals(mExpandedBubble.getKey())) {
2186 index = mBubbleData.getBubbles().size();
2187 } else {
2188 index = getBubbleIndex(mExpandedBubble);
2189 }
2190 PointF p = mPositioner.getExpandedBubbleXY(index, getState());
2191 final float translationY = mPositioner.getExpandedViewY(mExpandedBubble,
2192 mPositioner.showBubblesVertically() ? p.y : p.x);
2193 mExpandedViewContainer.setTranslationX(0f);
2194 mExpandedViewContainer.setTranslationY(translationY);
2195 mExpandedViewContainer.setAlpha(1f);
2196
2197 // How far horizontally the bubble will be animating. We'll wait a bit longer for bubbles
2198 // that are animating farther, so that the expanded view doesn't move as much.
2199 final float relevantStackPosition = showVertically
2200 ? mStackAnimationController.getStackPosition().y
2201 : mStackAnimationController.getStackPosition().x;
2202 final float bubbleWillBeAt = showVertically
2203 ? p.y
2204 : p.x;
2205 final float distanceAnimated = Math.abs(bubbleWillBeAt - relevantStackPosition);
2206
2207 // Wait for the path animation target to reach its end, and add a small amount of extra time
2208 // if the bubble is moving a lot horizontally.
2209 long startDelay = 0L;
2210
2211 // Should not happen since we lay out before expanding, but just in case...
2212 if (getWidth() > 0) {
2213 startDelay = (long)
2214 (ExpandedAnimationController.EXPAND_COLLAPSE_TARGET_ANIM_DURATION * 1.2f
2215 + (distanceAnimated / getWidth()) * 30);
2216 }
2217
2218 // Set the pivot point for the scale, so the expanded view animates out from the bubble.
2219 if (showVertically) {
2220 float pivotX;
2221 if (mStackOnLeftOrWillBe) {
2222 pivotX = p.x + mBubbleSize + mExpandedViewPadding;
2223 } else {
2224 pivotX = p.x - mExpandedViewPadding;
2225 }
2226 mExpandedViewContainerMatrix.setScale(
2227 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2228 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2229 pivotX,
2230 p.y + mBubbleSize / 2f);
2231 } else {
2232 mExpandedViewContainerMatrix.setScale(
2233 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2234 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2235 p.x + mBubbleSize / 2f,
2236 p.y + mBubbleSize + mExpandedViewPadding);
2237 }
2238 mExpandedViewContainer.setAnimationMatrix(mExpandedViewContainerMatrix);
2239
2240 if (mExpandedBubble.getExpandedView() != null) {
2241 mExpandedBubble.getExpandedView().setContentAlpha(0f);
2242 mExpandedBubble.getExpandedView().setBackgroundAlpha(0f);
2243
2244 // We'll be starting the alpha animation after a slight delay, so set this flag early
2245 // here.
2246 mExpandedBubble.getExpandedView().setAnimating(true);
2247 }
2248
2249 mDelayedAnimation = () -> {
2250 mExpandedViewAlphaAnimator.start();
2251
2252 PhysicsAnimator.getInstance(mExpandedViewContainerMatrix).cancel();
2253 PhysicsAnimator.getInstance(mExpandedViewContainerMatrix)
2254 .spring(AnimatableScaleMatrix.SCALE_X,
2255 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(1f),
2256 mScaleInSpringConfig)
2257 .spring(AnimatableScaleMatrix.SCALE_Y,
2258 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(1f),
2259 mScaleInSpringConfig)
2260 .addUpdateListener((target, values) -> {
2261 if (mExpandedBubble == null || mExpandedBubble.getIconView() == null) {
2262 return;
2263 }
2264 float translation = showVertically
2265 ? mExpandedBubble.getIconView().getTranslationY()
2266 : mExpandedBubble.getIconView().getTranslationX();
2267 mExpandedViewContainerMatrix.postTranslate(
2268 translation - bubbleWillBeAt,
2269 0);
2270 mExpandedViewContainer.setAnimationMatrix(
2271 mExpandedViewContainerMatrix);
2272 })
2273 .withEndActions(() -> {
2274 mExpandedViewContainer.setAnimationMatrix(null);
2275 afterExpandedViewAnimation();
2276 if (mExpandedBubble != null
2277 && mExpandedBubble.getExpandedView() != null) {
2278 mExpandedBubble.getExpandedView()
2279 .setSurfaceZOrderedOnTop(false);
2280 }
2281 })
2282 .start();
2283 };
2284 mMainExecutor.executeDelayed(mDelayedAnimation, startDelay);
2285 }
2286
2287 private void animateCollapse() {
2288 cancelDelayedExpandCollapseSwitchAnimations();
2289
2290 if (mManageEduView != null && mManageEduView.getVisibility() == VISIBLE) {
2291 mManageEduView.hide();
2292 }
2293
2294 mIsExpanded = false;
2295 mIsExpansionAnimating = true;
2296
2297 showScrim(false);
2298
2299 mBubbleContainer.cancelAllAnimations();
2300
2301 // If we were in the middle of swapping, the animating-out surface would have been scaling
2302 // to zero - finish it off.
2303 PhysicsAnimator.getInstance(mAnimatingOutSurfaceContainer).cancel();
2304 mAnimatingOutSurfaceContainer.setScaleX(0f);
2305 mAnimatingOutSurfaceContainer.setScaleY(0f);
2306
2307 // Let the expanded animation controller know that it shouldn't animate child adds/reorders
2308 // since we're about to animate collapsed.
2309 mExpandedAnimationController.notifyPreparingToCollapse();
2310
2311 final Runnable collapseBackToStack = () -> mExpandedAnimationController.collapseBackToStack(
2312 mStackAnimationController
2313 .getStackPositionAlongNearestHorizontalEdge()
2314 /* collapseTo */,
2315 () -> mBubbleContainer.setActiveController(mStackAnimationController));
2316
2317 final Runnable after = () -> {
2318 final BubbleViewProvider previouslySelected = mExpandedBubble;
2319 // TODO(b/231350255): investigate why this call is needed here
2320 beforeExpandedViewAnimation();
2321 if (mManageEduView != null) {
2322 mManageEduView.hide();
2323 }
2324
2325 if (DEBUG_BUBBLE_STACK_VIEW) {
2326 Log.d(TAG, "animateCollapse");
2327 Log.d(TAG, BubbleDebugConfig.formatBubblesString(getBubblesOnScreen(),
2328 mExpandedBubble));
2329 }
2330 updateOverflowVisibility();
2331 updateZOrder();
2332 updateBadges(true /* setBadgeForCollapsedStack */);
2333 afterExpandedViewAnimation();
2334 if (previouslySelected != null) {
2335 previouslySelected.setTaskViewVisibility(false);
2336 }
2337 mExpandedViewAnimationController.reset();
2338 };
2339 mExpandedViewAnimationController.animateCollapse(collapseBackToStack, after);
2340 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
2341 // When the animation completes, we should no longer be showing the content.
2342 // This won't actually update content visibility immediately, if we are currently
2343 // animating. But updates the internal state for the content to be hidden after
2344 // animation completes.
2345 mExpandedBubble.getExpandedView().setContentVisibility(false);
2346 }
2347 }
2348
2349 private void animateSwitchBubbles() {
2350 // If we're no longer expanded, this is meaningless.
2351 if (!mIsExpanded) {
2352 mIsBubbleSwitchAnimating = false;
2353 return;
2354 }
2355
2356 // The surface contains a screenshot of the animating out bubble, so we just need to animate
2357 // it out (and then release the GraphicBuffer).
2358 PhysicsAnimator.getInstance(mAnimatingOutSurfaceContainer).cancel();
2359
2360 mAnimatingOutSurfaceAlphaAnimator.reverse();
2361 mExpandedViewAlphaAnimator.start();
2362
2363 if (mPositioner.showBubblesVertically()) {
2364 float translationX = mStackAnimationController.isStackOnLeftSide()
2365 ? mAnimatingOutSurfaceContainer.getTranslationX() + mBubbleSize * 2
2366 : mAnimatingOutSurfaceContainer.getTranslationX();
2367 PhysicsAnimator.getInstance(mAnimatingOutSurfaceContainer)
2368 .spring(DynamicAnimation.TRANSLATION_X, translationX, mTranslateSpringConfig)
2369 .start();
2370 } else {
2371 PhysicsAnimator.getInstance(mAnimatingOutSurfaceContainer)
2372 .spring(DynamicAnimation.TRANSLATION_Y,
2373 mAnimatingOutSurfaceContainer.getTranslationY() - mBubbleSize,
2374 mTranslateSpringConfig)
2375 .start();
2376 }
2377
2378 boolean isOverflow = mExpandedBubble != null
2379 && mExpandedBubble.getKey().equals(BubbleOverflow.KEY);
2380 PointF p = mPositioner.getExpandedBubbleXY(isOverflow
2381 ? mBubbleContainer.getChildCount() - 1
2382 : mBubbleData.getBubbles().indexOf(mExpandedBubble),
2383 getState());
2384 mExpandedViewContainer.setAlpha(1f);
2385 mExpandedViewContainer.setVisibility(View.VISIBLE);
2386
2387 if (mPositioner.showBubblesVertically()) {
2388 float pivotX;
2389 float pivotY = p.y + mBubbleSize / 2f;
2390 if (mStackOnLeftOrWillBe) {
2391 pivotX = p.x + mBubbleSize + mExpandedViewPadding;
2392 } else {
2393 pivotX = p.x - mExpandedViewPadding;
2394 }
2395 mExpandedViewContainerMatrix.setScale(
2396 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2397 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2398 pivotX, pivotY);
2399 } else {
2400 mExpandedViewContainerMatrix.setScale(
2401 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2402 1f - EXPANDED_VIEW_ANIMATE_SCALE_AMOUNT,
2403 p.x + mBubbleSize / 2f,
2404 p.y + mBubbleSize + mExpandedViewPadding);
2405 }
2406
2407 mExpandedViewContainer.setAnimationMatrix(mExpandedViewContainerMatrix);
2408
2409 mMainExecutor.executeDelayed(() -> {
2410 if (!mIsExpanded) {
2411 mIsBubbleSwitchAnimating = false;
2412 return;
2413 }
2414
2415 PhysicsAnimator.getInstance(mExpandedViewContainerMatrix).cancel();
2416 PhysicsAnimator.getInstance(mExpandedViewContainerMatrix)
2417 .spring(AnimatableScaleMatrix.SCALE_X,
2418 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(1f),
2419 mScaleInSpringConfig)
2420 .spring(AnimatableScaleMatrix.SCALE_Y,
2421 AnimatableScaleMatrix.getAnimatableValueForScaleFactor(1f),
2422 mScaleInSpringConfig)
2423 .addUpdateListener((target, values) -> {
2424 mExpandedViewContainer.setAnimationMatrix(mExpandedViewContainerMatrix);
2425 })
2426 .withEndActions(() -> {
2427 mExpandedViewTemporarilyHidden = false;
2428 mIsBubbleSwitchAnimating = false;
2429 mExpandedViewContainer.setAnimationMatrix(null);
2430 })
2431 .start();
2432 }, 25);
2433 }
2434
2435 /**
2436 * Cancels any delayed steps for expand/collapse and bubble switch animations, and resets the is
2437 * animating flags for those animations.
2438 */
2439 private void cancelDelayedExpandCollapseSwitchAnimations() {
2440 mMainExecutor.removeCallbacks(mDelayedAnimation);
2441
2442 mIsExpansionAnimating = false;
2443 mIsBubbleSwitchAnimating = false;
2444 }
2445
2446 private void cancelAllExpandCollapseSwitchAnimations() {
2447 cancelDelayedExpandCollapseSwitchAnimations();
2448
2449 PhysicsAnimator.getInstance(mAnimatingOutSurfaceView).cancel();
2450 PhysicsAnimator.getInstance(mExpandedViewContainerMatrix).cancel();
2451
2452 mExpandedViewContainer.setAnimationMatrix(null);
2453 }
2454
2455 private void notifyExpansionChanged(BubbleViewProvider bubble, boolean expanded) {
2456 if (mExpandListener != null && bubble != null) {
2457 mExpandListener.onBubbleExpandChanged(expanded, bubble.getKey());
2458 }
2459 }
2460
2461 /**
2462 * Updates the stack based for IME changes. When collapsed it'll move the stack if it
2463 * overlaps where they IME would be. When expanded it'll shift the expanded bubbles
2464 * if they might overlap with the IME (this only happens for large screens)
2465 * and clip the expanded view.
2466 */
2467 public void setImeVisible(boolean visible) {
2468 if ((mIsExpansionAnimating || mIsBubbleSwitchAnimating) && mIsExpanded) {
2469 // This will update the animation so the bubbles move to position for the IME
2470 mExpandedAnimationController.expandFromStack(() -> {
2471 updatePointerPosition(false /* forIme */);
2472 afterExpandedViewAnimation();
2473 mExpandedViewAnimationController.animateForImeVisibilityChange(visible);
2474 } /* after */);
2475 return;
2476 }
2477
2478 if (!mIsExpanded && getBubbleCount() > 0) {
2479 final float stackDestinationY =
2480 mStackAnimationController.animateForImeVisibility(visible);
2481
2482 // How far the stack is animating due to IME, we'll just animate the flyout by that
2483 // much too.
2484 final float stackDy =
2485 stackDestinationY - mStackAnimationController.getStackPosition().y;
2486
2487 // If the flyout is visible, translate it along with the bubble stack.
2488 if (mFlyout.getVisibility() == VISIBLE) {
2489 PhysicsAnimator.getInstance(mFlyout)
2490 .spring(DynamicAnimation.TRANSLATION_Y,
2491 mFlyout.getTranslationY() + stackDy,
2492 FLYOUT_IME_ANIMATION_SPRING_CONFIG)
2493 .start();
2494 }
2495 }
2496
2497 if (mIsExpanded) {
2498 mExpandedViewAnimationController.animateForImeVisibilityChange(visible);
2499 if (mPositioner.showBubblesVertically()
2500 && mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
2501 float selectedY = mPositioner.getExpandedBubbleXY(getState().selectedIndex,
2502 getState()).y;
2503 float newExpandedViewTop = mPositioner.getExpandedViewY(mExpandedBubble, selectedY);
2504 mExpandedBubble.getExpandedView().setImeVisible(visible);
2505 if (!mExpandedBubble.getExpandedView().isUsingMaxHeight()) {
2506 mExpandedViewContainer.animate().translationY(newExpandedViewTop);
2507 }
2508 List<Animator> animList = new ArrayList();
2509 for (int i = 0; i < mBubbleContainer.getChildCount(); i++) {
2510 View child = mBubbleContainer.getChildAt(i);
2511 float transY = mPositioner.getExpandedBubbleXY(i, getState()).y;
2512 ObjectAnimator anim = ObjectAnimator.ofFloat(child, TRANSLATION_Y, transY);
2513 animList.add(anim);
2514 }
2515 updatePointerPosition(true /* forIme */);
2516 AnimatorSet set = new AnimatorSet();
2517 set.playTogether(animList);
2518 set.start();
2519 }
2520 }
2521 }
2522
2523 @Override
2524 public boolean dispatchTouchEvent(MotionEvent ev) {
2525 if (ev.getAction() != MotionEvent.ACTION_DOWN && ev.getActionIndex() != mPointerIndexDown) {
2526 // Ignore touches from additional pointer indices.
2527 return false;
2528 }
2529
2530 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2531 mPointerIndexDown = ev.getActionIndex();
2532 } else if (ev.getAction() == MotionEvent.ACTION_UP
2533 || ev.getAction() == MotionEvent.ACTION_CANCEL) {
2534 mPointerIndexDown = -1;
2535 }
2536
2537 boolean dispatched = super.dispatchTouchEvent(ev);
2538
2539 // If a new bubble arrives while the collapsed stack is being dragged, it will be positioned
2540 // at the front of the stack (under the touch position). Subsequent ACTION_MOVE events will
2541 // then be passed to the new bubble, which will not consume them since it hasn't received an
2542 // ACTION_DOWN yet. Work around this by passing MotionEvents directly to the touch handler
2543 // until the current gesture ends with an ACTION_UP event.
2544 if (!dispatched && !mIsExpanded && mIsGestureInProgress) {
2545 dispatched = mBubbleTouchListener.onTouch(this /* view */, ev);
2546 }
2547
2548 mIsGestureInProgress =
2549 ev.getAction() != MotionEvent.ACTION_UP
2550 && ev.getAction() != MotionEvent.ACTION_CANCEL;
2551
2552 return dispatched;
2553 }
2554
2555 void setFlyoutStateForDragLength(float deltaX) {
2556 // This shouldn't happen, but if it does, just wait until the flyout lays out. This method
2557 // is continually called.
2558 if (mFlyout.getWidth() <= 0) {
2559 return;
2560 }
2561
2562 final boolean onLeft = mStackAnimationController.isStackOnLeftSide();
2563 mFlyoutDragDeltaX = deltaX;
2564
2565 final float collapsePercent =
2566 onLeft ? -deltaX / mFlyout.getWidth() : deltaX / mFlyout.getWidth();
2567 mFlyout.setCollapsePercent(Math.min(1f, Math.max(0f, collapsePercent)));
2568
2569 // Calculate how to translate the flyout if it has been dragged too far in either direction.
2570 float overscrollTranslation = 0f;
2571 if (collapsePercent < 0f || collapsePercent > 1f) {
2572 // Whether we are more than 100% transitioned to the dot.
2573 final boolean overscrollingPastDot = collapsePercent > 1f;
2574
2575 // Whether we are overscrolling physically to the left - this can either be pulling the
2576 // flyout away from the stack (if the stack is on the right) or pushing it to the left
2577 // after it has already become the dot.
2578 final boolean overscrollingLeft =
2579 (onLeft && collapsePercent > 1f) || (!onLeft && collapsePercent < 0f);
2580 overscrollTranslation =
2581 (overscrollingPastDot ? collapsePercent - 1f : collapsePercent * -1)
2582 * (overscrollingLeft ? -1 : 1)
2583 * (mFlyout.getWidth() / (FLYOUT_OVERSCROLL_ATTENUATION_FACTOR
2584 // Attenuate the smaller dot less than the larger flyout.
2585 / (overscrollingPastDot ? 2 : 1)));
2586 }
2587
2588 mFlyout.setTranslationX(mFlyout.getRestingTranslationX() + overscrollTranslation);
2589 }
2590
2591 /** Passes the MotionEvent to the magnetized object and returns true if it was consumed. */
2592 private boolean passEventToMagnetizedObject(MotionEvent event) {
2593 return mMagnetizedObject != null && mMagnetizedObject.maybeConsumeMotionEvent(event);
2594 }
2595
2596 /**
2597 * Dismisses the magnetized object - either an individual bubble, if we're expanded, or the
2598 * stack, if we're collapsed.
2599 */
2600 private void dismissMagnetizedObject() {
2601 if (mIsExpanded) {
2602 final View draggedOutBubbleView = (View) mMagnetizedObject.getUnderlyingObject();
2603 dismissBubbleIfExists(mBubbleData.getBubbleWithView(draggedOutBubbleView));
2604 } else {
2605 mBubbleData.dismissAll(Bubbles.DISMISS_USER_GESTURE);
2606 }
2607 }
2608
2609 private void dismissBubbleIfExists(@Nullable BubbleViewProvider bubble) {
2610 if (bubble != null && mBubbleData.hasBubbleInStackWithKey(bubble.getKey())) {
2611 if (mIsExpanded && mBubbleData.getBubbles().size() > 1
2612 && Objects.equals(bubble, mExpandedBubble)) {
2613 // If we have more than 1 bubble and it's the current bubble being dismissed,
2614 // we will perform the switch animation
2615 mIsBubbleSwitchAnimating = true;
2616 }
2617 mBubbleData.dismissBubbleWithKey(bubble.getKey(), Bubbles.DISMISS_USER_GESTURE);
2618 }
2619 }
2620
2621 /** Prepares and starts the dismiss animation on the bubble stack. */
2622 private void animateDismissBubble(View targetView, boolean applyAlpha) {
2623 mViewBeingDismissed = targetView;
2624
2625 if (mViewBeingDismissed == null) {
2626 return;
2627 }
2628 if (applyAlpha) {
2629 mDismissBubbleAnimator.removeAllListeners();
2630 mDismissBubbleAnimator.start();
2631 } else {
2632 mDismissBubbleAnimator.removeAllListeners();
2633 mDismissBubbleAnimator.addListener(new AnimatorListenerAdapter() {
2634 @Override
2635 public void onAnimationEnd(Animator animation) {
2636 super.onAnimationEnd(animation);
2637 resetDismissAnimator();
2638 }
2639
2640 @Override
2641 public void onAnimationCancel(Animator animation) {
2642 super.onAnimationCancel(animation);
2643 resetDismissAnimator();
2644 }
2645 });
2646 mDismissBubbleAnimator.reverse();
2647 }
2648 }
2649
2650 private void resetDismissAnimator() {
2651 mDismissBubbleAnimator.removeAllListeners();
2652 mDismissBubbleAnimator.cancel();
2653
2654 if (mViewBeingDismissed != null) {
2655 mViewBeingDismissed.setAlpha(1f);
2656 mViewBeingDismissed = null;
2657 }
2658 if (mDismissView != null) {
2659 mDismissView.getCircle().setScaleX(1f);
2660 mDismissView.getCircle().setScaleY(1f);
2661 }
2662 }
2663
2664 /** Animates the flyout collapsed (to dot), or the reverse, starting with the given velocity. */
2665 private void animateFlyoutCollapsed(boolean collapsed, float velX) {
2666 final boolean onLeft = mStackAnimationController.isStackOnLeftSide();
2667 // If the flyout was tapped, we want a higher stiffness for the collapse animation so it's
2668 // faster.
2669 mFlyoutTransitionSpring.getSpring().setStiffness(
2670 (mBubbleToExpandAfterFlyoutCollapse != null)
2671 ? SpringForce.STIFFNESS_MEDIUM
2672 : SpringForce.STIFFNESS_LOW);
2673 mFlyoutTransitionSpring
2674 .setStartValue(mFlyoutDragDeltaX)
2675 .setStartVelocity(velX)
2676 .animateToFinalPosition(collapsed
2677 ? (onLeft ? -mFlyout.getWidth() : mFlyout.getWidth())
2678 : 0f);
2679 }
2680
2681 private boolean shouldShowFlyout(Bubble bubble) {
2682 Bubble.FlyoutMessage flyoutMessage = bubble.getFlyoutMessage();
2683 final BadgedImageView bubbleView = bubble.getIconView();
2684 if (flyoutMessage == null
2685 || flyoutMessage.message == null
2686 || !bubble.showFlyout()
2687 || isStackEduShowing()
2688 || isExpanded()
2689 || mIsExpansionAnimating
2690 || mIsGestureInProgress
2691 || mBubbleToExpandAfterFlyoutCollapse != null
2692 || bubbleView == null) {
2693 if (bubbleView != null && mFlyout.getVisibility() != VISIBLE) {
2694 bubbleView.removeDotSuppressionFlag(BadgedImageView.SuppressionFlag.FLYOUT_VISIBLE);
2695 }
2696 // Skip the message if none exists, we're expanded or animating expansion, or we're
2697 // about to expand a bubble from the previous tapped flyout, or if bubble view is null.
2698 return false;
2699 }
2700 return true;
2701 }
2702
2703 /**
2704 * Animates in the flyout for the given bubble, if available, and then hides it after some time.
2705 */
2706 @VisibleForTesting
2707 void animateInFlyoutForBubble(Bubble bubble) {
2708 if (!shouldShowFlyout(bubble)) {
2709 return;
2710 }
2711
2712 mFlyoutDragDeltaX = 0f;
2713 clearFlyoutOnHide();
2714 mAfterFlyoutHidden = () -> {
2715 // Null it out to ensure it runs once.
2716 mAfterFlyoutHidden = null;
2717
2718 if (mBubbleToExpandAfterFlyoutCollapse != null) {
2719 // User tapped on the flyout and we should expand
2720 mBubbleData.setSelectedBubble(mBubbleToExpandAfterFlyoutCollapse);
2721 mBubbleData.setExpanded(true);
2722 mBubbleToExpandAfterFlyoutCollapse = null;
2723 }
2724
2725 // Stop suppressing the dot now that the flyout has morphed into the dot.
2726 if (bubble.getIconView() != null) {
2727 bubble.getIconView().removeDotSuppressionFlag(
2728 BadgedImageView.SuppressionFlag.FLYOUT_VISIBLE);
2729 }
2730 // Hide the stack after a delay, if needed.
2731 updateTemporarilyInvisibleAnimation(false /* hideImmediately */);
2732 };
2733
2734 // Suppress the dot when we are animating the flyout.
2735 bubble.getIconView().addDotSuppressionFlag(
2736 BadgedImageView.SuppressionFlag.FLYOUT_VISIBLE);
2737
2738 // Start flyout expansion. Post in case layout isn't complete and getWidth returns 0.
2739 post(() -> {
2740 // An auto-expanding bubble could have been posted during the time it takes to
2741 // layout.
2742 if (isExpanded() || bubble.getIconView() == null) {
2743 return;
2744 }
2745 final Runnable expandFlyoutAfterDelay = () -> {
2746 mAnimateInFlyout = () -> {
2747 mFlyout.setVisibility(VISIBLE);
2748 updateTemporarilyInvisibleAnimation(false /* hideImmediately */);
2749 mFlyoutDragDeltaX =
2750 mStackAnimationController.isStackOnLeftSide()
2751 ? -mFlyout.getWidth()
2752 : mFlyout.getWidth();
2753 animateFlyoutCollapsed(false /* collapsed */, 0 /* velX */);
2754 mFlyout.postDelayed(mHideFlyout, FLYOUT_HIDE_AFTER);
2755 };
2756 mFlyout.postDelayed(mAnimateInFlyout, 200);
2757 };
2758
2759
2760 if (mFlyout.getVisibility() == View.VISIBLE) {
2761 mFlyout.animateUpdate(bubble.getFlyoutMessage(),
2762 mStackAnimationController.getStackPosition(), !bubble.showDot(),
2763 bubble.getIconView().getDotCenter(),
2764 mAfterFlyoutHidden /* onHide */);
2765 } else {
2766 mFlyout.setVisibility(INVISIBLE);
2767 mFlyout.setupFlyoutStartingAsDot(bubble.getFlyoutMessage(),
2768 mStackAnimationController.getStackPosition(),
2769 mStackAnimationController.isStackOnLeftSide(),
2770 bubble.getIconView().getDotColor() /* dotColor */,
2771 expandFlyoutAfterDelay /* onLayoutComplete */,
2772 mAfterFlyoutHidden /* onHide */,
2773 bubble.getIconView().getDotCenter(),
2774 !bubble.showDot());
2775 }
2776 mFlyout.bringToFront();
2777 });
2778 mFlyout.removeCallbacks(mHideFlyout);
2779 mFlyout.postDelayed(mHideFlyout, FLYOUT_HIDE_AFTER);
2780 logBubbleEvent(bubble, FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__FLYOUT);
2781 }
2782
2783 /** Hide the flyout immediately and cancel any pending hide runnables. */
2784 private void hideFlyoutImmediate() {
2785 clearFlyoutOnHide();
2786 mFlyout.removeCallbacks(mAnimateInFlyout);
2787 mFlyout.removeCallbacks(mHideFlyout);
2788 mFlyout.hideFlyout();
2789 }
2790
2791 private void clearFlyoutOnHide() {
2792 mFlyout.removeCallbacks(mAnimateInFlyout);
2793 if (mAfterFlyoutHidden == null) {
2794 return;
2795 }
2796 mAfterFlyoutHidden.run();
2797 mAfterFlyoutHidden = null;
2798 }
2799
2800 /**
2801 * Fills the Rect with the touchable region of the bubbles. This will be used by WindowManager
2802 * to decide which touch events go to Bubbles.
2803 *
2804 * Bubbles is below the status bar/notification shade but above application windows. If you're
2805 * trying to get touch events from the status bar or another higher-level window layer, you'll
2806 * need to re-order TYPE_BUBBLES in WindowManagerPolicy so that we have the opportunity to steal
2807 * them.
2808 */
2809 public void getTouchableRegion(Rect outRect) {
2810 if (isStackEduShowing()) {
2811 // When user education shows then capture all touches
2812 outRect.set(0, 0, getWidth(), getHeight());
2813 return;
2814 }
2815
2816 if (!mIsExpanded) {
2817 if (getBubbleCount() > 0 || mBubbleData.isShowingOverflow()) {
2818 mBubbleContainer.getChildAt(0).getBoundsOnScreen(outRect);
2819 // Increase the touch target size of the bubble
2820 outRect.top -= mBubbleTouchPadding;
2821 outRect.left -= mBubbleTouchPadding;
2822 outRect.right += mBubbleTouchPadding;
2823 outRect.bottom += mBubbleTouchPadding;
2824 }
2825 } else {
2826 mBubbleContainer.getBoundsOnScreen(outRect);
2827 // Account for the IME in the touchable region so that the touchable region of the
2828 // Bubble window doesn't obscure the IME. The touchable region affects which areas
2829 // of the screen can be excluded by lower windows (IME is just above the embedded task)
2830 outRect.bottom -= mPositioner.getImeHeight();
2831 }
2832
2833 if (mFlyout.getVisibility() == View.VISIBLE) {
2834 final Rect flyoutBounds = new Rect();
2835 mFlyout.getBoundsOnScreen(flyoutBounds);
2836 outRect.union(flyoutBounds);
2837 }
2838 }
2839
2840 private void requestUpdate() {
2841 if (mViewUpdatedRequested || mIsExpansionAnimating) {
2842 return;
2843 }
2844 mViewUpdatedRequested = true;
2845 getViewTreeObserver().addOnPreDrawListener(mViewUpdater);
2846 invalidate();
2847 }
2848
2849 /** Hide or show the manage menu for the currently expanded bubble. */
2850 @VisibleForTesting
2851 public void showManageMenu(boolean show) {
2852 mShowingManage = show;
2853
2854 // This should not happen, since the manage menu is only visible when there's an expanded
2855 // bubble. If we end up in this state, just hide the menu immediately.
2856 if (mExpandedBubble == null || mExpandedBubble.getExpandedView() == null) {
2857 mManageMenu.setVisibility(View.INVISIBLE);
2858 mManageMenuScrim.setVisibility(INVISIBLE);
2859 mBubbleController.getSysuiProxy().onManageMenuExpandChanged(false /* show */);
2860 return;
2861 }
2862 if (show) {
2863 mManageMenuScrim.setVisibility(VISIBLE);
2864 mManageMenuScrim.setTranslationZ(mManageMenu.getElevation() - 1f);
2865 }
2866 Runnable endAction = () -> {
2867 if (!show) {
2868 mManageMenuScrim.setVisibility(INVISIBLE);
2869 mManageMenuScrim.setTranslationZ(0f);
2870 }
2871 };
2872
2873 mBubbleController.getSysuiProxy().onManageMenuExpandChanged(show);
2874 mManageMenuScrim.animate()
2875 .setInterpolator(show ? ALPHA_IN : ALPHA_OUT)
2876 .alpha(show ? SCRIM_ALPHA : 0f)
2877 .withEndAction(endAction)
2878 .start();
2879
2880 // If available, update the manage menu's settings option with the expanded bubble's app
2881 // name and icon.
2882 if (show) {
2883 final Bubble bubble = mBubbleData.getBubbleInStackWithKey(mExpandedBubble.getKey());
2884 if (bubble != null) {
2885 mManageSettingsIcon.setImageBitmap(bubble.getRawAppBadge());
2886 mManageSettingsText.setText(getResources().getString(
2887 R.string.bubbles_app_settings, bubble.getAppName()));
2888 }
2889 }
2890
2891 if (mExpandedBubble.getExpandedView().getTaskView() != null) {
2892 mExpandedBubble.getExpandedView().getTaskView().setObscuredTouchRect(mShowingManage
2893 ? new Rect(0, 0, getWidth(), getHeight())
2894 : null);
2895 }
2896
2897 final boolean isLtr =
2898 getResources().getConfiguration().getLayoutDirection() == LAYOUT_DIRECTION_LTR;
2899
2900 // When the menu is open, it should be at these coordinates. The menu pops out to the right
2901 // in LTR and to the left in RTL.
2902 mExpandedBubble.getExpandedView().getManageButtonBoundsOnScreen(mTempRect);
2903 final float margin = mExpandedBubble.getExpandedView().getManageButtonMargin();
2904 final float targetX = isLtr
2905 ? mTempRect.left - margin
2906 : mTempRect.right + margin - mManageMenu.getWidth();
2907 final float targetY = mTempRect.bottom - mManageMenu.getHeight();
2908
2909 final float xOffsetForAnimation = (isLtr ? 1 : -1) * mManageMenu.getWidth() / 4f;
2910 if (show) {
2911 mManageMenu.setScaleX(0.5f);
2912 mManageMenu.setScaleY(0.5f);
2913 mManageMenu.setTranslationX(targetX - xOffsetForAnimation);
2914 mManageMenu.setTranslationY(targetY + mManageMenu.getHeight() / 4f);
2915 mManageMenu.setAlpha(0f);
2916
2917 PhysicsAnimator.getInstance(mManageMenu)
2918 .spring(DynamicAnimation.ALPHA, 1f)
2919 .spring(DynamicAnimation.SCALE_X, 1f)
2920 .spring(DynamicAnimation.SCALE_Y, 1f)
2921 .spring(DynamicAnimation.TRANSLATION_X, targetX)
2922 .spring(DynamicAnimation.TRANSLATION_Y, targetY)
2923 .withEndActions(() -> {
2924 View child = mManageMenu.getChildAt(0);
2925 child.requestAccessibilityFocus();
2926 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
2927 // Update the AV's obscured touchable region for the new state.
2928 mExpandedBubble.getExpandedView().updateObscuredTouchableRegion();
2929 }
2930 })
2931 .start();
2932
2933 mManageMenu.setVisibility(View.VISIBLE);
2934 } else {
2935 PhysicsAnimator.getInstance(mManageMenu)
2936 .spring(DynamicAnimation.ALPHA, 0f)
2937 .spring(DynamicAnimation.SCALE_X, 0.5f)
2938 .spring(DynamicAnimation.SCALE_Y, 0.5f)
2939 .spring(DynamicAnimation.TRANSLATION_X, targetX - xOffsetForAnimation)
2940 .spring(DynamicAnimation.TRANSLATION_Y, targetY + mManageMenu.getHeight() / 4f)
2941 .withEndActions(() -> {
2942 mManageMenu.setVisibility(View.INVISIBLE);
2943 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
2944 // Update the AV's obscured touchable region for the new state.
2945 mExpandedBubble.getExpandedView().updateObscuredTouchableRegion();
2946 }
2947 })
2948 .start();
2949 }
2950 }
2951
2952 private void updateExpandedBubble() {
2953 if (DEBUG_BUBBLE_STACK_VIEW) {
2954 Log.d(TAG, "updateExpandedBubble()");
2955 }
2956
2957 mExpandedViewContainer.removeAllViews();
2958 if (mIsExpanded && mExpandedBubble != null
2959 && mExpandedBubble.getExpandedView() != null) {
2960 BubbleExpandedView bev = mExpandedBubble.getExpandedView();
2961 bev.setContentVisibility(false);
2962 bev.setAnimating(!mIsExpansionAnimating);
2963 mExpandedViewContainerMatrix.setScaleX(0f);
2964 mExpandedViewContainerMatrix.setScaleY(0f);
2965 mExpandedViewContainerMatrix.setTranslate(0f, 0f);
2966 mExpandedViewContainer.setVisibility(View.INVISIBLE);
2967 mExpandedViewContainer.setAlpha(0f);
2968 mExpandedViewContainer.addView(bev);
2969
2970 postDelayed(() -> {
2971 // Set the Manage button click handler from postDelayed. This appears to resolve
2972 // a race condition with adding the BubbleExpandedView view to the expanded view
2973 // container. Due to the race condition the click handler sometimes is not set up
2974 // correctly and is never called.
2975 updateManageButtonListener();
2976 }, 0);
2977
2978 if (!mIsExpansionAnimating) {
2979 mIsBubbleSwitchAnimating = true;
2980 mSurfaceSynchronizer.syncSurfaceAndRun(() -> {
2981 post(this::animateSwitchBubbles);
2982 });
2983 }
2984 }
2985 }
2986
2987 private void updateManageButtonListener() {
2988 if (mIsExpanded && mExpandedBubble != null
2989 && mExpandedBubble.getExpandedView() != null) {
2990 BubbleExpandedView bev = mExpandedBubble.getExpandedView();
2991 bev.setManageClickListener((view) -> {
2992 showManageMenu(true /* show */);
2993 });
2994 }
2995 }
2996
2997 /**
2998 * Requests a snapshot from the currently expanded bubble's TaskView and displays it in a
2999 * SurfaceView. This allows us to load a newly expanded bubble's Activity into the TaskView,
3000 * while animating the (screenshot of the) previously selected bubble's content away.
3001 *
3002 * @param onComplete Callback to run once we're done here - called with 'false' if something
3003 * went wrong, or 'true' if the SurfaceView is now showing a screenshot of the
3004 * expanded bubble.
3005 */
3006 private void screenshotAnimatingOutBubbleIntoSurface(Consumer<Boolean> onComplete) {
3007 if (!mIsExpanded || mExpandedBubble == null || mExpandedBubble.getExpandedView() == null) {
3008 // You can't animate null.
3009 onComplete.accept(false);
3010 return;
3011 }
3012
3013 final BubbleExpandedView animatingOutExpandedView = mExpandedBubble.getExpandedView();
3014
3015 // Release the previous screenshot if it hasn't been released already.
3016 if (mAnimatingOutBubbleBuffer != null) {
3017 releaseAnimatingOutBubbleBuffer();
3018 }
3019
3020 try {
3021 mAnimatingOutBubbleBuffer = animatingOutExpandedView.snapshotActivitySurface();
3022 } catch (Exception e) {
3023 // If we fail for any reason, print the stack trace and then notify the callback of our
3024 // failure. This is not expected to occur, but it's not worth crashing over.
3025 Log.wtf(TAG, e);
3026 onComplete.accept(false);
3027 }
3028
3029 if (mAnimatingOutBubbleBuffer == null
3030 || mAnimatingOutBubbleBuffer.getHardwareBuffer() == null) {
3031 // While no exception was thrown, we were unable to get a snapshot.
3032 onComplete.accept(false);
3033 return;
3034 }
3035
3036 // Make sure the surface container's properties have been reset.
3037 PhysicsAnimator.getInstance(mAnimatingOutSurfaceContainer).cancel();
3038 mAnimatingOutSurfaceContainer.setScaleX(1f);
3039 mAnimatingOutSurfaceContainer.setScaleY(1f);
3040 final float translationX = mPositioner.showBubblesVertically() && mStackOnLeftOrWillBe
3041 ? mExpandedViewContainer.getPaddingLeft() + mPositioner.getPointerSize()
3042 : mExpandedViewContainer.getPaddingLeft();
3043 mAnimatingOutSurfaceContainer.setTranslationX(translationX);
3044 mAnimatingOutSurfaceContainer.setTranslationY(0);
3045
3046 final int[] taskViewLocation =
3047 mExpandedBubble.getExpandedView().getTaskViewLocationOnScreen();
3048 final int[] surfaceViewLocation = mAnimatingOutSurfaceView.getLocationOnScreen();
3049
3050 // Translate the surface to overlap the real TaskView.
3051 mAnimatingOutSurfaceContainer.setTranslationY(
3052 taskViewLocation[1] - surfaceViewLocation[1]);
3053
3054 // Set the width/height of the SurfaceView to match the snapshot.
3055 mAnimatingOutSurfaceView.getLayoutParams().width =
3056 mAnimatingOutBubbleBuffer.getHardwareBuffer().getWidth();
3057 mAnimatingOutSurfaceView.getLayoutParams().height =
3058 mAnimatingOutBubbleBuffer.getHardwareBuffer().getHeight();
3059 mAnimatingOutSurfaceView.requestLayout();
3060
3061 // Post to wait for layout.
3062 post(() -> {
3063 // The buffer might have been destroyed if the user is mashing on bubbles, that's okay.
3064 if (mAnimatingOutBubbleBuffer == null
3065 || mAnimatingOutBubbleBuffer.getHardwareBuffer() == null
3066 || mAnimatingOutBubbleBuffer.getHardwareBuffer().isClosed()) {
3067 onComplete.accept(false);
3068 return;
3069 }
3070
3071 if (!mIsExpanded || !mAnimatingOutSurfaceReady) {
3072 onComplete.accept(false);
3073 return;
3074 }
3075
3076 // Attach the buffer! We're now displaying the snapshot.
3077 mAnimatingOutSurfaceView.getHolder().getSurface().attachAndQueueBufferWithColorSpace(
3078 mAnimatingOutBubbleBuffer.getHardwareBuffer(),
3079 mAnimatingOutBubbleBuffer.getColorSpace());
3080
3081 mAnimatingOutSurfaceView.setAlpha(1f);
3082 mExpandedViewContainer.setVisibility(View.GONE);
3083
3084 mSurfaceSynchronizer.syncSurfaceAndRun(() -> {
3085 post(() -> {
3086 onComplete.accept(true);
3087 });
3088 });
3089 });
3090 }
3091
3092 /**
3093 * Releases the buffer containing the screenshot of the animating-out bubble, if it exists and
3094 * isn't yet destroyed.
3095 */
3096 private void releaseAnimatingOutBubbleBuffer() {
3097 if (mAnimatingOutBubbleBuffer != null
3098 && !mAnimatingOutBubbleBuffer.getHardwareBuffer().isClosed()) {
3099 mAnimatingOutBubbleBuffer.getHardwareBuffer().close();
3100 }
3101 }
3102
3103 private void updateExpandedView() {
3104 if (DEBUG_BUBBLE_STACK_VIEW) {
3105 Log.d(TAG, "updateExpandedView: mIsExpanded=" + mIsExpanded);
3106 }
3107 boolean isOverflowExpanded = mExpandedBubble != null
3108 && BubbleOverflow.KEY.equals(mExpandedBubble.getKey());
3109 int[] paddings = mPositioner.getExpandedViewContainerPadding(
3110 mStackAnimationController.isStackOnLeftSide(), isOverflowExpanded);
3111 mExpandedViewContainer.setPadding(paddings[0], paddings[1], paddings[2], paddings[3]);
3112 if (mIsExpansionAnimating) {
3113 mExpandedViewContainer.setVisibility(mIsExpanded ? VISIBLE : GONE);
3114 }
3115 if (mExpandedBubble != null && mExpandedBubble.getExpandedView() != null) {
3116 PointF p = mPositioner.getExpandedBubbleXY(getBubbleIndex(mExpandedBubble),
3117 getState());
3118 mExpandedViewContainer.setTranslationY(mPositioner.getExpandedViewY(mExpandedBubble,
3119 mPositioner.showBubblesVertically() ? p.y : p.x));
3120 mExpandedViewContainer.setTranslationX(0f);
3121 mExpandedBubble.getExpandedView().updateView(
3122 mExpandedViewContainer.getLocationOnScreen());
3123 updatePointerPosition(false /* forIme */);
3124 }
3125
3126 mStackOnLeftOrWillBe = mStackAnimationController.isStackOnLeftSide();
3127 }
3128
3129 /**
3130 * Updates whether each of the bubbles should show shadows. When collapsed & resting, only the
3131 * visible bubbles (top 2) will show a shadow. When the stack is being dragged, everything
3132 * shows a shadow. When an individual bubble is dragged out, it should show a shadow.
3133 */
3134 private void updateBubbleShadows(boolean showForAllBubbles) {
3135 int bubbleCount = getBubbleCount();
3136 for (int i = 0; i < bubbleCount; i++) {
3137 final float z = (mPositioner.getMaxBubbles() * mBubbleElevation) - i;
3138 BadgedImageView bv = (BadgedImageView) mBubbleContainer.getChildAt(i);
3139 boolean isDraggedOut = mMagnetizedObject != null
3140 && mMagnetizedObject.getUnderlyingObject().equals(bv);
3141 if (showForAllBubbles || isDraggedOut) {
3142 bv.setZ(z);
3143 } else {
3144 final float tz = i < NUM_VISIBLE_WHEN_RESTING ? z : 0f;
3145 bv.setZ(tz);
3146 }
3147 }
3148 }
3149
3150 /**
3151 * When the bubbles are flung and then rest, the shadows stack up for the bubbles hidden
3152 * beneath the top two bubbles, to avoid this we animate the Z translations once the stack
3153 * is resting so that they fade away nicely.
3154 */
3155 private void animateShadows() {
3156 int bubbleCount = getBubbleCount();
3157 for (int i = 0; i < bubbleCount; i++) {
3158 BadgedImageView bv = (BadgedImageView) mBubbleContainer.getChildAt(i);
3159 boolean fullShadow = i < NUM_VISIBLE_WHEN_RESTING;
3160 if (!fullShadow) {
3161 bv.animate().translationZ(0).start();
3162 }
3163 }
3164 }
3165
3166 private void updateZOrder() {
3167 int bubbleCount = getBubbleCount();
3168 for (int i = 0; i < bubbleCount; i++) {
3169 BadgedImageView bv = (BadgedImageView) mBubbleContainer.getChildAt(i);
3170 bv.setZ(i < NUM_VISIBLE_WHEN_RESTING
3171 ? (mPositioner.getMaxBubbles() * mBubbleElevation) - i
3172 : 0f);
3173 }
3174 }
3175
3176 private void updateBadges(boolean setBadgeForCollapsedStack) {
3177 int bubbleCount = getBubbleCount();
3178 for (int i = 0; i < bubbleCount; i++) {
3179 BadgedImageView bv = (BadgedImageView) mBubbleContainer.getChildAt(i);
3180 if (mIsExpanded) {
3181 // If we're not displaying vertically, we always show the badge on the left.
3182 boolean onLeft = mPositioner.showBubblesVertically() && !mStackOnLeftOrWillBe;
3183 bv.showDotAndBadge(onLeft);
3184 } else if (setBadgeForCollapsedStack) {
3185 if (i == 0) {
3186 bv.showDotAndBadge(!mStackOnLeftOrWillBe);
3187 } else {
3188 bv.hideDotAndBadge(!mStackOnLeftOrWillBe);
3189 }
3190 }
3191 }
3192 }
3193
3194 /**
3195 * Updates the position of the pointer based on the expanded bubble.
3196 *
3197 * @param forIme whether the position is being updated due to the ime appearing, in this case
3198 * the pointer is animated to the location.
3199 */
3200 private void updatePointerPosition(boolean forIme) {
3201 if (mExpandedBubble == null || mExpandedBubble.getExpandedView() == null) {
3202 return;
3203 }
3204 int index = getBubbleIndex(mExpandedBubble);
3205 if (index == -1) {
3206 return;
3207 }
3208 PointF position = mPositioner.getExpandedBubbleXY(index, getState());
3209 float bubblePosition = mPositioner.showBubblesVertically()
3210 ? position.y
3211 : position.x;
3212 mExpandedBubble.getExpandedView().setPointerPosition(bubblePosition,
3213 mStackOnLeftOrWillBe, forIme /* animate */);
3214 }
3215
3216 /**
3217 * @return the number of bubbles in the stack view.
3218 */
3219 public int getBubbleCount() {
3220 // Subtract 1 for the overflow button that is always in the bubble container.
3221 return mBubbleContainer.getChildCount() - 1;
3222 }
3223
3224 /**
3225 * Finds the bubble index within the stack.
3226 *
3227 * @param provider the bubble view provider with the bubble to look up.
3228 * @return the index of the bubble view within the bubble stack. The range of the position
3229 * is between 0 and the bubble count minus 1.
3230 */
3231 int getBubbleIndex(@Nullable BubbleViewProvider provider) {
3232 if (provider == null) {
3233 return 0;
3234 }
3235 return mBubbleContainer.indexOfChild(provider.getIconView());
3236 }
3237
3238 /**
3239 * @return the normalized x-axis position of the bubble stack rounded to 4 decimal places.
3240 */
3241 public float getNormalizedXPosition() {
3242 return new BigDecimal(getStackPosition().x / mPositioner.getAvailableRect().width())
3243 .setScale(4, RoundingMode.CEILING.HALF_UP)
3244 .floatValue();
3245 }
3246
3247 /**
3248 * @return the normalized y-axis position of the bubble stack rounded to 4 decimal places.
3249 */
3250 public float getNormalizedYPosition() {
3251 return new BigDecimal(getStackPosition().y / mPositioner.getAvailableRect().height())
3252 .setScale(4, RoundingMode.CEILING.HALF_UP)
3253 .floatValue();
3254 }
3255
3256 /** @return the position of the bubble stack. */
3257 public PointF getStackPosition() {
3258 return mStackAnimationController.getStackPosition();
3259 }
3260
3261 /**
3262 * Logs the bubble UI event.
3263 *
3264 * @param provider the bubble view provider that is being interacted on. Null value indicates
3265 * that the user interaction is not specific to one bubble.
3266 * @param action the user interaction enum.
3267 */
3268 private void logBubbleEvent(@Nullable BubbleViewProvider provider, int action) {
3269 final String packageName =
3270 (provider != null && provider instanceof Bubble)
3271 ? ((Bubble) provider).getPackageName()
3272 : "null";
3273 mBubbleData.logBubbleEvent(provider,
3274 action,
3275 packageName,
3276 getBubbleCount(),
3277 getBubbleIndex(provider),
3278 getNormalizedXPosition(),
3279 getNormalizedYPosition());
3280 }
3281
3282 /** For debugging only */
3283 List<Bubble> getBubblesOnScreen() {
3284 List<Bubble> bubbles = new ArrayList<>();
3285 for (int i = 0; i < getBubbleCount(); i++) {
3286 View child = mBubbleContainer.getChildAt(i);
3287 if (child instanceof BadgedImageView) {
3288 String key = ((BadgedImageView) child).getKey();
3289 Bubble bubble = mBubbleData.getBubbleInStackWithKey(key);
3290 bubbles.add(bubble);
3291 }
3292 }
3293 return bubbles;
3294 }
3295
3296 /** @return the current stack state. */
3297 public StackViewState getState() {
3298 mStackViewState.numberOfBubbles = mBubbleContainer.getChildCount();
3299 mStackViewState.selectedIndex = getBubbleIndex(mExpandedBubble);
3300 mStackViewState.onLeft = mStackOnLeftOrWillBe;
3301 return mStackViewState;
3302 }
3303
3304 /**
3305 * Handles vertical offset changes, e.g. when one handed mode is switched on/off.
3306 *
3307 * @param offset new vertical offset.
3308 */
3309 void onVerticalOffsetChanged(int offset) {
3310 // adjust dismiss view vertical position, so that it is still visible to the user
3311 mDismissView.setPadding(/* left = */ 0, /* top = */ 0, /* right = */ 0, offset);
3312 }
3313
3314 /**
3315 * Holds some commonly queried information about the stack.
3316 */
3317 public static class StackViewState {
3318 // Number of bubbles (including the overflow itself) in the stack.
3319 public int numberOfBubbles;
3320 // The selected index if the stack is expanded.
3321 public int selectedIndex;
3322 // Whether the stack is resting on the left or right side of the screen when collapsed.
3323 public boolean onLeft;
3324 }
3325
3326 /**
3327 * Representation of stack position that uses relative properties rather than absolute
3328 * coordinates. This is used to maintain similar stack positions across configuration changes.
3329 */
3330 public static class RelativeStackPosition {
3331 /** Whether to place the stack at the leftmost allowed position. */
3332 private boolean mOnLeft;
3333
3334 /**
3335 * How far down the vertically allowed region to place the stack. For example, if the stack
3336 * allowed region is between y = 100 and y = 1100 and this is 0.2f, we'll place the stack at
3337 * 100 + (0.2f * 1000) = 300.
3338 */
3339 private float mVerticalOffsetPercent;
3340
3341 public RelativeStackPosition(boolean onLeft, float verticalOffsetPercent) {
3342 mOnLeft = onLeft;
3343 mVerticalOffsetPercent = clampVerticalOffsetPercent(verticalOffsetPercent);
3344 }
3345
3346 /** Constructs a relative position given a region and a point in that region. */
3347 public RelativeStackPosition(PointF position, RectF region) {
3348 mOnLeft = position.x < region.width() / 2;
3349 mVerticalOffsetPercent =
3350 clampVerticalOffsetPercent((position.y - region.top) / region.height());
3351 }
3352
3353 /** Ensures that the offset percent is between 0f and 1f. */
3354 private float clampVerticalOffsetPercent(float offsetPercent) {
3355 return Math.max(0f, Math.min(1f, offsetPercent));
3356 }
3357
3358 /**
3359 * Given an allowable stack position region, returns the point within that region
3360 * represented by this relative position.
3361 */
3362 public PointF getAbsolutePositionInRegion(RectF region) {
3363 return new PointF(
3364 mOnLeft ? region.left : region.right,
3365 region.top + mVerticalOffsetPercent * region.height());
3366 }
3367 }
3368 }