huangcm
2025-04-11 48566d1cda2d109a94496c806286f47b8984166d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.android.systemui.bubbles;
 
import static android.graphics.Paint.ANTI_ALIAS_FLAG;
import static android.graphics.Paint.FILTER_BITMAP_FLAG;
 
import android.animation.ArgbEvaluator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.ShapeDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.FrameLayout;
import android.widget.TextView;
 
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.SpringAnimation;
 
import com.android.systemui.R;
import com.android.systemui.recents.TriangleShape;
 
/**
 * Flyout view that appears as a 'chat bubble' alongside the bubble stack. The flyout can visually
 * transform into the 'new' dot, which is used during flyout dismiss animations/gestures.
 */
public class BubbleFlyoutView extends FrameLayout {
    /** Max width of the flyout, in terms of percent of the screen width. */
    private static final float FLYOUT_MAX_WIDTH_PERCENT = .6f;
 
    private final int mFlyoutPadding;
    private final int mFlyoutSpaceFromBubble;
    private final int mPointerSize;
    private final int mBubbleSize;
    private final int mFlyoutElevation;
    private final int mBubbleElevation;
    private final int mFloatingBackgroundColor;
    private final float mCornerRadius;
 
    private final ViewGroup mFlyoutTextContainer;
    private final TextView mFlyoutText;
    /** Spring animation for the flyout. */
    private final SpringAnimation mFlyoutSpring =
            new SpringAnimation(this, DynamicAnimation.TRANSLATION_X);
 
    /** Values related to the 'new' dot which we use to figure out where to collapse the flyout. */
    private final float mNewDotRadius;
    private final float mNewDotSize;
    private final float mNewDotOffsetFromBubbleBounds;
 
    /**
     * The paint used to draw the background, whose color changes as the flyout transitions to the
     * tinted 'new' dot.
     */
    private final Paint mBgPaint = new Paint(ANTI_ALIAS_FLAG | FILTER_BITMAP_FLAG);
    private final ArgbEvaluator mArgbEvaluator = new ArgbEvaluator();
 
    /**
     * Triangular ShapeDrawables used for the triangle that points from the flyout to the bubble
     * stack (a chat-bubble effect).
     */
    private final ShapeDrawable mLeftTriangleShape;
    private final ShapeDrawable mRightTriangleShape;
 
    /** Whether the flyout arrow is on the left (pointing left) or right (pointing right). */
    private boolean mArrowPointingLeft = true;
 
    /** Color of the 'new' dot that the flyout will transform into. */
    private int mDotColor;
 
    /** The outline of the triangle, used for elevation shadows. */
    private final Outline mTriangleOutline = new Outline();
 
    /** The bounds of the flyout background, kept up to date as it transitions to the 'new' dot. */
    private final RectF mBgRect = new RectF();
 
    /**
     * Percent progress in the transition from flyout to 'new' dot. These two values are the inverse
     * of each other (if we're 40% transitioned to the dot, we're 60% flyout), but it makes the code
     * much more readable.
     */
    private float mPercentTransitionedToDot = 1f;
    private float mPercentStillFlyout = 0f;
 
    /**
     * The difference in values between the flyout and the dot. These differences are gradually
     * added over the course of the animation to transform the flyout into the 'new' dot.
     */
    private float mFlyoutToDotWidthDelta = 0f;
    private float mFlyoutToDotHeightDelta = 0f;
    private float mFlyoutToDotCornerRadiusDelta;
 
    /** The translation values when the flyout is completely transitioned into the dot. */
    private float mTranslationXWhenDot = 0f;
    private float mTranslationYWhenDot = 0f;
 
    /**
     * The current translation values applied to the flyout background as it transitions into the
     * 'new' dot.
     */
    private float mBgTranslationX;
    private float mBgTranslationY;
 
    /** The flyout's X translation when at rest (not animating or dragging). */
    private float mRestingTranslationX = 0f;
 
    /** Callback to run when the flyout is hidden. */
    private Runnable mOnHide;
 
    public BubbleFlyoutView(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.bubble_flyout, this, true);
 
        mFlyoutTextContainer = findViewById(R.id.bubble_flyout_text_container);
        mFlyoutText = mFlyoutTextContainer.findViewById(R.id.bubble_flyout_text);
 
        final Resources res = getResources();
        mFlyoutPadding = res.getDimensionPixelSize(R.dimen.bubble_flyout_padding_x);
        mFlyoutSpaceFromBubble = res.getDimensionPixelSize(R.dimen.bubble_flyout_space_from_bubble);
        mPointerSize = res.getDimensionPixelSize(R.dimen.bubble_flyout_pointer_size);
        mBubbleSize = res.getDimensionPixelSize(R.dimen.individual_bubble_size);
        mBubbleElevation = res.getDimensionPixelSize(R.dimen.bubble_elevation);
        mFlyoutElevation = res.getDimensionPixelSize(R.dimen.bubble_flyout_elevation);
        mNewDotOffsetFromBubbleBounds = BadgeRenderer.getDotCenterOffset(context);
        mNewDotRadius = BadgeRenderer.getDotRadius(mNewDotOffsetFromBubbleBounds);
        mNewDotSize = mNewDotRadius * 2f;
 
        final TypedArray ta = mContext.obtainStyledAttributes(
                new int[] {
                        android.R.attr.colorBackgroundFloating,
                        android.R.attr.dialogCornerRadius});
        mFloatingBackgroundColor = ta.getColor(0, Color.WHITE);
        mCornerRadius = ta.getDimensionPixelSize(1, 0);
        mFlyoutToDotCornerRadiusDelta = mNewDotRadius - mCornerRadius;
        ta.recycle();
 
        // Add padding for the pointer on either side, onDraw will draw it in this space.
        setPadding(mPointerSize, 0, mPointerSize, 0);
        setWillNotDraw(false);
        setClipChildren(false);
        setTranslationZ(mFlyoutElevation);
        setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                BubbleFlyoutView.this.getOutline(outline);
            }
        });
 
        mBgPaint.setColor(mFloatingBackgroundColor);
 
        mLeftTriangleShape =
                new ShapeDrawable(TriangleShape.createHorizontal(
                        mPointerSize, mPointerSize, true /* isPointingLeft */));
        mLeftTriangleShape.setBounds(0, 0, mPointerSize, mPointerSize);
        mLeftTriangleShape.getPaint().setColor(mFloatingBackgroundColor);
 
        mRightTriangleShape =
                new ShapeDrawable(TriangleShape.createHorizontal(
                        mPointerSize, mPointerSize, false /* isPointingLeft */));
        mRightTriangleShape.setBounds(0, 0, mPointerSize, mPointerSize);
        mRightTriangleShape.getPaint().setColor(mFloatingBackgroundColor);
    }
 
    @Override
    protected void onDraw(Canvas canvas) {
        renderBackground(canvas);
        invalidateOutline();
        super.onDraw(canvas);
    }
 
    /** Configures the flyout and animates it in. */
    void showFlyout(
            CharSequence updateMessage, PointF stackPos, float parentWidth,
            boolean arrowPointingLeft, int dotColor, Runnable onHide) {
        mArrowPointingLeft = arrowPointingLeft;
        mDotColor = dotColor;
        mOnHide = onHide;
 
        setCollapsePercent(0f);
        setAlpha(0f);
        setVisibility(VISIBLE);
 
        // Set the flyout TextView's max width in terms of percent, and then subtract out the
        // padding so that the entire flyout view will be the desired width (rather than the
        // TextView being the desired width + extra padding).
        mFlyoutText.setMaxWidth(
                (int) (parentWidth * FLYOUT_MAX_WIDTH_PERCENT) - mFlyoutPadding * 2);
        mFlyoutText.setText(updateMessage);
 
        // Wait for the TextView to lay out so we know its line count.
        post(() -> {
            // Multi line flyouts get top-aligned to the bubble.
            if (mFlyoutText.getLineCount() > 1) {
                setTranslationY(stackPos.y);
            } else {
                // Single line flyouts are vertically centered with respect to the bubble.
                setTranslationY(
                        stackPos.y + (mBubbleSize - mFlyoutTextContainer.getHeight()) / 2f);
            }
 
            // Calculate the translation required to position the flyout next to the bubble stack,
            // with the desired padding.
            mRestingTranslationX = mArrowPointingLeft
                    ? stackPos.x + mBubbleSize + mFlyoutSpaceFromBubble
                    : stackPos.x - getWidth() - mFlyoutSpaceFromBubble;
 
            // Translate towards the stack slightly.
            setTranslationX(
                    mRestingTranslationX + (arrowPointingLeft ? -mBubbleSize : mBubbleSize));
 
            // Fade in the entire flyout and spring it to its normal position.
            animate().alpha(1f);
            mFlyoutSpring.animateToFinalPosition(mRestingTranslationX);
 
            // Calculate the difference in size between the flyout and the 'dot' so that we can
            // transform into the dot later.
            mFlyoutToDotWidthDelta = getWidth() - mNewDotSize;
            mFlyoutToDotHeightDelta = getHeight() - mNewDotSize;
 
            // Calculate the translation values needed to be in the correct 'new dot' position.
            final float distanceFromFlyoutLeftToDotCenterX =
                    mFlyoutSpaceFromBubble + mNewDotOffsetFromBubbleBounds / 2;
            if (mArrowPointingLeft) {
                mTranslationXWhenDot = -distanceFromFlyoutLeftToDotCenterX - mNewDotRadius;
            } else {
                mTranslationXWhenDot =
                        getWidth() + distanceFromFlyoutLeftToDotCenterX - mNewDotRadius;
            }
 
            mTranslationYWhenDot =
                    getHeight() / 2f
                            - mNewDotRadius
                            - mBubbleSize / 2f
                            + mNewDotOffsetFromBubbleBounds / 2;
        });
    }
 
    /**
     * Hides the flyout and runs the optional callback passed into showFlyout. The flyout has been
     * animated into the 'new' dot by the time we call this, so no animations are needed.
     */
    void hideFlyout() {
        if (mOnHide != null) {
            mOnHide.run();
            mOnHide = null;
        }
 
        setVisibility(GONE);
    }
 
    /** Sets the percentage that the flyout should be collapsed into dot form. */
    void setCollapsePercent(float percentCollapsed) {
        mPercentTransitionedToDot = Math.max(0f, Math.min(percentCollapsed, 1f));
        mPercentStillFlyout = (1f - mPercentTransitionedToDot);
 
        // Move and fade out the text.
        mFlyoutText.setTranslationX(
                (mArrowPointingLeft ? -getWidth() : getWidth()) * mPercentTransitionedToDot);
        mFlyoutText.setAlpha(clampPercentage(
                (mPercentStillFlyout - (1f - BubbleStackView.FLYOUT_DRAG_PERCENT_DISMISS))
                        / BubbleStackView.FLYOUT_DRAG_PERCENT_DISMISS));
 
        // Reduce the elevation towards that of the topmost bubble.
        setTranslationZ(
                mFlyoutElevation
                        - (mFlyoutElevation - mBubbleElevation) * mPercentTransitionedToDot);
        invalidate();
    }
 
    /** Return the flyout's resting X translation (translation when not dragging or animating). */
    float getRestingTranslationX() {
        return mRestingTranslationX;
    }
 
    /** Clamps a float to between 0 and 1. */
    private float clampPercentage(float percent) {
        return Math.min(1f, Math.max(0f, percent));
    }
 
    /**
     * Renders the background, which is either the rounded 'chat bubble' flyout, or some state
     * between that and the 'new' dot over the bubbles.
     */
    private void renderBackground(Canvas canvas) {
        // Calculate the width, height, and corner radius of the flyout given the current collapsed
        // percentage.
        final float width = getWidth() - (mFlyoutToDotWidthDelta * mPercentTransitionedToDot);
        final float height = getHeight() - (mFlyoutToDotHeightDelta * mPercentTransitionedToDot);
        final float cornerRadius = mCornerRadius
                - (mFlyoutToDotCornerRadiusDelta * mPercentTransitionedToDot);
 
        // Translate the flyout background towards the collapsed 'dot' state.
        mBgTranslationX = mTranslationXWhenDot * mPercentTransitionedToDot;
        mBgTranslationY = mTranslationYWhenDot * mPercentTransitionedToDot;
 
        // Set the bounds of the rounded rectangle that serves as either the flyout background or
        // the collapsed 'dot'. These bounds will also be used to provide the outline for elevation
        // shadows. In the expanded flyout state, the left and right bounds leave space for the
        // pointer triangle - as the flyout collapses, this space is reduced since the triangle
        // retracts into the flyout.
        mBgRect.set(
                mPointerSize * mPercentStillFlyout /* left */,
                0 /* top */,
                width - mPointerSize * mPercentStillFlyout /* right */,
                height /* bottom */);
 
        mBgPaint.setColor(
                (int) mArgbEvaluator.evaluate(
                        mPercentTransitionedToDot, mFloatingBackgroundColor, mDotColor));
 
        canvas.save();
        canvas.translate(mBgTranslationX, mBgTranslationY);
        renderPointerTriangle(canvas, width, height);
        canvas.drawRoundRect(mBgRect, cornerRadius, cornerRadius, mBgPaint);
        canvas.restore();
    }
 
    /** Renders the 'pointer' triangle that points from the flyout to the bubble stack. */
    private void renderPointerTriangle(
            Canvas canvas, float currentFlyoutWidth, float currentFlyoutHeight) {
        canvas.save();
 
        // Translation to apply for the 'retraction' effect as the flyout collapses.
        final float retractionTranslationX =
                (mArrowPointingLeft ? 1 : -1) * (mPercentTransitionedToDot * mPointerSize * 2f);
 
        // Place the arrow either at the left side, or the far right, depending on whether the
        // flyout is on the left or right side.
        final float arrowTranslationX =
                mArrowPointingLeft
                        ? retractionTranslationX
                        : currentFlyoutWidth - mPointerSize + retractionTranslationX;
 
        // Vertically center the arrow at all times.
        final float arrowTranslationY = currentFlyoutHeight / 2f - mPointerSize / 2f;
 
        // Draw the appropriate direction of arrow.
        final ShapeDrawable relevantTriangle =
                mArrowPointingLeft ? mLeftTriangleShape : mRightTriangleShape;
        canvas.translate(arrowTranslationX, arrowTranslationY);
        relevantTriangle.setAlpha((int) (255f * mPercentStillFlyout));
        relevantTriangle.draw(canvas);
 
        // Save the triangle's outline for use in the outline provider, offsetting it to reflect its
        // current position.
        relevantTriangle.getOutline(mTriangleOutline);
        mTriangleOutline.offset((int) arrowTranslationX, (int) arrowTranslationY);
 
        canvas.restore();
    }
 
    /** Builds an outline that includes the transformed flyout background and triangle. */
    private void getOutline(Outline outline) {
        if (!mTriangleOutline.isEmpty()) {
            // Draw the rect into the outline as a path so we can merge the triangle path into it.
            final Path rectPath = new Path();
            rectPath.addRoundRect(mBgRect, mCornerRadius, mCornerRadius, Path.Direction.CW);
            outline.setConvexPath(rectPath);
 
            // Get rid of the triangle path once it has disappeared behind the flyout.
            if (mPercentStillFlyout > 0.5f) {
                outline.mPath.addPath(mTriangleOutline.mPath);
            }
 
            // Translate the outline to match the background's position.
            final Matrix outlineMatrix = new Matrix();
            outlineMatrix.postTranslate(getLeft() + mBgTranslationX, getTop() + mBgTranslationY);
 
            // At the very end, retract the outline into the bubble so the shadow will be pulled
            // into the flyout-dot as it (visually) becomes part of the bubble. We can't do this by
            // animating translationZ to zero since then it'll go under the bubbles, which have
            // elevation.
            if (mPercentTransitionedToDot > 0.98f) {
                final float percentBetween99and100 = (mPercentTransitionedToDot - 0.98f) / .02f;
                final float percentShadowVisible = 1f - percentBetween99and100;
 
                // Keep it centered.
                outlineMatrix.postTranslate(
                        mNewDotRadius * percentBetween99and100,
                        mNewDotRadius * percentBetween99and100);
                outlineMatrix.preScale(percentShadowVisible, percentShadowVisible);
            }
 
            outline.mPath.transform(outlineMatrix);
        }
    }
}