-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
PartialCustomTabHeightStrategy.java
1026 lines (888 loc) · 41.6 KB
/
PartialCustomTabHeightStrategy.java
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.customtabs;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.InsetDrawable;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.VisibleForTesting;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsAnimationControlListenerCompat;
import androidx.core.view.WindowInsetsAnimationControllerCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.swiperefreshlayout.widget.CircularProgressDrawable;
import org.chromium.base.ContextUtils;
import org.chromium.base.MathUtils;
import org.chromium.base.SysUtils;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.customtabs.features.toolbar.CustomTabToolbar;
import org.chromium.chrome.browser.flags.BooleanCachedFieldTrialParameter;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.fullscreen.FullscreenManager;
import org.chromium.chrome.browser.fullscreen.FullscreenOptions;
import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher;
import org.chromium.chrome.browser.lifecycle.ConfigurationChangedObserver;
import org.chromium.chrome.browser.multiwindow.MultiWindowUtils;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.ui.base.ViewUtils;
import org.chromium.ui.util.ColorUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* CustomTabHeightStrategy for Partial Custom Tab. An instance of this class should be
* owned by the CustomTabActivity.
*/
public class PartialCustomTabHeightStrategy extends CustomTabHeightStrategy
implements ConfigurationChangedObserver, ValueAnimator.AnimatorUpdateListener,
PartialCustomTabHandleStrategy.DragEventCallback, FullscreenManager.Observer {
@VisibleForTesting
static final long SPINNER_TIMEOUT_MS = 500;
/**
* Minimal height the bottom sheet CCT should show is half of the display height.
*/
private static final float MINIMAL_HEIGHT_RATIO = 0.5f;
/**
* The maximum height we can snap to is under experiment, we have two branches, 90% of the
* display height and 100% of the display height. This ratio is used to calculate the 90% of the
* display height.
*/
private static final float EXTRA_HEIGHT_RATIO = 0.1f;
private static final int NAVBAR_FADE_DURATION_MS = 16;
private static final int SPINNER_FADEIN_DURATION_MS = 100;
private static final int SPINNER_FADEOUT_DURATION_MS = 400;
private static final int NAVBAR_BUTTON_RESTORE_DELAY_MS = 400;
private static final int NAVBAR_BUTTON_HIDE_SHOW_DELAY_MS = 150;
private static final String PARAM_LOG_IMMERSIVE_MODE_CONFIRMATIONS =
"log_immersive_mode_confirmations";
@VisibleForTesting
static final String IMMERSIVE_MODE_CONFIRMATIONS_SETTING = "immersive_mode_confirmations";
@VisibleForTesting
static final String IMMERSIVE_MODE_CONFIRMATIONS_SETTING_VALUE = "confirmed";
public static final BooleanCachedFieldTrialParameter LOG_IMMERSIVE_MODE_CONFIRMATIONS =
new BooleanCachedFieldTrialParameter(
ChromeFeatureList.CCT_RESIZABLE_ALWAYS_SHOW_NAVBAR_BUTTONS,
PARAM_LOG_IMMERSIVE_MODE_CONFIRMATIONS, true);
@IntDef({HeightStatus.TOP, HeightStatus.INITIAL_HEIGHT, HeightStatus.TRANSITION,
HeightStatus.CLOSE})
@Retention(RetentionPolicy.SOURCE)
@interface HeightStatus {
int TOP = 0;
int INITIAL_HEIGHT = 1;
int TRANSITION = 2;
int CLOSE = 3;
}
private final Activity mActivity;
private final PartialCustomTabVersionCompat mVersionCompat;
private final OnResizedCallback mOnResizedCallback;
private final AnimatorListener mSpinnerFadeoutAnimatorListener;
private final int mCachedHandleHeight;
private final boolean mInteractWithBackground;
private final boolean mIsFixedHeight;
private final @Px int mUnclampedInitialHeight;
private final FullscreenManager mFullscreenManager;
private final boolean mAlwaysShowNavbarButtons;
private final Rect mFullscreenRestoreRect = new Rect();
private static boolean sHasLoggedImmersiveModeConfirmationSetting;
private @Px int mDisplayHeight;
private @Px int mFullyExpandedAdjustmentHeight;
private ValueAnimator mAnimator;
private int mShadowOffset;
private boolean mDrawOutlineShadow;
// ContentFrame + CoordinatorLayout - CompositorViewHolder
// + NavigationBar
// + Spinner
// Not just CompositorViewHolder but also CoordinatorLayout is resized because many UI
// components such as BottomSheet, InfoBar, Snackbar are child views of CoordinatorLayout,
// which makes them appear correctly at the bottom.
private ViewGroup mCoordinatorLayout;
private @HeightStatus int mStatus = HeightStatus.INITIAL_HEIGHT;
private @HeightStatus int mTargetStatus;
// Bottom navigation bar height. Set to zero when the bar is positioned on the right side
// in landcape mode.
private @Px int mNavbarHeight;
private int mOrientation;
private @Px int mStatusbarHeight;
// Note: Do not use anywhere except in |onConfigurationChanged| as it might not be up-to-date.
private boolean mIsInMultiWindowMode;
private ImageView mSpinnerView;
private LinearLayout mNavbar;
private CircularProgressDrawable mSpinner;
private View mToolbarView;
private View mToolbarCoordinator;
private int mToolbarColor;
private Runnable mPositionUpdater;
private Runnable mSoftKeyboardRunnable;
private boolean mStopShowingSpinner;
private boolean mRestoreAfterFindPage;
// Runnable finishing the activity after the exit animation. Non-null when PCCT is closing.
@Nullable
private Runnable mFinishRunnable;
// Y offset when a dragging gesture starts.
private int mDraggingStartY;
private float mOffsetY;
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
// This should be kept in sync with the definition |CustomTabsResizeType|
// in tools/metrics/histograms/enums.xml.
@IntDef({ResizeType.EXPANSION, ResizeType.MINIMIZATION, ResizeType.COUNT})
@Retention(RetentionPolicy.SOURCE)
@VisibleForTesting
@interface ResizeType {
int EXPANSION = 0;
int MINIMIZATION = 1;
int COUNT = 2;
}
/** A callback to be called once the Custom Tab has been resized. */
interface OnResizedCallback {
/** The Custom Tab has been resized. */
void onResized(int size);
}
// The current height used to trigger onResizedCallback when it is resized.
private int mHeight;
// Class used to control show / hide nav bar.
private NavBarTransitionController mNavbarTransitionController =
new NavBarTransitionController();
// Used to initialize the coordinator view (R.id.coordinator) to full-height at the beginning.
// This is a workaround to an issue of the host app briefly flashing when the tab is resized.
private boolean mInitFirstHeight;
private boolean mIsTablet;
public PartialCustomTabHeightStrategy(Activity activity, @Px int initialHeight,
boolean isFixedHeight, OnResizedCallback onResizedCallback,
ActivityLifecycleDispatcher lifecycleDispatcher, FullscreenManager fullscreenManager,
boolean isTablet, boolean interactWithBackground) {
mAlwaysShowNavbarButtons =
ChromeFeatureList.sCctResizableAlwaysShowNavBarButtons.isEnabled();
mActivity = activity;
mVersionCompat = PartialCustomTabVersionCompat.create(mActivity, this::updatePosition);
mDisplayHeight = mVersionCompat.getDisplayHeight();
mUnclampedInitialHeight = initialHeight;
mIsFixedHeight = isFixedHeight;
mInteractWithBackground = interactWithBackground;
mOnResizedCallback = onResizedCallback;
mFullscreenManager = fullscreenManager;
mAnimator = new ValueAnimator();
mAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
mStatus = HeightStatus.TRANSITION;
}
@Override
public void onAnimationEnd(Animator animation) {
mStatus = mTargetStatus;
onMoveEnd();
}
});
mAnimator.addUpdateListener(this);
mAnimator.setInterpolator(new AccelerateInterpolator());
mAnimator.setDuration(
mActivity.getResources().getInteger(android.R.integer.config_mediumAnimTime));
lifecycleDispatcher.register(this);
mOrientation = mActivity.getResources().getConfiguration().orientation;
mIsInMultiWindowMode = MultiWindowUtils.getInstance().isInMultiWindowMode(mActivity);
mDrawOutlineShadow = SysUtils.isLowEndDevice();
mCachedHandleHeight =
mActivity.getResources().getDimensionPixelSize(R.dimen.custom_tabs_handle_height);
mSpinnerFadeoutAnimatorListener = new AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {}
@Override
public void onAnimationRepeat(Animator animator) {}
@Override
public void onAnimationEnd(Animator animator) {
mSpinner.stop();
mSpinnerView.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animator) {}
};
mPositionUpdater = mVersionCompat::updatePosition;
fullscreenManager.addObserver(this);
mIsTablet = isTablet;
logImmersiveModeConfirmationSettingValue(ContextUtils.getApplicationContext());
}
@Override
public void onPostInflationStartup() {
mCoordinatorLayout = (ViewGroup) mActivity.findViewById(R.id.coordinator);
// Elevate the main web contents area as high as the handle bar to have the shadow
// effect look right.
int ev = mActivity.getResources().getDimensionPixelSize(R.dimen.custom_tabs_elevation);
mCoordinatorLayout.setElevation(ev);
mPositionUpdater.run();
}
public void onShowSoftInput(Runnable softKeyboardRunnable) {
// Expands to full height to avoid the tab being hidden by the soft keyboard.
// Necessary only if we're at the initial height status.
if (isFullHeight() || mStatus != HeightStatus.INITIAL_HEIGHT) {
softKeyboardRunnable.run();
return;
}
mSoftKeyboardRunnable = softKeyboardRunnable;
animateTabTo(HeightStatus.TOP);
}
private void animateTabTo(int targetStatus) {
// Tab cannot be animated to top/initial when running in full height.
assert !(isFullHeight()
&& (targetStatus == HeightStatus.TOP
|| targetStatus == HeightStatus.INITIAL_HEIGHT));
Window window = mActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
WindowManager.LayoutParams attrs = window.getAttributes();
int start = attrs.y;
int end;
switch (targetStatus) {
case HeightStatus.TOP:
// Make the window full height if it is not already. Otherwise background app
// can flash briefly while expanding.
if (attrs.height < mDisplayHeight - mNavbarHeight) {
attrs.height = mDisplayHeight - mNavbarHeight;
window.setAttributes(attrs);
}
end = getFullyExpandedYWithAdjustment();
break;
case HeightStatus.INITIAL_HEIGHT:
end = initialY();
break;
case HeightStatus.CLOSE:
end = mDisplayHeight - mNavbarHeight;
if (isFullHeight()) {
attrs.y = getFullyExpandedY();
window.setAttributes(attrs);
}
break;
default:
end = 0;
assert false : "Target status should be either top or initial height";
}
mTargetStatus = targetStatus;
mAnimator.setIntValues(start, end);
mAnimator.start();
}
private void updatePosition() {
if (mActivity.findViewById(android.R.id.content) == null) return;
initializeHeight();
updateShadowOffset();
maybeInvokeResizeCallback();
mRestoreAfterFindPage = false;
}
private int initialY() {
return mDisplayHeight - initialHeightInPortraitMode();
}
private int initialHeightInPortraitMode() {
assert !isFullHeight() : "initialHeightInPortraitMode() is used in portrait mode only";
return MathUtils.clamp(mUnclampedInitialHeight, mDisplayHeight - mStatusbarHeight,
(int) (mDisplayHeight * MINIMAL_HEIGHT_RATIO));
}
@Override
public void onToolbarInitialized(
View coordinatorView, CustomTabToolbar toolbar, @Px int toolbarCornerRadius) {
mToolbarCoordinator = coordinatorView;
mToolbarView = toolbar;
mToolbarColor = toolbar.getBackground().getColor();
roundCorners(coordinatorView, toolbar, toolbarCornerRadius);
toolbar.setHandleStrategy(new PartialCustomTabHandleStrategy(
mActivity, this::isFullHeight, () -> mStatus, this));
updateDragBarVisibility();
}
// ConfigurationChangedObserver implementation.
@Override
public void onConfigurationChanged(Configuration newConfig) {
boolean isInMultiWindow = MultiWindowUtils.getInstance().isInMultiWindowMode(mActivity);
int orientation = newConfig.orientation;
int displayHeight = mVersionCompat.getDisplayHeight();
if (isInMultiWindow != mIsInMultiWindowMode || orientation != mOrientation
|| displayHeight != mDisplayHeight) {
mIsInMultiWindowMode = isInMultiWindow;
mOrientation = orientation;
mDisplayHeight = displayHeight;
if (isFullHeight()) {
// We should update CCT position before Window#FLAG_LAYOUT_NO_LIMITS is set,
// otherwise it is not possible to get the correct content height.
mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
mPositionUpdater.run();
}
}
// ValueAnimator.AnimatorUpdateListener implementation.
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (int) valueAnimator.getAnimatedValue();
updateWindowPos(value);
}
private void roundCorners(
View coordinator, CustomTabToolbar toolbar, @Px int toolbarCornerRadius) {
// Inflate the handle View.
ViewStub handleViewStub = mActivity.findViewById(R.id.custom_tabs_handle_view_stub);
handleViewStub.inflate();
View handleView = mActivity.findViewById(R.id.custom_tabs_handle_view);
handleView.setElevation(
mActivity.getResources().getDimensionPixelSize(R.dimen.custom_tabs_elevation));
updateShadowOffset();
GradientDrawable cctBackground = (GradientDrawable) handleView.getBackground();
adjustCornerRadius(cctBackground, toolbarCornerRadius);
handleView.setBackground(cctBackground);
// Inner frame |R.id.drag_bar| is used for setting background color to match that of
// the toolbar. Outer frame |R.id.custom_tabs_handle_view| is not suitable since it
// covers the entire client area for rendering outline shadow around the CCT.
View dragBar = handleView.findViewById(R.id.drag_bar);
GradientDrawable dragBarBackground = (GradientDrawable) dragBar.getBackground();
adjustCornerRadius(dragBarBackground, toolbarCornerRadius);
if (mDrawOutlineShadow) {
int width = mActivity.getResources().getDimensionPixelSize(
R.dimen.custom_tabs_outline_width);
cctBackground.setStroke(width, toolbar.getToolbarHairlineColor(mToolbarColor));
// We need an inset to make the outline shadow visible.
dragBar.setBackground(new InsetDrawable(dragBarBackground, width, width, width, 0));
} else {
dragBar.setBackground(dragBarBackground);
}
// Pass the drag bar portion to CustomTabToolbar for background color management.
toolbar.setHandleBackground(dragBarBackground);
// Having the transparent background is necessary for the shadow effect.
mActivity.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
private static void adjustCornerRadius(GradientDrawable d, int radius) {
d.mutate();
d.setCornerRadii(new float[] {radius, radius, radius, radius, 0, 0, 0, 0});
}
private GradientDrawable getDragBarBackground() {
View dragBar = mActivity.findViewById(R.id.drag_bar);
return (GradientDrawable) dragBar.getBackground();
}
@Override
public void setScrimFraction(float scrimFraction) {
int scrimColor = mActivity.getResources().getColor(R.color.default_scrim_color);
float scrimColorAlpha = (scrimColor >>> 24) / 255f;
int scrimColorOpaque = scrimColor & 0xFF000000;
int color = ColorUtils.getColorWithOverlay(
mToolbarColor, scrimColorOpaque, scrimFraction * scrimColorAlpha, false);
// Drag handle view is not part of CoordinatorLayout. As the root UI scrim changes,
// the handle view color needs updating to match it. This is a better way than running
// PCCT's own scrim coordinator since it can apply shape-aware scrim to the handle view
// that has the rounded corner.
getDragBarBackground().setColor(color);
ImageView handle = (ImageView) mActivity.findViewById(R.id.drag_handlebar);
int handleColor = mActivity.getColor(R.color.drag_handlebar_color_baseline);
if (scrimFraction > 0.f) {
handle.setColorFilter(ColorUtils.getColorWithOverlay(
handleColor, scrimColorOpaque, scrimFraction * scrimColorAlpha, false));
} else {
handle.clearColorFilter();
}
}
@Override
public void onFindToolbarShown() {
if (mIsTablet) return;
int findToolbarBackground =
mActivity.getResources().getColor(R.color.find_in_page_background_color);
getDragBarBackground().setColor(findToolbarBackground);
if (isFullHeight()) return;
// We get zero search results if the content view is entirely hidden by the soft keyboard,
// which can happen if the tab is at initial height. Expand it.
if (mStatus == HeightStatus.INITIAL_HEIGHT) {
animateTabTo(HeightStatus.TOP);
mRestoreAfterFindPage = true;
}
}
@Override
public void onFindToolbarHidden() {
if (mIsTablet) return;
getDragBarBackground().setColor(mToolbarColor);
if (isFullHeight()) return;
if (mRestoreAfterFindPage) {
animateTabTo(HeightStatus.INITIAL_HEIGHT);
mRestoreAfterFindPage = false;
}
}
private void initializeHeight() {
Window window = mActivity.getWindow();
if (canInteractWithBackground()) {
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
window.setDimAmount(0.6f);
}
mNavbarHeight = mVersionCompat.getNavbarHeight();
mStatusbarHeight = mVersionCompat.getStatusbarHeight();
// When the flag is enabled, we make the max snap point 10% shorter, so it will only occupy
// 90% of the height.
mFullyExpandedAdjustmentHeight = ChromeFeatureList.sCctResizable90MaximumHeight.isEnabled()
? (int) ((mDisplayHeight - getFullyExpandedY()) * EXTRA_HEIGHT_RATIO)
: 0;
int maxExpandedY = getFullyExpandedY();
@Px
int height = 0;
if (!isFullHeight()) {
if (mStatus == HeightStatus.INITIAL_HEIGHT) {
height = initialHeightInPortraitMode();
} else if (mStatus == HeightStatus.TOP) {
height = mDisplayHeight - maxExpandedY;
}
}
WindowManager.LayoutParams attrs = window.getAttributes();
if (attrs.height == height) return;
// To avoid the bottom navigation bar area flickering when starting dragging, position
// web contents area right above the navigation bar so the two won't overlap. The
// navigation area now just shows whatever is underneath: 1) loading view/web contents
// while dragging 2) host app's navigation bar when at rest.
positionAtHeight(height);
mHeight = attrs.height;
if (!mInitFirstHeight) {
setCoordinatorLayoutHeight(mDisplayHeight);
mInitFirstHeight = true;
new Handler().post(() -> setCoordinatorLayoutHeight(MATCH_PARENT));
}
updateDragBarVisibility();
}
private void positionAtHeight(int height) {
WindowManager.LayoutParams attrs = mActivity.getWindow().getAttributes();
if (isFullHeight()) {
attrs.height = MATCH_PARENT;
attrs.y = 0;
} else {
attrs.height = height - mNavbarHeight;
attrs.y = mDisplayHeight - attrs.height - mNavbarHeight;
}
attrs.gravity = Gravity.TOP;
mActivity.getWindow().setAttributes(attrs);
}
private void setCoordinatorLayoutHeight(int height) {
ViewGroup.LayoutParams p = mCoordinatorLayout.getLayoutParams();
p.height = height;
mCoordinatorLayout.setLayoutParams(p);
}
private void updateDragBarVisibility() {
View dragBar = mActivity.findViewById(R.id.drag_bar);
if (dragBar != null) dragBar.setVisibility(isFullHeight() ? View.GONE : View.VISIBLE);
View dragHandlebar = mActivity.findViewById(R.id.drag_handlebar);
if (dragHandlebar != null) {
dragHandlebar.setVisibility(isFixedHeight() ? View.GONE : View.VISIBLE);
}
}
private void updateShadowOffset() {
if (isFullHeight() || mDrawOutlineShadow || mStatus == HeightStatus.TOP) {
mShadowOffset = 0;
} else {
mShadowOffset = mActivity.getResources().getDimensionPixelSize(
R.dimen.custom_tabs_shadow_offset);
}
setTopMargins(mShadowOffset, getHandleHeight() + mShadowOffset);
ViewUtils.requestLayout(
mToolbarCoordinator, "PartialCustomTabHeightStrategy.updateShadowOffet");
}
private void setTopMargins(int shadowOffset, int handleOffset) {
View handleView = mActivity.findViewById(R.id.custom_tabs_handle_view);
ViewGroup.MarginLayoutParams lp =
(ViewGroup.MarginLayoutParams) handleView.getLayoutParams();
lp.setMargins(0, shadowOffset, 0, 0);
// Make enough room for the handle View.
ViewGroup.MarginLayoutParams mlp =
(ViewGroup.MarginLayoutParams) mToolbarCoordinator.getLayoutParams();
mlp.setMargins(0, handleOffset, 0, 0);
}
private int getHandleHeight() {
return isFullHeight() ? 0 : mCachedHandleHeight;
}
private boolean isFullHeight() {
return isLandscape() || MultiWindowUtils.getInstance().isInMultiWindowMode(mActivity);
}
private boolean isLandscape() {
return mOrientation == Configuration.ORIENTATION_LANDSCAPE;
}
private boolean isFixedHeight() {
return mIsFixedHeight;
}
private boolean isFullscreen() {
WindowManager.LayoutParams attrs = mActivity.getWindow().getAttributes();
return attrs.x == 0 && attrs.y == 0 && attrs.width == MATCH_PARENT
&& attrs.height == MATCH_PARENT;
}
private boolean canInteractWithBackground() {
return mInteractWithBackground;
}
private void updateWindowPos(@Px int y) {
// Do not allow the Window to go above the minimum threshold capped by the status
// bar and (optionally) the 90%-height adjustment.
int topY = getFullyExpandedYWithAdjustment();
y = MathUtils.clamp(y, topY, mDisplayHeight);
Window window = mActivity.getWindow();
WindowManager.LayoutParams attrs = window.getAttributes();
if (attrs.y == y) return;
// If the tab is not resizable then dragging it higher than the initial height will not be
// allowed. The tab can still be dragged down in order to be closed.
if (isFixedHeight() && y < initialY()) return;
attrs.y = y;
window.setAttributes(attrs);
if (mFinishRunnable != null) return;
// Starting dragging from INITIAL_HEIGHT state, we can hide the spinner if the tab:
// 1) reaches full height
// 2) is dragged below the initial height
if (mStatus == HeightStatus.INITIAL_HEIGHT && (y <= topY || y > initialY())
&& isSpinnerVisible()) {
hideSpinnerView();
if (y <= topY) {
// Once reaching full-height, tab can hide the spinner permanently till
// the finger is lifted. Keep it hidden.
mStopShowingSpinner = true;
return;
}
}
// Show the spinner lazily, only when the tab is dragged _up_, which requires showing
// more area than initial state.
if (!mStopShowingSpinner && mStatus != HeightStatus.TRANSITION && !isSpinnerVisible()
&& y < mDraggingStartY) {
showSpinnerView();
// We do not have to keep the spinner till the end of dragging action, since it doesn't
// have the flickering issue at the end. Keeping it visible up to 500ms is sufficient to
// hide the initial glitch that can briefly expose the host app screen at the beginning.
new Handler().postDelayed(() -> {
hideSpinnerView();
mStopShowingSpinner = true;
}, SPINNER_TIMEOUT_MS);
}
if (isSpinnerVisible()) {
centerSpinnerVertically((ViewGroup.LayoutParams) mSpinnerView.getLayoutParams());
}
}
private boolean isSpinnerVisible() {
return mSpinnerView != null && mSpinnerView.getVisibility() == View.VISIBLE;
}
private void onMoveStart() {
Window window = mActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
WindowManager.LayoutParams attrs = window.getAttributes();
attrs.height = mDisplayHeight;
window.setAttributes(attrs);
showNavbarButtons(false);
}
private void onMoveEnd() {
if (mFinishRunnable != null) {
mFinishRunnable.run();
return;
}
int draggingEndY = mActivity.getWindow().getAttributes().y;
if (mDraggingStartY >= 0 && mDraggingStartY != draggingEndY) {
RecordHistogram.recordEnumeratedHistogram("CustomTabs.ResizeType",
mDraggingStartY < draggingEndY ? ResizeType.MINIMIZATION : ResizeType.EXPANSION,
ResizeType.COUNT);
}
hideSpinnerView();
showNavbarButtons(true);
if (mAlwaysShowNavbarButtons) {
finishResizing();
} else {
// Give a small delay in restoring the window to avoid the flashing artifact
// at the navigation bar area.
new Handler().postDelayed(this::finishResizing, NAVBAR_BUTTON_RESTORE_DELAY_MS);
// Temporarily disables user input until the window is restored.
mTargetStatus = mStatus;
mStatus = HeightStatus.TRANSITION;
}
updateShadowOffset();
if (mSoftKeyboardRunnable != null) {
mSoftKeyboardRunnable.run();
mSoftKeyboardRunnable = null;
}
}
private void finishResizing() {
Window window = mActivity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
positionAtHeight(mDisplayHeight - window.getAttributes().y);
maybeInvokeResizeCallback();
mStatus = mTargetStatus;
if (mFinishRunnable != null) {
Runnable oldFinishRunnable = mFinishRunnable;
mFinishRunnable = null;
handleCloseAnimation(oldFinishRunnable);
}
}
private void hideSpinnerView() {
// TODO(crbug.com/1328555): Look into observing a view resize event to ensure the fade
// animation can always cover the transition artifact.
if (isSpinnerVisible()) {
mSpinnerView.animate()
.alpha(0f)
.setDuration(SPINNER_FADEOUT_DURATION_MS)
.setListener(mSpinnerFadeoutAnimatorListener);
}
}
private void showSpinnerView() {
if (mSpinnerView != null) {
centerSpinnerVertically((ViewGroup.LayoutParams) mSpinnerView.getLayoutParams());
} else {
mSpinnerView = new ImageView(mActivity);
mSpinnerView.setElevation(
mActivity.getResources().getDimensionPixelSize(R.dimen.custom_tabs_elevation));
mSpinnerView.setBackgroundColor(mActivity.getColor(R.color.window_background_color));
// Toolbar should not be hidden by spinner screen.
ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(MATCH_PARENT, 0);
int topMargin = mToolbarView.getHeight();
lp.setMargins(0, topMargin, 0, 0);
mSpinner = new CircularProgressDrawable(mActivity);
mSpinner.setStyle(CircularProgressDrawable.LARGE);
mSpinnerView.setImageDrawable(mSpinner);
mSpinnerView.setScaleType(ImageView.ScaleType.CENTER);
int[] colorList = new int[1];
colorList[0] = mActivity.getColor(R.color.default_bg_color_blue);
mSpinner.setColorSchemeColors(colorList);
centerSpinnerVertically(lp);
}
// Spinner view is added to CoordinatorLayoutForPointer (not R.id.content) to obscure
// the flickering at the beginning of dragging action.
if (mSpinnerView.getParent() == null) mCoordinatorLayout.addView(mSpinnerView);
mSpinnerView.clearAnimation();
mSpinnerView.setAlpha(0.f);
mSpinnerView.setVisibility(View.VISIBLE);
mSpinnerView.animate().alpha(1.f).setDuration(SPINNER_FADEIN_DURATION_MS).setListener(null);
mSpinner.start();
}
private void centerSpinnerVertically(ViewGroup.LayoutParams lp) {
int toolbarHeight = mToolbarView.getHeight();
int cctHeight = mDisplayHeight - mActivity.getWindow().getAttributes().y - toolbarHeight;
lp.height = cctHeight;
mSpinnerView.setLayoutParams(lp);
}
private void maybeInvokeResizeCallback() {
WindowManager.LayoutParams attrs = mActivity.getWindow().getAttributes();
if (mHeight != attrs.height && attrs.height > 0) {
mOnResizedCallback.onResized(attrs.height);
mHeight = attrs.height;
}
}
private void changeVisibilityNavbarButtons(boolean show) {
View decorView = mActivity.getWindow().getDecorView();
WindowInsetsControllerCompat controller =
WindowCompat.getInsetsController(mActivity.getWindow(), decorView);
if (show) {
controller.show(WindowInsetsCompat.Type.navigationBars());
} else {
// Can we remove the slow fade-out animation?
controller.hide(WindowInsetsCompat.Type.navigationBars());
}
// If we are no longer hiding the navbar buttons we don't need to take control over the
// insets animation.
if (!mAlwaysShowNavbarButtons) {
// Take over the control of insets animation after the #show / #hide. This call needs to
// happen after the #show / #hide call to work correctly.
mNavbarTransitionController.setShow(show);
controller.controlWindowInsetsAnimation(WindowInsetsCompat.Type.navigationBars(),
/*durationMillis*/ 1, null, null, mNavbarTransitionController);
}
}
private void showNavbarButtons(boolean show) {
if (mAlwaysShowNavbarButtons) {
// Resizing while the navbar buttons are visible, at times, flashes the host app.
// http://crbug/1360425 fixed this for when the navbar buttons are hidden, so taking
// advantage of that fix by hiding for a bit the navigation buttons, during the time the
// flashing usually occurs. The navbar buttons need to be visible while resizing so that
// the immersive mode confirmation dialog is not displayed, as fixed with
// http://crbug/1360453
// TODO: http://crbug/1373984 for follow-up on long term solution for fixing host app
// flashing issues.
if (!show) {
changeVisibilityNavbarButtons(false);
new Handler().postDelayed(() -> {
changeVisibilityNavbarButtons(true);
}, NAVBAR_BUTTON_HIDE_SHOW_DELAY_MS);
}
} else {
changeVisibilityNavbarButtons(show);
}
}
private @Px int getFullyExpandedY() {
return mStatusbarHeight;
}
@VisibleForTesting
@Px
int getFullyExpandedYWithAdjustment() {
// Adding |mFullyExpandedAdjustmentHeight| to the y coordinate because the
// coordinates system's origin is at the top left and y is growing in downward, larger y
// means smaller height of the bottom sheet CCT.
return getFullyExpandedY() + mFullyExpandedAdjustmentHeight;
}
// CustomTabHeightStrategy implementation
@Override
public boolean changeBackgroundColorForResizing() {
// Need to return true to keep the transparent background we set in the init step.
return true;
}
@Override
public void handleCloseAnimation(Runnable finishRunnable) {
if (mFinishRunnable != null) return;
mFinishRunnable = finishRunnable;
// Tapping the close button while in transition state should be ignored.
// Delay it till the height settles in to either top/initial state, where the animation
// begins when it detects the presence of |mFinishRunnable|.
if (mStatus == HeightStatus.TRANSITION) return;
animateTabTo(HeightStatus.CLOSE);
}
// DragEventCallback implementation
@Override
public void onDragStart(int y) {
onMoveStart();
Window window = mActivity.getWindow();
mDraggingStartY = window.getAttributes().y;
mOffsetY = mDraggingStartY - y;
mStopShowingSpinner = false;
}
@Override
public void onDragMove(int y) {
updateWindowPos((int) (y + mOffsetY));
}
@Override
public boolean onDragEnd(int flingDistance) {
int currentY = mActivity.getWindow().getAttributes().y;
int finalY = currentY + flingDistance;
int topY = getFullyExpandedYWithAdjustment();
int initialY = initialY();
int bottomY = mDisplayHeight - mNavbarHeight;
if (finalY < initialY) { // Move up
animateTabTo(Math.abs(topY - finalY) < Math.abs(finalY - initialY)
? HeightStatus.TOP
: HeightStatus.INITIAL_HEIGHT);
return true;
} else { // Move down
// Prevents skipping initial state when swiping from the top.
if (mStatus == HeightStatus.TOP) finalY = Math.min(initialY, finalY);
if (Math.abs(initialY - finalY) < Math.abs(finalY - bottomY)) {
animateTabTo(HeightStatus.INITIAL_HEIGHT);
return true;
}
}
// Tab is being closed. Animation is initiated in |handleCloseAnimation()|.
return false;
}
// FullscreenManager.Observer implementation
@Override
public void onEnterFullscreen(Tab tab, FullscreenOptions options) {
if (isFullscreen()) return;
WindowManager.LayoutParams attrs = mActivity.getWindow().getAttributes();
mFullscreenRestoreRect.set(attrs.x, attrs.y, attrs.width, attrs.height);
attrs.x = 0;
attrs.y = 0;
attrs.width = MATCH_PARENT;
attrs.height = MATCH_PARENT;
mActivity.getWindow().setAttributes(attrs);
setTopMargins(0, 0);
}
@Override
public void onExitFullscreen(Tab tab) {
if (!isFullscreen()) return;
WindowManager.LayoutParams attrs = mActivity.getWindow().getAttributes();
attrs.x = mFullscreenRestoreRect.left;
attrs.y = mFullscreenRestoreRect.top;
attrs.width = mFullscreenRestoreRect.right;
attrs.height = mFullscreenRestoreRect.bottom;
mActivity.getWindow().setAttributes(attrs);
updateShadowOffset();
// Status/navigation bar are not restored on T+. This makes host app visible
// at the area. To work around this, simulate user dragging the tab by 1 pixel
// upon exiting fullscreen.
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S) {
int startY = attrs.y;
new Handler().post(() -> {
onDragStart(startY);
onDragMove(startY + 1);
onDragEnd(0);
});
}
}
@Override
public void destroy() {
mFullscreenManager.removeObserver(this);
}
@VisibleForTesting
void setMockViewForTesting(LinearLayout navbar, ImageView spinnerView,
CircularProgressDrawable spinner, View toolbar, View toolbarCoordinator) {
mNavbar = navbar;
mSpinnerView = spinnerView;
mSpinner = spinner;
mToolbarView = toolbar;
mToolbarCoordinator = toolbarCoordinator;
mPositionUpdater = this::updatePosition;
onPostInflationStartup();
}
@VisibleForTesting
int getNavbarHeightForTesting() {
return mNavbarHeight;
}
@VisibleForTesting
PartialCustomTabHandleStrategy createHandleStrategyForTesting() {
// Pass null for context because we don't depend on the GestureDetector inside as we invoke
// MotionEvents directly in the tests.
return new PartialCustomTabHandleStrategy(null, this::isFullHeight, () -> mStatus, this);
}
@VisibleForTesting
void setToolbarColorForTesting(int toolbarColor) {
mToolbarColor = toolbarColor;
}
// Reusable class used to control nav bar transitioning, to make the transition instant.
private static class NavBarTransitionController
implements WindowInsetsAnimationControlListenerCompat {
private boolean mShown;
void setShow(boolean show) {
mShown = show;
}
@Override
public void onReady(@NonNull WindowInsetsAnimationControllerCompat controller, int types) {
controller.finish(mShown);
}
@Override
public void onFinished(WindowInsetsAnimationControllerCompat controller) {}
@Override
public void onCancelled(WindowInsetsAnimationControllerCompat controller) {}
}