Debian Codegraph @

core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.service.selectiontoolbar;
18
19 import android.animation.Animator;
20 import android.animation.AnimatorListenerAdapter;
21 import android.animation.AnimatorSet;
22 import android.animation.ObjectAnimator;
23 import android.animation.ValueAnimator;
24 import android.content.Context;
25 import android.graphics.Point;
26 import android.graphics.Rect;
27 import android.graphics.drawable.AnimatedVectorDrawable;
28 import android.graphics.drawable.Drawable;
29 import android.os.IBinder;
30 import android.text.TextUtils;
31 import android.util.Log;
32 import android.util.Size;
33 import android.view.ContextThemeWrapper;
34 import android.view.Gravity;
35 import android.view.LayoutInflater;
36 import android.view.MotionEvent;
37 import android.view.SurfaceControlViewHost;
38 import android.view.View;
39 import android.view.ViewConfiguration;
40 import android.view.ViewGroup;
41 import android.view.animation.Animation;
42 import android.view.animation.AnimationSet;
43 import android.view.animation.AnimationUtils;
44 import android.view.animation.Interpolator;
45 import android.view.animation.Transformation;
46 import android.view.selectiontoolbar.ShowInfo;
47 import android.view.selectiontoolbar.ToolbarMenuItem;
48 import android.view.selectiontoolbar.WidgetInfo;
49 import android.widget.ArrayAdapter;
50 import android.widget.ImageButton;
51 import android.widget.ImageView;
52 import android.widget.LinearLayout;
53 import android.widget.ListView;
54 import android.widget.TextView;
55
56 import com.android.internal.R;
57 import com.android.internal.util.Preconditions;
58 import com.android.internal.widget.floatingtoolbar.FloatingToolbar;
59
60 import java.io.PrintWriter;
61 import java.util.LinkedList;
62 import java.util.List;
63 import java.util.Objects;
64
65 /**
66 * This class is responsible for rendering/animation of the selection toolbar in the remote
67 * system process. It holds 2 panels (i.e. main panel and overflow panel) and an overflow
68 * button to transition between panels.
69 *
70 * @hide
71 */
72 // TODO(b/215497659): share code with LocalFloatingToolbarPopup
73 final class RemoteSelectionToolbar {
74 private static final String TAG = "RemoteSelectionToolbar";
75
76 /* Minimum and maximum number of items allowed in the overflow. */
77 private static final int MIN_OVERFLOW_SIZE = 2;
78 private static final int MAX_OVERFLOW_SIZE = 4;
79
80 private final Context mContext;
81
82 /* Margins between the popup window and its content. */
83 private final int mMarginHorizontal;
84 private final int mMarginVertical;
85
86 /* View components */
87 private final ViewGroup mContentContainer; // holds all contents.
88 private final ViewGroup mMainPanel; // holds menu items that are initially displayed.
89 // holds menu items hidden in the overflow.
90 private final OverflowPanel mOverflowPanel;
91 private final ImageButton mOverflowButton; // opens/closes the overflow.
92 /* overflow button drawables. */
93 private final Drawable mArrow;
94 private final Drawable mOverflow;
95 private final AnimatedVectorDrawable mToArrow;
96 private final AnimatedVectorDrawable mToOverflow;
97
98 private final OverflowPanelViewHelper mOverflowPanelViewHelper;
99
100 /* Animation interpolators. */
101 private final Interpolator mLogAccelerateInterpolator;
102 private final Interpolator mFastOutSlowInInterpolator;
103 private final Interpolator mLinearOutSlowInInterpolator;
104 private final Interpolator mFastOutLinearInInterpolator;
105
106 /* Animations. */
107 private final AnimatorSet mShowAnimation;
108 private final AnimatorSet mDismissAnimation;
109 private final AnimatorSet mHideAnimation;
110 private final AnimationSet mOpenOverflowAnimation;
111 private final AnimationSet mCloseOverflowAnimation;
112 private final Animation.AnimationListener mOverflowAnimationListener;
113
114 private final Rect mViewPortOnScreen = new Rect(); // portion of screen we can draw in.
115
116 private final int mLineHeight;
117 private final int mIconTextSpacing;
118
119 private final long mSelectionToolbarToken;
120 private IBinder mHostInputToken;
121 private final SelectionToolbarRenderService.RemoteCallbackWrapper mCallbackWrapper;
122 private final SelectionToolbarRenderService.TransferTouchListener mTransferTouchListener;
123 private int mPopupWidth;
124 private int mPopupHeight;
125 // Coordinates to show the toolbar relative to the specified view port
126 private final Point mRelativeCoordsForToolbar = new Point();
127 private List<ToolbarMenuItem> mMenuItems;
128 private SurfaceControlViewHost mSurfaceControlViewHost;
129 private SurfaceControlViewHost.SurfacePackage mSurfacePackage;
130
131 /**
132 * @see OverflowPanelViewHelper#preparePopupContent().
133 */
134 private final Runnable mPreparePopupContentRTLHelper = new Runnable() {
135 @Override
136 public void run() {
137 setPanelsStatesAtRestingPosition();
138 mContentContainer.setAlpha(1);
139 }
140 };
141
142 private boolean mDismissed = true; // tracks whether this popup is dismissed or dismissing.
143 private boolean mHidden; // tracks whether this popup is hidden or hiding.
144
145 /* Calculated sizes for panels and overflow button. */
146 private final Size mOverflowButtonSize;
147 private Size mOverflowPanelSize; // Should be null when there is no overflow.
148 private Size mMainPanelSize;
149
150 /* Menu items and click listeners */
151 private final View.OnClickListener mMenuItemButtonOnClickListener;
152
153 private boolean mOpenOverflowUpwards; // Whether the overflow opens upwards or downwards.
154 private boolean mIsOverflowOpen;
155
156 private int mTransitionDurationScale; // Used to scale the toolbar transition duration.
157
158 private final Rect mPreviousContentRect = new Rect();
159
160 private final Rect mTempContentRect = new Rect();
161 private final Rect mTempContentRectForRoot = new Rect();
162 private final int[] mTempCoords = new int[2];
163
164 RemoteSelectionToolbar(Context context, long selectionToolbarToken, ShowInfo showInfo,
165 SelectionToolbarRenderService.RemoteCallbackWrapper callbackWrapper,
166 SelectionToolbarRenderService.TransferTouchListener transferTouchListener) {
167 mContext = applyDefaultTheme(context, showInfo.isIsLightTheme());
168 mSelectionToolbarToken = selectionToolbarToken;
169 mCallbackWrapper = callbackWrapper;
170 mTransferTouchListener = transferTouchListener;
171 mHostInputToken = showInfo.getHostInputToken();
172 mContentContainer = createContentContainer(mContext);
173 mMarginHorizontal = mContext.getResources()
174 .getDimensionPixelSize(R.dimen.floating_toolbar_horizontal_margin);
175 mMarginVertical = mContext.getResources()
176 .getDimensionPixelSize(R.dimen.floating_toolbar_vertical_margin);
177 mLineHeight = mContext.getResources()
178 .getDimensionPixelSize(R.dimen.floating_toolbar_height);
179 mIconTextSpacing = mContext.getResources()
180 .getDimensionPixelSize(R.dimen.floating_toolbar_icon_text_spacing);
181
182 // Interpolators
183 mLogAccelerateInterpolator = new LogAccelerateInterpolator();
184 mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(
185 mContext, android.R.interpolator.fast_out_slow_in);
186 mLinearOutSlowInInterpolator = AnimationUtils.loadInterpolator(
187 mContext, android.R.interpolator.linear_out_slow_in);
188 mFastOutLinearInInterpolator = AnimationUtils.loadInterpolator(
189 mContext, android.R.interpolator.fast_out_linear_in);
190
191 // Drawables. Needed for views.
192 mArrow = mContext.getResources()
193 .getDrawable(R.drawable.ft_avd_tooverflow, mContext.getTheme());
194 mArrow.setAutoMirrored(true);
195 mOverflow = mContext.getResources()
196 .getDrawable(R.drawable.ft_avd_toarrow, mContext.getTheme());
197 mOverflow.setAutoMirrored(true);
198 mToArrow = (AnimatedVectorDrawable) mContext.getResources()
199 .getDrawable(R.drawable.ft_avd_toarrow_animation, mContext.getTheme());
200 mToArrow.setAutoMirrored(true);
201 mToOverflow = (AnimatedVectorDrawable) mContext.getResources()
202 .getDrawable(R.drawable.ft_avd_tooverflow_animation, mContext.getTheme());
203 mToOverflow.setAutoMirrored(true);
204
205 // Views
206 mOverflowButton = createOverflowButton();
207 mOverflowButtonSize = measure(mOverflowButton);
208 mMainPanel = createMainPanel();
209 mOverflowPanelViewHelper = new OverflowPanelViewHelper(mContext, mIconTextSpacing);
210 mOverflowPanel = createOverflowPanel();
211
212 // Animation. Need views.
213 mOverflowAnimationListener = createOverflowAnimationListener();
214 mOpenOverflowAnimation = new AnimationSet(true);
215 mOpenOverflowAnimation.setAnimationListener(mOverflowAnimationListener);
216 mCloseOverflowAnimation = new AnimationSet(true);
217 mCloseOverflowAnimation.setAnimationListener(mOverflowAnimationListener);
218 mShowAnimation = createEnterAnimation(mContentContainer,
219 new AnimatorListenerAdapter() {
220 @Override
221 public void onAnimationEnd(Animator animation) {
222 updateFloatingToolbarRootContentRect();
223 }
224 });
225 mDismissAnimation = createExitAnimation(
226 mContentContainer,
227 150, // startDelay
228 new AnimatorListenerAdapter() {
229 @Override
230 public void onAnimationEnd(Animator animation) {
231 // TODO(b/215497659): should dismiss window after animation
232 mContentContainer.removeAllViews();
233 mSurfaceControlViewHost.release();
234 mSurfaceControlViewHost = null;
235 mSurfacePackage = null;
236 }
237 });
238 mHideAnimation = createExitAnimation(
239 mContentContainer,
240 0, // startDelay
241 null); // TODO(b/215497659): should handle hide after animation
242 mMenuItemButtonOnClickListener = v -> {
243 Object tag = v.getTag();
244 if (!(tag instanceof ToolbarMenuItem)) {
245 return;
246 }
247 mCallbackWrapper.onMenuItemClicked((ToolbarMenuItem) tag);
248 };
249 }
250
251 private void updateFloatingToolbarRootContentRect() {
252 if (mSurfaceControlViewHost == null) {
253 return;
254 }
255 final FloatingToolbarRoot root = (FloatingToolbarRoot) mSurfaceControlViewHost.getView();
256 mContentContainer.getLocationOnScreen(mTempCoords);
257 int contentLeft = mTempCoords[0];
258 int contentTop = mTempCoords[1];
259 mTempContentRectForRoot.set(contentLeft, contentTop,
260 contentLeft + mContentContainer.getWidth(),
261 contentTop + mContentContainer.getHeight());
262 root.setContentRect(mTempContentRectForRoot);
263 }
264
265 private WidgetInfo createWidgetInfo() {
266 mTempContentRect.set(mRelativeCoordsForToolbar.x, mRelativeCoordsForToolbar.y,
267 mRelativeCoordsForToolbar.x + mPopupWidth,
268 mRelativeCoordsForToolbar.y + mPopupHeight);
269 return new WidgetInfo(mSelectionToolbarToken, mTempContentRect, getSurfacePackage());
270 }
271
272 private SurfaceControlViewHost.SurfacePackage getSurfacePackage() {
273 if (mSurfaceControlViewHost == null) {
274 final FloatingToolbarRoot contentHolder = new FloatingToolbarRoot(mContext,
275 mHostInputToken, mTransferTouchListener);
276 contentHolder.addView(mContentContainer);
277 mSurfaceControlViewHost = new SurfaceControlViewHost(mContext, mContext.getDisplay(),
278 mHostInputToken);
279 mSurfaceControlViewHost.setView(contentHolder, mPopupWidth, mPopupHeight);
280 }
281 if (mSurfacePackage == null) {
282 mSurfacePackage = mSurfaceControlViewHost.getSurfacePackage();
283 }
284 return mSurfacePackage;
285 }
286
287 private void layoutMenuItems(
288 List<ToolbarMenuItem> menuItems,
289 int suggestedWidth) {
290 cancelOverflowAnimations();
291 clearPanels();
292
293 menuItems = layoutMainPanelItems(menuItems, getAdjustedToolbarWidth(suggestedWidth));
294 if (!menuItems.isEmpty()) {
295 // Add remaining items to the overflow.
296 layoutOverflowPanelItems(menuItems);
297 }
298 updatePopupSize();
299 }
300
301 public void onToolbarShowTimeout() {
302 mCallbackWrapper.onToolbarShowTimeout();
303 }
304
305 /**
306 * Show the specified selection toolbar.
307 */
308 public void show(ShowInfo showInfo) {
309 debugLog("show() for " + showInfo);
310
311 mMenuItems = showInfo.getMenuItems();
312 mViewPortOnScreen.set(showInfo.getViewPortOnScreen());
313
314 debugLog("show(): layoutRequired=" + showInfo.isLayoutRequired());
315 if (showInfo.isLayoutRequired()) {
316 layoutMenuItems(mMenuItems, showInfo.getSuggestedWidth());
317 }
318 Rect contentRect = showInfo.getContentRect();
319 if (!isShowing()) {
320 show(contentRect);
321 } else if (!mPreviousContentRect.equals(contentRect)) {
322 updateCoordinates(contentRect);
323 }
324 mPreviousContentRect.set(contentRect);
325 }
326
327 private void show(Rect contentRectOnScreen) {
328 Objects.requireNonNull(contentRectOnScreen);
329
330 mHidden = false;
331 mDismissed = false;
332 cancelDismissAndHideAnimations();
333 cancelOverflowAnimations();
334 refreshCoordinatesAndOverflowDirection(contentRectOnScreen);
335 preparePopupContent();
336 mCallbackWrapper.onShown(createWidgetInfo());
337 // TODO(b/215681595): Use Choreographer to coordinate for show between different thread
338 mShowAnimation.start();
339 }
340
341 /**
342 * Dismiss the specified selection toolbar.
343 */
344 public void dismiss(long floatingToolbarToken) {
345 debugLog("dismiss for " + floatingToolbarToken);
346 if (mDismissed) {
347 return;
348 }
349 mHidden = false;
350 mDismissed = true;
351
352 mHideAnimation.cancel();
353 mDismissAnimation.start();
354 }
355
356 /**
357 * Hide the specified selection toolbar.
358 */
359 public void hide(long floatingToolbarToken) {
360 debugLog("hide for " + floatingToolbarToken);
361 if (!isShowing()) {
362 return;
363 }
364
365 mHidden = true;
366 mHideAnimation.start();
367 }
368
369 public boolean isShowing() {
370 return !mDismissed && !mHidden;
371 }
372
373 private void updateCoordinates(Rect contentRectOnScreen) {
374 Objects.requireNonNull(contentRectOnScreen);
375
376 if (!isShowing()) {
377 return;
378 }
379 cancelOverflowAnimations();
380 refreshCoordinatesAndOverflowDirection(contentRectOnScreen);
381 preparePopupContent();
382 WidgetInfo widgetInfo = createWidgetInfo();
383 mSurfaceControlViewHost.relayout(mPopupWidth, mPopupHeight);
384 mCallbackWrapper.onWidgetUpdated(widgetInfo);
385 }
386
387 private void refreshCoordinatesAndOverflowDirection(Rect contentRectOnScreen) {
388 // Initialize x ensuring that the toolbar isn't rendered behind the nav bar in
389 // landscape.
390 final int x = Math.min(
391 contentRectOnScreen.centerX() - mPopupWidth / 2,
392 mViewPortOnScreen.right - mPopupWidth);
393
394 final int y;
395
396 final int availableHeightAboveContent =
397 contentRectOnScreen.top - mViewPortOnScreen.top;
398 final int availableHeightBelowContent =
399 mViewPortOnScreen.bottom - contentRectOnScreen.bottom;
400
401 final int margin = 2 * mMarginVertical;
402 final int toolbarHeightWithVerticalMargin = mLineHeight + margin;
403
404 if (!hasOverflow()) {
405 if (availableHeightAboveContent >= toolbarHeightWithVerticalMargin) {
406 // There is enough space at the top of the content.
407 y = contentRectOnScreen.top - toolbarHeightWithVerticalMargin;
408 } else if (availableHeightBelowContent >= toolbarHeightWithVerticalMargin) {
409 // There is enough space at the bottom of the content.
410 y = contentRectOnScreen.bottom;
411 } else if (availableHeightBelowContent >= mLineHeight) {
412 // Just enough space to fit the toolbar with no vertical margins.
413 y = contentRectOnScreen.bottom - mMarginVertical;
414 } else {
415 // Not enough space. Prefer to position as high as possible.
416 y = Math.max(
417 mViewPortOnScreen.top,
418 contentRectOnScreen.top - toolbarHeightWithVerticalMargin);
419 }
420 } else {
421 // Has an overflow.
422 final int minimumOverflowHeightWithMargin =
423 calculateOverflowHeight(MIN_OVERFLOW_SIZE) + margin;
424 final int availableHeightThroughContentDown =
425 mViewPortOnScreen.bottom - contentRectOnScreen.top
426 + toolbarHeightWithVerticalMargin;
427 final int availableHeightThroughContentUp =
428 contentRectOnScreen.bottom - mViewPortOnScreen.top
429 + toolbarHeightWithVerticalMargin;
430
431 if (availableHeightAboveContent >= minimumOverflowHeightWithMargin) {
432 // There is enough space at the top of the content rect for the overflow.
433 // Position above and open upwards.
434 updateOverflowHeight(availableHeightAboveContent - margin);
435 y = contentRectOnScreen.top - mPopupHeight;
436 mOpenOverflowUpwards = true;
437 } else if (availableHeightAboveContent >= toolbarHeightWithVerticalMargin
438 && availableHeightThroughContentDown >= minimumOverflowHeightWithMargin) {
439 // There is enough space at the top of the content rect for the main panel
440 // but not the overflow.
441 // Position above but open downwards.
442 updateOverflowHeight(availableHeightThroughContentDown - margin);
443 y = contentRectOnScreen.top - toolbarHeightWithVerticalMargin;
444 mOpenOverflowUpwards = false;
445 } else if (availableHeightBelowContent >= minimumOverflowHeightWithMargin) {
446 // There is enough space at the bottom of the content rect for the overflow.
447 // Position below and open downwards.
448 updateOverflowHeight(availableHeightBelowContent - margin);
449 y = contentRectOnScreen.bottom;
450 mOpenOverflowUpwards = false;
451 } else if (availableHeightBelowContent >= toolbarHeightWithVerticalMargin
452 && mViewPortOnScreen.height() >= minimumOverflowHeightWithMargin) {
453 // There is enough space at the bottom of the content rect for the main panel
454 // but not the overflow.
455 // Position below but open upwards.
456 updateOverflowHeight(availableHeightThroughContentUp - margin);
457 y = contentRectOnScreen.bottom + toolbarHeightWithVerticalMargin
458 - mPopupHeight;
459 mOpenOverflowUpwards = true;
460 } else {
461 // Not enough space.
462 // Position at the top of the view port and open downwards.
463 updateOverflowHeight(mViewPortOnScreen.height() - margin);
464 y = mViewPortOnScreen.top;
465 mOpenOverflowUpwards = false;
466 }
467 }
468 mRelativeCoordsForToolbar.set(x, y);
469 }
470
471 private void cancelDismissAndHideAnimations() {
472 mDismissAnimation.cancel();
473 mHideAnimation.cancel();
474 }
475
476 private void cancelOverflowAnimations() {
477 mContentContainer.clearAnimation();
478 mMainPanel.animate().cancel();
479 mOverflowPanel.animate().cancel();
480 mToArrow.stop();
481 mToOverflow.stop();
482 }
483
484 private void openOverflow() {
485 final int targetWidth = mOverflowPanelSize.getWidth();
486 final int targetHeight = mOverflowPanelSize.getHeight();
487 final int startWidth = mContentContainer.getWidth();
488 final int startHeight = mContentContainer.getHeight();
489 final float startY = mContentContainer.getY();
490 final float left = mContentContainer.getX();
491 final float right = left + mContentContainer.getWidth();
492 Animation widthAnimation = new Animation() {
493 @Override
494 protected void applyTransformation(float interpolatedTime, Transformation t) {
495 int deltaWidth = (int) (interpolatedTime * (targetWidth - startWidth));
496 setWidth(mContentContainer, startWidth + deltaWidth);
497 if (isInRTLMode()) {
498 mContentContainer.setX(left);
499
500 // Lock the panels in place.
501 mMainPanel.setX(0);
502 mOverflowPanel.setX(0);
503 } else {
504 mContentContainer.setX(right - mContentContainer.getWidth());
505
506 // Offset the panels' positions so they look like they're locked in place
507 // on the screen.
508 mMainPanel.setX(mContentContainer.getWidth() - startWidth);
509 mOverflowPanel.setX(mContentContainer.getWidth() - targetWidth);
510 }
511 }
512 };
513 Animation heightAnimation = new Animation() {
514 @Override
515 protected void applyTransformation(float interpolatedTime, Transformation t) {
516 int deltaHeight = (int) (interpolatedTime * (targetHeight - startHeight));
517 setHeight(mContentContainer, startHeight + deltaHeight);
518 if (mOpenOverflowUpwards) {
519 mContentContainer.setY(
520 startY - (mContentContainer.getHeight() - startHeight));
521 positionContentYCoordinatesIfOpeningOverflowUpwards();
522 }
523 }
524 };
525 final float overflowButtonStartX = mOverflowButton.getX();
526 final float overflowButtonTargetX =
527 isInRTLMode() ? overflowButtonStartX + targetWidth - mOverflowButton.getWidth()
528 : overflowButtonStartX - targetWidth + mOverflowButton.getWidth();
529 Animation overflowButtonAnimation = new Animation() {
530 @Override
531 protected void applyTransformation(float interpolatedTime, Transformation t) {
532 float overflowButtonX = overflowButtonStartX
533 + interpolatedTime * (overflowButtonTargetX - overflowButtonStartX);
534 float deltaContainerWidth =
535 isInRTLMode() ? 0 : mContentContainer.getWidth() - startWidth;
536 float actualOverflowButtonX = overflowButtonX + deltaContainerWidth;
537 mOverflowButton.setX(actualOverflowButtonX);
538 updateFloatingToolbarRootContentRect();
539 }
540 };
541 widthAnimation.setInterpolator(mLogAccelerateInterpolator);
542 widthAnimation.setDuration(getAnimationDuration());
543 heightAnimation.setInterpolator(mFastOutSlowInInterpolator);
544 heightAnimation.setDuration(getAnimationDuration());
545 overflowButtonAnimation.setInterpolator(mFastOutSlowInInterpolator);
546 overflowButtonAnimation.setDuration(getAnimationDuration());
547 mOpenOverflowAnimation.getAnimations().clear();
548 mOpenOverflowAnimation.addAnimation(widthAnimation);
549 mOpenOverflowAnimation.addAnimation(heightAnimation);
550 mOpenOverflowAnimation.addAnimation(overflowButtonAnimation);
551 mContentContainer.startAnimation(mOpenOverflowAnimation);
552 mIsOverflowOpen = true;
553 mMainPanel.animate()
554 .alpha(0).withLayer()
555 .setInterpolator(mLinearOutSlowInInterpolator)
556 .setDuration(250)
557 .start();
558 mOverflowPanel.setAlpha(1); // fadeIn in 0ms.
559 }
560
561 private void closeOverflow() {
562 final int targetWidth = mMainPanelSize.getWidth();
563 final int startWidth = mContentContainer.getWidth();
564 final float left = mContentContainer.getX();
565 final float right = left + mContentContainer.getWidth();
566 Animation widthAnimation = new Animation() {
567 @Override
568 protected void applyTransformation(float interpolatedTime, Transformation t) {
569 int deltaWidth = (int) (interpolatedTime * (targetWidth - startWidth));
570 setWidth(mContentContainer, startWidth + deltaWidth);
571 if (isInRTLMode()) {
572 mContentContainer.setX(left);
573
574 // Lock the panels in place.
575 mMainPanel.setX(0);
576 mOverflowPanel.setX(0);
577 } else {
578 mContentContainer.setX(right - mContentContainer.getWidth());
579
580 // Offset the panels' positions so they look like they're locked in place
581 // on the screen.
582 mMainPanel.setX(mContentContainer.getWidth() - targetWidth);
583 mOverflowPanel.setX(mContentContainer.getWidth() - startWidth);
584 }
585 }
586 };
587 final int targetHeight = mMainPanelSize.getHeight();
588 final int startHeight = mContentContainer.getHeight();
589 final float bottom = mContentContainer.getY() + mContentContainer.getHeight();
590 Animation heightAnimation = new Animation() {
591 @Override
592 protected void applyTransformation(float interpolatedTime, Transformation t) {
593 int deltaHeight = (int) (interpolatedTime * (targetHeight - startHeight));
594 setHeight(mContentContainer, startHeight + deltaHeight);
595 if (mOpenOverflowUpwards) {
596 mContentContainer.setY(bottom - mContentContainer.getHeight());
597 positionContentYCoordinatesIfOpeningOverflowUpwards();
598 }
599 }
600 };
601 final float overflowButtonStartX = mOverflowButton.getX();
602 final float overflowButtonTargetX =
603 isInRTLMode() ? overflowButtonStartX - startWidth + mOverflowButton.getWidth()
604 : overflowButtonStartX + startWidth - mOverflowButton.getWidth();
605 Animation overflowButtonAnimation = new Animation() {
606 @Override
607 protected void applyTransformation(float interpolatedTime, Transformation t) {
608 float overflowButtonX = overflowButtonStartX
609 + interpolatedTime * (overflowButtonTargetX - overflowButtonStartX);
610 float deltaContainerWidth =
611 isInRTLMode() ? 0 : mContentContainer.getWidth() - startWidth;
612 float actualOverflowButtonX = overflowButtonX + deltaContainerWidth;
613 mOverflowButton.setX(actualOverflowButtonX);
614 updateFloatingToolbarRootContentRect();
615 }
616 };
617 widthAnimation.setInterpolator(mFastOutSlowInInterpolator);
618 widthAnimation.setDuration(getAnimationDuration());
619 heightAnimation.setInterpolator(mLogAccelerateInterpolator);
620 heightAnimation.setDuration(getAnimationDuration());
621 overflowButtonAnimation.setInterpolator(mFastOutSlowInInterpolator);
622 overflowButtonAnimation.setDuration(getAnimationDuration());
623 mCloseOverflowAnimation.getAnimations().clear();
624 mCloseOverflowAnimation.addAnimation(widthAnimation);
625 mCloseOverflowAnimation.addAnimation(heightAnimation);
626 mCloseOverflowAnimation.addAnimation(overflowButtonAnimation);
627 mContentContainer.startAnimation(mCloseOverflowAnimation);
628 mIsOverflowOpen = false;
629 mMainPanel.animate()
630 .alpha(1).withLayer()
631 .setInterpolator(mFastOutLinearInInterpolator)
632 .setDuration(100)
633 .start();
634 mOverflowPanel.animate()
635 .alpha(0).withLayer()
636 .setInterpolator(mLinearOutSlowInInterpolator)
637 .setDuration(150)
638 .start();
639 }
640
641 /**
642 * Defines the position of the floating toolbar popup panels when transition animation has
643 * stopped.
644 */
645 private void setPanelsStatesAtRestingPosition() {
646 mOverflowButton.setEnabled(true);
647 mOverflowPanel.awakenScrollBars();
648
649 if (mIsOverflowOpen) {
650 // Set open state.
651 final Size containerSize = mOverflowPanelSize;
652 setSize(mContentContainer, containerSize);
653 mMainPanel.setAlpha(0);
654 mMainPanel.setVisibility(View.INVISIBLE);
655 mOverflowPanel.setAlpha(1);
656 mOverflowPanel.setVisibility(View.VISIBLE);
657 mOverflowButton.setImageDrawable(mArrow);
658 mOverflowButton.setContentDescription(mContext.getString(
659 R.string.floating_toolbar_close_overflow_description));
660
661 // Update x-coordinates depending on RTL state.
662 if (isInRTLMode()) {
663 mContentContainer.setX(mMarginHorizontal); // align left
664 mMainPanel.setX(0); // align left
665 mOverflowButton.setX(// align right
666 containerSize.getWidth() - mOverflowButtonSize.getWidth());
667 mOverflowPanel.setX(0); // align left
668 } else {
669 mContentContainer.setX(// align right
670 mPopupWidth - containerSize.getWidth() - mMarginHorizontal);
671 mMainPanel.setX(-mContentContainer.getX()); // align right
672 mOverflowButton.setX(0); // align left
673 mOverflowPanel.setX(0); // align left
674 }
675
676 // Update y-coordinates depending on overflow's open direction.
677 if (mOpenOverflowUpwards) {
678 mContentContainer.setY(mMarginVertical); // align top
679 mMainPanel.setY(// align bottom
680 containerSize.getHeight() - mContentContainer.getHeight());
681 mOverflowButton.setY(// align bottom
682 containerSize.getHeight() - mOverflowButtonSize.getHeight());
683 mOverflowPanel.setY(0); // align top
684 } else {
685 // opens downwards.
686 mContentContainer.setY(mMarginVertical); // align top
687 mMainPanel.setY(0); // align top
688 mOverflowButton.setY(0); // align top
689 mOverflowPanel.setY(mOverflowButtonSize.getHeight()); // align bottom
690 }
691 } else {
692 // Overflow not open. Set closed state.
693 final Size containerSize = mMainPanelSize;
694 setSize(mContentContainer, containerSize);
695 mMainPanel.setAlpha(1);
696 mMainPanel.setVisibility(View.VISIBLE);
697 mOverflowPanel.setAlpha(0);
698 mOverflowPanel.setVisibility(View.INVISIBLE);
699 mOverflowButton.setImageDrawable(mOverflow);
700 mOverflowButton.setContentDescription(mContext.getString(
701 R.string.floating_toolbar_open_overflow_description));
702
703 if (hasOverflow()) {
704 // Update x-coordinates depending on RTL state.
705 if (isInRTLMode()) {
706 mContentContainer.setX(mMarginHorizontal); // align left
707 mMainPanel.setX(0); // align left
708 mOverflowButton.setX(0); // align left
709 mOverflowPanel.setX(0); // align left
710 } else {
711 mContentContainer.setX(// align right
712 mPopupWidth - containerSize.getWidth() - mMarginHorizontal);
713 mMainPanel.setX(0); // align left
714 mOverflowButton.setX(// align right
715 containerSize.getWidth() - mOverflowButtonSize.getWidth());
716 mOverflowPanel.setX(// align right
717 containerSize.getWidth() - mOverflowPanelSize.getWidth());
718 }
719
720 // Update y-coordinates depending on overflow's open direction.
721 if (mOpenOverflowUpwards) {
722 mContentContainer.setY(// align bottom
723 mMarginVertical + mOverflowPanelSize.getHeight()
724 - containerSize.getHeight());
725 mMainPanel.setY(0); // align top
726 mOverflowButton.setY(0); // align top
727 mOverflowPanel.setY(// align bottom
728 containerSize.getHeight() - mOverflowPanelSize.getHeight());
729 } else {
730 // opens downwards.
731 mContentContainer.setY(mMarginVertical); // align top
732 mMainPanel.setY(0); // align top
733 mOverflowButton.setY(0); // align top
734 mOverflowPanel.setY(mOverflowButtonSize.getHeight()); // align bottom
735 }
736 } else {
737 // No overflow.
738 mContentContainer.setX(mMarginHorizontal); // align left
739 mContentContainer.setY(mMarginVertical); // align top
740 mMainPanel.setX(0); // align left
741 mMainPanel.setY(0); // align top
742 }
743 }
744 }
745
746 private void updateOverflowHeight(int suggestedHeight) {
747 if (hasOverflow()) {
748 final int maxItemSize =
749 (suggestedHeight - mOverflowButtonSize.getHeight()) / mLineHeight;
750 final int newHeight = calculateOverflowHeight(maxItemSize);
751 if (mOverflowPanelSize.getHeight() != newHeight) {
752 mOverflowPanelSize = new Size(mOverflowPanelSize.getWidth(), newHeight);
753 }
754 setSize(mOverflowPanel, mOverflowPanelSize);
755 if (mIsOverflowOpen) {
756 setSize(mContentContainer, mOverflowPanelSize);
757 if (mOpenOverflowUpwards) {
758 final int deltaHeight = mOverflowPanelSize.getHeight() - newHeight;
759 mContentContainer.setY(mContentContainer.getY() + deltaHeight);
760 mOverflowButton.setY(mOverflowButton.getY() - deltaHeight);
761 }
762 } else {
763 setSize(mContentContainer, mMainPanelSize);
764 }
765 updatePopupSize();
766 }
767 }
768
769 private void updatePopupSize() {
770 int width = 0;
771 int height = 0;
772 if (mMainPanelSize != null) {
773 width = Math.max(width, mMainPanelSize.getWidth());
774 height = Math.max(height, mMainPanelSize.getHeight());
775 }
776 if (mOverflowPanelSize != null) {
777 width = Math.max(width, mOverflowPanelSize.getWidth());
778 height = Math.max(height, mOverflowPanelSize.getHeight());
779 }
780
781 mPopupWidth = width + mMarginHorizontal * 2;
782 mPopupHeight = height + mMarginVertical * 2;
783 maybeComputeTransitionDurationScale();
784 }
785
786 private int getAdjustedToolbarWidth(int suggestedWidth) {
787 int width = suggestedWidth;
788 int maximumWidth = mViewPortOnScreen.width() - 2 * mContext.getResources()
789 .getDimensionPixelSize(R.dimen.floating_toolbar_horizontal_margin);
790 if (width <= 0) {
791 width = mContext.getResources()
792 .getDimensionPixelSize(R.dimen.floating_toolbar_preferred_width);
793 }
794 return Math.min(width, maximumWidth);
795 }
796
797 private boolean isInRTLMode() {
798 return mContext.getApplicationInfo().hasRtlSupport()
799 && mContext.getResources().getConfiguration().getLayoutDirection()
800 == View.LAYOUT_DIRECTION_RTL;
801 }
802
803 private boolean hasOverflow() {
804 return mOverflowPanelSize != null;
805 }
806
807 /**
808 * Fits as many menu items in the main panel and returns a list of the menu items that
809 * were not fit in.
810 *
811 * @return The menu items that are not included in this main panel.
812 */
813 private List<ToolbarMenuItem> layoutMainPanelItems(List<ToolbarMenuItem> menuItems,
814 int toolbarWidth) {
815 final LinkedList<ToolbarMenuItem> remainingMenuItems = new LinkedList<>();
816 // add the overflow menu items to the end of the remainingMenuItems list.
817 final LinkedList<ToolbarMenuItem> overflowMenuItems = new LinkedList();
818 for (ToolbarMenuItem menuItem : menuItems) {
819 if (menuItem.getItemId() != android.R.id.textAssist
820 && menuItem.getPriority() == ToolbarMenuItem.PRIORITY_OVERFLOW) {
821 overflowMenuItems.add(menuItem);
822 } else {
823 remainingMenuItems.add(menuItem);
824 }
825 }
826 remainingMenuItems.addAll(overflowMenuItems);
827
828 mMainPanel.removeAllViews();
829 mMainPanel.setPaddingRelative(0, 0, 0, 0);
830
831 int availableWidth = toolbarWidth;
832 boolean isFirstItem = true;
833 while (!remainingMenuItems.isEmpty()) {
834 ToolbarMenuItem menuItem = remainingMenuItems.peek();
835 // if this is the first item, regardless of requiresOverflow(), it should be
836 // displayed on the main panel. Otherwise all items including this one will be
837 // overflow items, and should be displayed in overflow panel.
838 if (!isFirstItem && menuItem.getPriority() == ToolbarMenuItem.PRIORITY_OVERFLOW) {
839 break;
840 }
841 final boolean showIcon = isFirstItem && menuItem.getItemId() == R.id.textAssist;
842 final View menuItemButton = createMenuItemButton(
843 mContext, menuItem, mIconTextSpacing, showIcon);
844 if (!showIcon && menuItemButton instanceof LinearLayout) {
845 ((LinearLayout) menuItemButton).setGravity(Gravity.CENTER);
846 }
847 // Adding additional start padding for the first button to even out button spacing.
848 if (isFirstItem) {
849 menuItemButton.setPaddingRelative(
850 (int) (1.5 * menuItemButton.getPaddingStart()),
851 menuItemButton.getPaddingTop(),
852 menuItemButton.getPaddingEnd(),
853 menuItemButton.getPaddingBottom());
854 }
855 // Adding additional end padding for the last button to even out button spacing.
856 boolean isLastItem = remainingMenuItems.size() == 1;
857 if (isLastItem) {
858 menuItemButton.setPaddingRelative(
859 menuItemButton.getPaddingStart(),
860 menuItemButton.getPaddingTop(),
861 (int) (1.5 * menuItemButton.getPaddingEnd()),
862 menuItemButton.getPaddingBottom());
863 }
864 menuItemButton.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
865 final int menuItemButtonWidth = Math.min(
866 menuItemButton.getMeasuredWidth(), toolbarWidth);
867 // Check if we can fit an item while reserving space for the overflowButton.
868 final boolean canFitWithOverflow =
869 menuItemButtonWidth <= availableWidth - mOverflowButtonSize.getWidth();
870 final boolean canFitNoOverflow =
871 isLastItem && menuItemButtonWidth <= availableWidth;
872 if (canFitWithOverflow || canFitNoOverflow) {
873 menuItemButton.setTag(menuItem);
874 menuItemButton.setOnClickListener(mMenuItemButtonOnClickListener);
875 // Set tooltips for main panel items, but not overflow items (b/35726766).
876 menuItemButton.setTooltipText(menuItem.getTooltipText());
877 mMainPanel.addView(menuItemButton);
878 final ViewGroup.LayoutParams params = menuItemButton.getLayoutParams();
879 params.width = menuItemButtonWidth;
880 menuItemButton.setLayoutParams(params);
881 availableWidth -= menuItemButtonWidth;
882 remainingMenuItems.pop();
883 } else {
884 break;
885 }
886 isFirstItem = false;
887 }
888 if (!remainingMenuItems.isEmpty()) {
889 // Reserve space for overflowButton.
890 mMainPanel.setPaddingRelative(0, 0, mOverflowButtonSize.getWidth(), 0);
891 }
892 mMainPanelSize = measure(mMainPanel);
893
894 return remainingMenuItems;
895 }
896
897 private void layoutOverflowPanelItems(List<ToolbarMenuItem> menuItems) {
898 ArrayAdapter<ToolbarMenuItem> overflowPanelAdapter =
899 (ArrayAdapter<ToolbarMenuItem>) mOverflowPanel.getAdapter();
900 overflowPanelAdapter.clear();
901 final int size = menuItems.size();
902 for (int i = 0; i < size; i++) {
903 overflowPanelAdapter.add(menuItems.get(i));
904 }
905 mOverflowPanel.setAdapter(overflowPanelAdapter);
906 if (mOpenOverflowUpwards) {
907 mOverflowPanel.setY(0);
908 } else {
909 mOverflowPanel.setY(mOverflowButtonSize.getHeight());
910 }
911 int width = Math.max(getOverflowWidth(), mOverflowButtonSize.getWidth());
912 int height = calculateOverflowHeight(MAX_OVERFLOW_SIZE);
913 mOverflowPanelSize = new Size(width, height);
914 setSize(mOverflowPanel, mOverflowPanelSize);
915 }
916
917 /**
918 * Resets the content container and appropriately position it's panels.
919 */
920 private void preparePopupContent() {
921 mContentContainer.removeAllViews();
922 // Add views in the specified order so they stack up as expected.
923 // Order: overflowPanel, mainPanel, overflowButton.
924 if (hasOverflow()) {
925 mContentContainer.addView(mOverflowPanel);
926 }
927 mContentContainer.addView(mMainPanel);
928 if (hasOverflow()) {
929 mContentContainer.addView(mOverflowButton);
930 }
931 setPanelsStatesAtRestingPosition();
932
933 // The positioning of contents in RTL is wrong when the view is first rendered.
934 // Hide the view and post a runnable to recalculate positions and render the view.
935 // TODO: Investigate why this happens and fix.
936 if (isInRTLMode()) {
937 mContentContainer.setAlpha(0);
938 mContentContainer.post(mPreparePopupContentRTLHelper);
939 }
940 }
941
942 /**
943 * Clears out the panels and their container. Resets their calculated sizes.
944 */
945 private void clearPanels() {
946 mIsOverflowOpen = false;
947 mMainPanelSize = null;
948 mMainPanel.removeAllViews();
949 mOverflowPanelSize = null;
950 ArrayAdapter<ToolbarMenuItem> overflowPanelAdapter =
951 (ArrayAdapter<ToolbarMenuItem>) mOverflowPanel.getAdapter();
952 overflowPanelAdapter.clear();
953 mOverflowPanel.setAdapter(overflowPanelAdapter);
954 mContentContainer.removeAllViews();
955 }
956
957 private void positionContentYCoordinatesIfOpeningOverflowUpwards() {
958 if (mOpenOverflowUpwards) {
959 mMainPanel.setY(mContentContainer.getHeight() - mMainPanelSize.getHeight());
960 mOverflowButton.setY(mContentContainer.getHeight() - mOverflowButton.getHeight());
961 mOverflowPanel.setY(mContentContainer.getHeight() - mOverflowPanelSize.getHeight());
962 }
963 }
964
965 private int getOverflowWidth() {
966 int overflowWidth = 0;
967 final int count = mOverflowPanel.getAdapter().getCount();
968 for (int i = 0; i < count; i++) {
969 ToolbarMenuItem menuItem = (ToolbarMenuItem) mOverflowPanel.getAdapter().getItem(i);
970 overflowWidth =
971 Math.max(mOverflowPanelViewHelper.calculateWidth(menuItem), overflowWidth);
972 }
973 return overflowWidth;
974 }
975
976 private int calculateOverflowHeight(int maxItemSize) {
977 // Maximum of 4 items, minimum of 2 if the overflow has to scroll.
978 int actualSize = Math.min(
979 MAX_OVERFLOW_SIZE,
980 Math.min(
981 Math.max(MIN_OVERFLOW_SIZE, maxItemSize),
982 mOverflowPanel.getCount()));
983 int extension = 0;
984 if (actualSize < mOverflowPanel.getCount()) {
985 // The overflow will require scrolling to get to all the items.
986 // Extend the height so that part of the hidden items is displayed.
987 extension = (int) (mLineHeight * 0.5f);
988 }
989 return actualSize * mLineHeight
990 + mOverflowButtonSize.getHeight()
991 + extension;
992 }
993
994 /**
995 * NOTE: Use only in android.view.animation.* animations. Do not use in android.animation.*
996 * animations. See comment about this in the code.
997 */
998 private int getAnimationDuration() {
999 if (mTransitionDurationScale < 150) {
1000 // For smaller transition, decrease the time.
1001 return 200;
1002 } else if (mTransitionDurationScale > 300) {
1003 // For bigger transition, increase the time.
1004 return 300;
1005 }
1006
1007 // Scale the animation duration with getDurationScale(). This allows
1008 // android.view.animation.* animations to scale just like android.animation.* animations
1009 // when animator duration scale is adjusted in "Developer Options".
1010 // For this reason, do not use this method for android.animation.* animations.
1011 return (int) (250 * ValueAnimator.getDurationScale());
1012 }
1013
1014 private void maybeComputeTransitionDurationScale() {
1015 if (mMainPanelSize != null && mOverflowPanelSize != null) {
1016 int w = mMainPanelSize.getWidth() - mOverflowPanelSize.getWidth();
1017 int h = mOverflowPanelSize.getHeight() - mMainPanelSize.getHeight();
1018 mTransitionDurationScale = (int) (Math.sqrt(w * w + h * h)
1019 / mContentContainer.getContext().getResources().getDisplayMetrics().density);
1020 }
1021 }
1022
1023 private ViewGroup createMainPanel() {
1024 return new LinearLayout(mContext) {
1025 @Override
1026 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1027 if (isOverflowAnimating()) {
1028 // Update widthMeasureSpec to make sure that this view is not clipped
1029 // as we offset its coordinates with respect to its parent.
1030 widthMeasureSpec = MeasureSpec.makeMeasureSpec(
1031 mMainPanelSize.getWidth(),
1032 MeasureSpec.EXACTLY);
1033 }
1034 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1035 }
1036
1037 @Override
1038 public boolean onInterceptTouchEvent(MotionEvent ev) {
1039 // Intercept the touch event while the overflow is animating.
1040 return isOverflowAnimating();
1041 }
1042 };
1043 }
1044
1045 private ImageButton createOverflowButton() {
1046 final ImageButton overflowButton = (ImageButton) LayoutInflater.from(mContext)
1047 .inflate(R.layout.floating_popup_overflow_button, null);
1048 overflowButton.setImageDrawable(mOverflow);
1049 overflowButton.setOnClickListener(v -> {
1050 if (isShowing()) {
1051 preparePopupContent();
1052 WidgetInfo widgetInfo = createWidgetInfo();
1053 mSurfaceControlViewHost.relayout(mPopupWidth, mPopupHeight);
1054 mCallbackWrapper.onWidgetUpdated(widgetInfo);
1055 }
1056 if (mIsOverflowOpen) {
1057 overflowButton.setImageDrawable(mToOverflow);
1058 mToOverflow.start();
1059 closeOverflow();
1060 } else {
1061 overflowButton.setImageDrawable(mToArrow);
1062 mToArrow.start();
1063 openOverflow();
1064 }
1065 });
1066 return overflowButton;
1067 }
1068
1069 private OverflowPanel createOverflowPanel() {
1070 final OverflowPanel overflowPanel = new OverflowPanel(this);
1071 overflowPanel.setLayoutParams(new ViewGroup.LayoutParams(
1072 ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
1073 overflowPanel.setDivider(null);
1074 overflowPanel.setDividerHeight(0);
1075
1076 final ArrayAdapter adapter =
1077 new ArrayAdapter<ToolbarMenuItem>(mContext, 0) {
1078 @Override
1079 public View getView(int position, View convertView, ViewGroup parent) {
1080 return mOverflowPanelViewHelper.getView(
1081 getItem(position), mOverflowPanelSize.getWidth(), convertView);
1082 }
1083 };
1084 overflowPanel.setAdapter(adapter);
1085 overflowPanel.setOnItemClickListener((parent, view, position, id) -> {
1086 ToolbarMenuItem menuItem =
1087 (ToolbarMenuItem) overflowPanel.getAdapter().getItem(position);
1088 mCallbackWrapper.onMenuItemClicked(menuItem);
1089 });
1090 return overflowPanel;
1091 }
1092
1093 private boolean isOverflowAnimating() {
1094 final boolean overflowOpening = mOpenOverflowAnimation.hasStarted()
1095 && !mOpenOverflowAnimation.hasEnded();
1096 final boolean overflowClosing = mCloseOverflowAnimation.hasStarted()
1097 && !mCloseOverflowAnimation.hasEnded();
1098 return overflowOpening || overflowClosing;
1099 }
1100
1101 private Animation.AnimationListener createOverflowAnimationListener() {
1102 return new Animation.AnimationListener() {
1103 @Override
1104 public void onAnimationStart(Animation animation) {
1105 // Disable the overflow button while it's animating.
1106 // It will be re-enabled when the animation stops.
1107 mOverflowButton.setEnabled(false);
1108 // Ensure both panels have visibility turned on when the overflow animation
1109 // starts.
1110 mMainPanel.setVisibility(View.VISIBLE);
1111 mOverflowPanel.setVisibility(View.VISIBLE);
1112 }
1113
1114 @Override
1115 public void onAnimationEnd(Animation animation) {
1116 // Posting this because it seems like this is called before the animation
1117 // actually ends.
1118 mContentContainer.post(() -> {
1119 setPanelsStatesAtRestingPosition();
1120 });
1121 }
1122
1123 @Override
1124 public void onAnimationRepeat(Animation animation) {
1125 }
1126 };
1127 }
1128
1129 private static Size measure(View view) {
1130 Preconditions.checkState(view.getParent() == null);
1131 view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
1132 return new Size(view.getMeasuredWidth(), view.getMeasuredHeight());
1133 }
1134
1135 private static void setSize(View view, int width, int height) {
1136 view.setMinimumWidth(width);
1137 view.setMinimumHeight(height);
1138 ViewGroup.LayoutParams params = view.getLayoutParams();
1139 params = (params == null) ? new ViewGroup.LayoutParams(0, 0) : params;
1140 params.width = width;
1141 params.height = height;
1142 view.setLayoutParams(params);
1143 }
1144
1145 private static void setSize(View view, Size size) {
1146 setSize(view, size.getWidth(), size.getHeight());
1147 }
1148
1149 private static void setWidth(View view, int width) {
1150 ViewGroup.LayoutParams params = view.getLayoutParams();
1151 setSize(view, width, params.height);
1152 }
1153
1154 private static void setHeight(View view, int height) {
1155 ViewGroup.LayoutParams params = view.getLayoutParams();
1156 setSize(view, params.width, height);
1157 }
1158
1159 /**
1160 * A custom ListView for the overflow panel.
1161 */
1162 private static final class OverflowPanel extends ListView {
1163
1164 private final RemoteSelectionToolbar mPopup;
1165
1166 OverflowPanel(RemoteSelectionToolbar popup) {
1167 super(Objects.requireNonNull(popup).mContext);
1168 this.mPopup = popup;
1169 setScrollBarDefaultDelayBeforeFade(ViewConfiguration.getScrollDefaultDelay() * 3);
1170 setScrollIndicators(View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_BOTTOM);
1171 }
1172
1173 @Override
1174 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1175 // Update heightMeasureSpec to make sure that this view is not clipped
1176 // as we offset it's coordinates with respect to its parent.
1177 int height = mPopup.mOverflowPanelSize.getHeight()
1178 - mPopup.mOverflowButtonSize.getHeight();
1179 heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
1180 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1181 }
1182
1183 @Override
1184 public boolean dispatchTouchEvent(MotionEvent ev) {
1185 if (mPopup.isOverflowAnimating()) {
1186 // Eat the touch event.
1187 return true;
1188 }
1189 return super.dispatchTouchEvent(ev);
1190 }
1191
1192 @Override
1193 protected boolean awakenScrollBars() {
1194 return super.awakenScrollBars();
1195 }
1196 }
1197
1198 /**
1199 * A custom interpolator used for various floating toolbar animations.
1200 */
1201 private static final class LogAccelerateInterpolator implements Interpolator {
1202
1203 private static final int BASE = 100;
1204 private static final float LOGS_SCALE = 1f / computeLog(1, BASE);
1205
1206 private static float computeLog(float t, int base) {
1207 return (float) (1 - Math.pow(base, -t));
1208 }
1209
1210 @Override
1211 public float getInterpolation(float t) {
1212 return 1 - computeLog(1 - t, BASE) * LOGS_SCALE;
1213 }
1214 }
1215
1216 /**
1217 * A helper for generating views for the overflow panel.
1218 */
1219 private static final class OverflowPanelViewHelper {
1220 private final Context mContext;
1221 private final View mCalculator;
1222 private final int mIconTextSpacing;
1223 private final int mSidePadding;
1224
1225 OverflowPanelViewHelper(Context context, int iconTextSpacing) {
1226 mContext = Objects.requireNonNull(context);
1227 mIconTextSpacing = iconTextSpacing;
1228 mSidePadding = context.getResources()
1229 .getDimensionPixelSize(R.dimen.floating_toolbar_overflow_side_padding);
1230 mCalculator = createMenuButton(null);
1231 }
1232
1233 public View getView(ToolbarMenuItem menuItem, int minimumWidth, View convertView) {
1234 Objects.requireNonNull(menuItem);
1235 if (convertView != null) {
1236 updateMenuItemButton(
1237 convertView, menuItem, mIconTextSpacing, shouldShowIcon(menuItem));
1238 } else {
1239 convertView = createMenuButton(menuItem);
1240 }
1241 convertView.setMinimumWidth(minimumWidth);
1242 return convertView;
1243 }
1244
1245 public int calculateWidth(ToolbarMenuItem menuItem) {
1246 updateMenuItemButton(
1247 mCalculator, menuItem, mIconTextSpacing, shouldShowIcon(menuItem));
1248 mCalculator.measure(
1249 View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
1250 return mCalculator.getMeasuredWidth();
1251 }
1252
1253 private View createMenuButton(ToolbarMenuItem menuItem) {
1254 View button = createMenuItemButton(
1255 mContext, menuItem, mIconTextSpacing, shouldShowIcon(menuItem));
1256 button.setPadding(mSidePadding, 0, mSidePadding, 0);
1257 return button;
1258 }
1259
1260 private boolean shouldShowIcon(ToolbarMenuItem menuItem) {
1261 if (menuItem != null) {
1262 return menuItem.getGroupId() == android.R.id.textAssist;
1263 }
1264 return false;
1265 }
1266 }
1267
1268 /**
1269 * Creates and returns a menu button for the specified menu item.
1270 */
1271 private static View createMenuItemButton(
1272 Context context, ToolbarMenuItem menuItem, int iconTextSpacing, boolean showIcon) {
1273 final View menuItemButton = LayoutInflater.from(context)
1274 .inflate(R.layout.floating_popup_menu_button, null);
1275 if (menuItem != null) {
1276 updateMenuItemButton(menuItemButton, menuItem, iconTextSpacing, showIcon);
1277 }
1278 return menuItemButton;
1279 }
1280
1281 /**
1282 * Updates the specified menu item button with the specified menu item data.
1283 */
1284 private static void updateMenuItemButton(View menuItemButton, ToolbarMenuItem menuItem,
1285 int iconTextSpacing, boolean showIcon) {
1286 final TextView buttonText = menuItemButton.findViewById(
1287 R.id.floating_toolbar_menu_item_text);
1288 buttonText.setEllipsize(null);
1289 if (TextUtils.isEmpty(menuItem.getTitle())) {
1290 buttonText.setVisibility(View.GONE);
1291 } else {
1292 buttonText.setVisibility(View.VISIBLE);
1293 buttonText.setText(menuItem.getTitle());
1294 }
1295 final ImageView buttonIcon = menuItemButton.findViewById(
1296 R.id.floating_toolbar_menu_item_image);
1297 if (menuItem.getIcon() == null || !showIcon) {
1298 buttonIcon.setVisibility(View.GONE);
1299 buttonText.setPaddingRelative(0, 0, 0, 0);
1300 } else {
1301 buttonIcon.setVisibility(View.VISIBLE);
1302 buttonIcon.setImageDrawable(
1303 menuItem.getIcon().loadDrawable(menuItemButton.getContext()));
1304 buttonText.setPaddingRelative(iconTextSpacing, 0, 0, 0);
1305 }
1306 final CharSequence contentDescription = menuItem.getContentDescription();
1307 if (TextUtils.isEmpty(contentDescription)) {
1308 menuItemButton.setContentDescription(menuItem.getTitle());
1309 } else {
1310 menuItemButton.setContentDescription(contentDescription);
1311 }
1312 }
1313
1314 private static ViewGroup createContentContainer(Context context) {
1315 ViewGroup contentContainer = (ViewGroup) LayoutInflater.from(context)
1316 .inflate(R.layout.floating_popup_container, null);
1317 contentContainer.setLayoutParams(new ViewGroup.LayoutParams(
1318 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
1319 contentContainer.setTag(FloatingToolbar.FLOATING_TOOLBAR_TAG);
1320 contentContainer.setClipToOutline(true);
1321 return contentContainer;
1322 }
1323
1324 /**
1325 * Creates an "appear" animation for the specified view.
1326 *
1327 * @param view The view to animate
1328 */
1329 private static AnimatorSet createEnterAnimation(View view, Animator.AnimatorListener listener) {
1330 AnimatorSet animation = new AnimatorSet();
1331 animation.playTogether(
1332 ObjectAnimator.ofFloat(view, View.ALPHA, 0, 1).setDuration(150));
1333 animation.addListener(listener);
1334 return animation;
1335 }
1336
1337 /**
1338 * Creates a "disappear" animation for the specified view.
1339 *
1340 * @param view The view to animate
1341 * @param startDelay The start delay of the animation
1342 * @param listener The animation listener
1343 */
1344 private static AnimatorSet createExitAnimation(
1345 View view, int startDelay, Animator.AnimatorListener listener) {
1346 AnimatorSet animation = new AnimatorSet();
1347 animation.playTogether(
1348 ObjectAnimator.ofFloat(view, View.ALPHA, 1, 0).setDuration(100));
1349 animation.setStartDelay(startDelay);
1350 if (listener != null) {
1351 animation.addListener(listener);
1352 }
1353 return animation;
1354 }
1355
1356 /**
1357 * Returns a re-themed context with controlled look and feel for views.
1358 */
1359 private static Context applyDefaultTheme(Context originalContext, boolean isLightTheme) {
1360 int themeId =
1361 isLightTheme ? R.style.Theme_DeviceDefault_Light : R.style.Theme_DeviceDefault;
1362 return new ContextThemeWrapper(originalContext, themeId);
1363 }
1364
1365 private static void debugLog(String message) {
1366 if (Log.isLoggable(FloatingToolbar.FLOATING_TOOLBAR_TAG, Log.DEBUG)) {
1367 Log.v(TAG, message);
1368 }
1369 }
1370
1371 void dump(String prefix, PrintWriter pw) {
1372 pw.print(prefix); pw.print("toolbar token: "); pw.println(mSelectionToolbarToken);
1373 pw.print(prefix); pw.print("dismissed: "); pw.println(mDismissed);
1374 pw.print(prefix); pw.print("hidden: "); pw.println(mHidden);
1375 pw.print(prefix); pw.print("popup width: "); pw.println(mPopupWidth);
1376 pw.print(prefix); pw.print("popup height: "); pw.println(mPopupHeight);
1377 pw.print(prefix); pw.print("relative coords: "); pw.println(mRelativeCoordsForToolbar);
1378 pw.print(prefix); pw.print("main panel size: "); pw.println(mMainPanelSize);
1379 boolean hasOverflow = hasOverflow();
1380 pw.print(prefix); pw.print("has overflow: "); pw.println(hasOverflow);
1381 if (hasOverflow) {
1382 pw.print(prefix); pw.print("overflow open: "); pw.println(mIsOverflowOpen);
1383 pw.print(prefix); pw.print("overflow size: "); pw.println(mOverflowPanelSize);
1384 }
1385 if (mSurfaceControlViewHost != null) {
1386 FloatingToolbarRoot root = (FloatingToolbarRoot) mSurfaceControlViewHost.getView();
1387 root.dump(prefix, pw);
1388 }
1389 if (mMenuItems != null) {
1390 int menuItemSize = mMenuItems.size();
1391 pw.print(prefix); pw.print("number menu items: "); pw.println(menuItemSize);
1392 for (int i = 0; i < menuItemSize; i++) {
1393 pw.print(prefix); pw.print("#"); pw.println(i);
1394 pw.print(prefix + " "); pw.println(mMenuItems.get(i));
1395 }
1396 }
1397 }
1398 }