-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPagedView.java
2001 lines (1727 loc) · 74.9 KB
/
PagedView.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 (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3;
import static com.android.app.animation.Interpolators.SCROLL;
import static com.android.launcher3.compat.AccessibilityManagerCompat.isAccessibilityEnabled;
import static com.android.launcher3.compat.AccessibilityManagerCompat.isObservedEventType;
import static com.android.launcher3.testing.shared.TestProtocol.SCROLL_FINISHED_MESSAGE;
import static com.android.launcher3.touch.OverScroll.OVERSCROLL_DAMP_FACTOR;
import static com.android.launcher3.touch.PagedOrientationHandler.VIEW_SCROLL_BY;
import static com.android.launcher3.touch.PagedOrientationHandler.VIEW_SCROLL_TO;
import android.animation.LayoutTransition;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.OverScroller;
import android.widget.ScrollView;
import androidx.annotation.Nullable;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.pageindicators.PageIndicator;
import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.touch.PagedOrientationHandler.ChildBounds;
import com.android.launcher3.util.EdgeEffectCompat;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ActivityContext;
import java.util.ArrayList;
import java.util.function.Consumer;
/**
* An abstraction of the original Workspace which supports browsing through a
* sequential list of "pages"
*/
public abstract class PagedView<T extends View & PageIndicator> extends ViewGroup {
private static final String TAG = "PagedView";
private static final boolean DEBUG = false;
public static final boolean DEBUG_FAILED_QUICKSWITCH = false;
public static final int ACTION_MOVE_ALLOW_EASY_FLING = MotionEvent.ACTION_MASK - 1;
public static final int INVALID_PAGE = -1;
protected static final ComputePageScrollsLogic SIMPLE_SCROLL_LOGIC = (v) -> v.getVisibility() != GONE;
private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
// The page is moved more than halfway, automatically move to the next page on touch up.
private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
private static final float MAX_SCROLL_PROGRESS = 1.0f;
private boolean mFreeScroll = false;
private int mFlingThresholdVelocity;
private int mEasyFlingThresholdVelocity;
private int mMinFlingVelocity;
private int mMinSnapVelocity;
private int mPageSnapAnimationDuration;
protected boolean mFirstLayout = true;
@ViewDebug.ExportedProperty(category = "launcher")
protected int mCurrentPage;
// Difference between current scroll position and mCurrentPage's page scroll. Used to maintain
// relative scroll position unchanged in updateCurrentPageScroll. Cleared when snapping to a
// page.
protected int mCurrentPageScrollDiff;
// The current page the PagedView is scrolling over on it's way to the destination page.
protected int mCurrentScrollOverPage;
@ViewDebug.ExportedProperty(category = "launcher")
protected int mNextPage = INVALID_PAGE;
protected int mMaxScroll;
protected int mMinScroll;
protected OverScroller mScroller;
private VelocityTracker mVelocityTracker;
protected int mPageSpacing = 0;
private float mDownMotionX;
private float mDownMotionY;
private float mDownMotionPrimary;
private int mLastMotion;
private float mTotalMotion;
// Used in special cases where the fling checks can be relaxed for an intentional gesture
private boolean mAllowEasyFling;
private PagedOrientationHandler mOrientationHandler =
PagedOrientationHandler.DEFAULT;
private final ArrayList<Runnable> mOnPageScrollsInitializedCallbacks = new ArrayList<>();
// We should always check pageScrollsInitialized() is true when using mPageScrolls.
@Nullable protected int[] mPageScrolls = null;
private boolean mIsBeingDragged;
// The amount of movement to begin scrolling
protected int mTouchSlop;
// The amount of movement to begin paging
protected int mPageSlop;
private int mMaximumVelocity;
protected boolean mAllowOverScroll = true;
protected static final int INVALID_POINTER = -1;
protected int mActivePointerId = INVALID_POINTER;
protected boolean mIsPageInTransition = false;
private Runnable mOnPageTransitionEndCallback;
// Page Indicator
@Thunk int mPageIndicatorViewId;
protected T mPageIndicator;
protected final Rect mInsets = new Rect();
protected boolean mIsRtl;
// Similar to the platform implementation of isLayoutValid();
protected boolean mIsLayoutValid;
private int[] mTmpIntPair = new int[2];
protected EdgeEffectCompat mEdgeGlowLeft;
protected EdgeEffectCompat mEdgeGlowRight;
public PagedView(Context context) {
this(context, null);
}
public PagedView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PagedView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.PagedView, defStyle, 0);
mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
a.recycle();
setHapticFeedbackEnabled(false);
mIsRtl = Utilities.isRtl(getResources());
mScroller = new OverScroller(context, SCROLL);
mCurrentPage = 0;
mCurrentScrollOverPage = 0;
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = configuration.getScaledTouchSlop();
mPageSlop = configuration.getScaledPagingTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
updateVelocityValues();
initEdgeEffect();
setDefaultFocusHighlightEnabled(false);
setWillNotDraw(false);
}
protected void initEdgeEffect() {
mEdgeGlowLeft = new EdgeEffectCompat(getContext());
mEdgeGlowRight = new EdgeEffectCompat(getContext());
}
public void initParentViews(View parent) {
if (mPageIndicatorViewId > -1) {
mPageIndicator = parent.findViewById(mPageIndicatorViewId);
mPageIndicator.setMarkersCount(getChildCount() / getPanelCount());
}
}
public T getPageIndicator() {
return mPageIndicator;
}
/**
* Returns the index of the currently displayed page. When in free scroll mode, this is the page
* that the user was on before entering free scroll mode (e.g. the home screen page they
* long-pressed on to enter the overview). Try using {@link #getDestinationPage()}
* to get the page the user is currently scrolling over.
*/
public int getCurrentPage() {
return mCurrentPage;
}
/**
* Returns the index of page to be shown immediately afterwards.
*/
public int getNextPage() {
return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
}
public int getPageCount() {
return getChildCount();
}
public View getPageAt(int index) {
return getChildAt(index);
}
protected PagedOrientationHandler getPagedOrientationHandler() {
return mOrientationHandler;
}
protected void setOrientationHandler(PagedOrientationHandler orientationHandler) {
this.mOrientationHandler = orientationHandler;
}
/**
* Updates the scroll of the current page immediately to its final scroll position. We use this
* in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
* the previous tab page.
*/
protected void updateCurrentPageScroll() {
// If the current page is invalid, just reset the scroll position to zero
int newPosition = 0;
if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
newPosition = getScrollForPage(mCurrentPage) + mCurrentPageScrollDiff;
}
mOrientationHandler.setPrimary(this, VIEW_SCROLL_TO, newPosition);
mScroller.startScroll(mScroller.getCurrX(), 0, newPosition - mScroller.getCurrX(), 0);
forceFinishScroller();
}
/**
* Immediately finishes any overscroll effect and jumps to the end of the scroller animation.
*/
public void abortScrollerAnimation() {
mEdgeGlowLeft.finish();
mEdgeGlowRight.finish();
abortScrollerAnimation(true);
}
protected void onScrollerAnimationAborted() {
// No-Op
}
private void abortScrollerAnimation(boolean resetNextPage) {
mScroller.abortAnimation();
onScrollerAnimationAborted();
// We need to clean up the next page here to avoid computeScrollHelper from
// updating current page on the pass.
if (resetNextPage) {
mNextPage = INVALID_PAGE;
pageEndTransition();
}
}
/**
* Immediately finishes any in-progress scroll, maintaining the current position. Also sets
* mNextPage = INVALID_PAGE and calls pageEndTransition().
*/
public void forceFinishScroller() {
mScroller.forceFinished(true);
// We need to clean up the next page here to avoid computeScrollHelper from
// updating current page on the pass.
mNextPage = INVALID_PAGE;
pageEndTransition();
}
private int validateNewPage(int newPage) {
newPage = ensureWithinScrollBounds(newPage);
// Ensure that it is clamped by the actual set of children in all cases
newPage = Utilities.boundToRange(newPage, 0, getPageCount() - 1);
if (getPanelCount() > 1) {
// Always return left most panel as new page
newPage = getLeftmostVisiblePageForIndex(newPage);
}
return newPage;
}
/**
* In most cases where panelCount is 1, this method will just return the page index that was
* passed in.
* But for example when two panel home is enabled we might need the leftmost visible page index
* because that page is the current page.
*/
public int getLeftmostVisiblePageForIndex(int pageIndex) {
int panelCount = getPanelCount();
return pageIndex - pageIndex % panelCount;
}
/**
* Returns the number of pages that are shown at the same time.
*/
protected int getPanelCount() {
return 1;
}
/**
* Returns an IntSet with the indices of the currently visible pages
*/
public IntSet getVisiblePageIndices() {
return getPageIndices(mCurrentPage);
}
/**
* In case the panelCount is 1 this just returns the same page index in an IntSet.
* But in cases where the panelCount > 1 this will return all the page indices that belong
* together, i.e. on the Workspace they are next to each other and shown at the same time.
*/
private IntSet getPageIndices(int pageIndex) {
// we want to make sure the pageIndex is the leftmost page
pageIndex = getLeftmostVisiblePageForIndex(pageIndex);
IntSet pageIndices = new IntSet();
int panelCount = getPanelCount();
int pageCount = getPageCount();
for (int page = pageIndex; page < pageIndex + panelCount && page < pageCount; page++) {
pageIndices.add(page);
}
return pageIndices;
}
/**
* Returns an IntSet with the indices of the neighbour pages that are in the focus direction.
*/
private IntSet getNeighbourPageIndices(int focus) {
int panelCount = getPanelCount();
// getNextPage is more reliable than getCurrentPage
int currentPage = getNextPage();
int nextPage;
if (focus == View.FOCUS_LEFT) {
nextPage = currentPage - panelCount;
} else if (focus == View.FOCUS_RIGHT) {
nextPage = currentPage + panelCount;
} else {
// no neighbours to other directions
return new IntSet();
}
nextPage = validateNewPage(nextPage);
if (nextPage == currentPage) {
// We reached the end of the pages
return new IntSet();
}
return getPageIndices(nextPage);
}
/**
* Executes the callback against each visible page
*/
public void forEachVisiblePage(Consumer<View> callback) {
getVisiblePageIndices().forEach(pageIndex -> {
View page = getPageAt(pageIndex);
if (page != null) {
callback.accept(page);
}
});
}
/**
* Returns true if the view is on one of the current pages, false otherwise.
*/
public boolean isVisible(View child) {
return isVisible(indexOfChild(child));
}
/**
* Returns true if the page with the given index is currently visible, false otherwise.
*/
private boolean isVisible(int pageIndex) {
return getLeftmostVisiblePageForIndex(pageIndex) == mCurrentPage;
}
/**
* @return The closest page to the provided page that is within mMinScrollX and mMaxScrollX.
*/
private int ensureWithinScrollBounds(int page) {
int dir = !mIsRtl ? 1 : - 1;
int currScroll = getScrollForPage(page);
int prevScroll;
while (currScroll < mMinScroll) {
page += dir;
prevScroll = currScroll;
currScroll = getScrollForPage(page);
if (currScroll <= prevScroll) {
Log.e(TAG, "validateNewPage: failed to find a page > mMinScrollX");
break;
}
}
while (currScroll > mMaxScroll) {
page -= dir;
prevScroll = currScroll;
currScroll = getScrollForPage(page);
if (currScroll >= prevScroll) {
Log.e(TAG, "validateNewPage: failed to find a page < mMaxScrollX");
break;
}
}
return page;
}
public void setCurrentPage(int currentPage) {
setCurrentPage(currentPage, INVALID_PAGE);
}
/**
* Sets the current page.
*/
public void setCurrentPage(int currentPage, int overridePrevPage) {
if (!mScroller.isFinished()) {
abortScrollerAnimation(true);
}
// don't introduce any checks like mCurrentPage == currentPage here-- if we change the
// the default
if (getChildCount() == 0) {
return;
}
int prevPage = overridePrevPage != INVALID_PAGE ? overridePrevPage : mCurrentPage;
mCurrentPage = validateNewPage(currentPage);
mCurrentScrollOverPage = mCurrentPage;
updateCurrentPageScroll();
notifyPageSwitchListener(prevPage);
invalidate();
}
/**
* Should be called whenever the page changes. In the case of a scroll, we wait until the page
* has settled.
*/
protected void notifyPageSwitchListener(int prevPage) {
updatePageIndicator();
}
private void updatePageIndicator() {
if (mPageIndicator != null) {
mPageIndicator.setActiveMarker(getNextPage());
}
}
protected void pageBeginTransition() {
if (!mIsPageInTransition) {
mIsPageInTransition = true;
onPageBeginTransition();
}
}
protected void pageEndTransition() {
if (mIsPageInTransition && !mIsBeingDragged && mScroller.isFinished()
&& (!isShown() || (mEdgeGlowLeft.isFinished() && mEdgeGlowRight.isFinished()))) {
mIsPageInTransition = false;
onPageEndTransition();
}
}
@Override
public void onVisibilityAggregated(boolean isVisible) {
pageEndTransition();
super.onVisibilityAggregated(isVisible);
}
/**
* Returns true if the page is in the middle of transition to another page
*/
public boolean isPageInTransition() {
return mIsPageInTransition;
}
/**
* Called when the page starts moving as part of the scroll. Subclasses can override this
* to provide custom behavior during animation.
*/
protected void onPageBeginTransition() {
}
/**
* Called when the page ends moving as part of the scroll. Subclasses can override this
* to provide custom behavior during animation.
*/
protected void onPageEndTransition() {
mCurrentPageScrollDiff = 0;
AccessibilityManagerCompat.sendTestProtocolEventToTest(getContext(),
SCROLL_FINISHED_MESSAGE);
AccessibilityManagerCompat.sendCustomAccessibilityEvent(getPageAt(mCurrentPage),
AccessibilityEvent.TYPE_VIEW_FOCUSED, null);
if (mOnPageTransitionEndCallback != null) {
mOnPageTransitionEndCallback.run();
mOnPageTransitionEndCallback = null;
}
}
/**
* Sets a callback to run once when the scrolling finishes. If there is currently
* no page in transition, then the callback is called immediately.
*/
public void setOnPageTransitionEndCallback(@Nullable Runnable callback) {
if (mIsPageInTransition || callback == null) {
mOnPageTransitionEndCallback = callback;
} else {
callback.run();
}
}
@Override
public void scrollTo(int x, int y) {
x = Utilities.boundToRange(x,
mOrientationHandler.getPrimaryValue(mMinScroll, 0), mMaxScroll);
y = Utilities.boundToRange(y,
mOrientationHandler.getPrimaryValue(0, mMinScroll), mMaxScroll);
super.scrollTo(x, y);
}
private void sendScrollAccessibilityEvent() {
if (isObservedEventType(getContext(), AccessibilityEvent.TYPE_VIEW_SCROLLED)) {
if (mCurrentPage != getNextPage()) {
AccessibilityEvent ev =
AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
ev.setScrollable(true);
ev.setScrollX(getScrollX());
ev.setScrollY(getScrollY());
mOrientationHandler.setMaxScroll(ev, mMaxScroll);
sendAccessibilityEventUnchecked(ev);
}
}
}
protected void announcePageForAccessibility() {
if (isAccessibilityEnabled(getContext())) {
// Notify the user when the page changes
announceForAccessibility(getCurrentPageDescription());
}
}
protected boolean computeScrollHelper() {
if (mScroller.computeScrollOffset()) {
// Don't bother scrolling if the page does not need to be moved
int oldPos = mOrientationHandler.getPrimaryScroll(this);
int newPos = mScroller.getCurrX();
if (oldPos != newPos) {
mOrientationHandler.setPrimary(this, VIEW_SCROLL_TO, mScroller.getCurrX());
}
if (mAllowOverScroll) {
if (newPos < mMinScroll && oldPos >= mMinScroll) {
mEdgeGlowLeft.onAbsorb((int) mScroller.getCurrVelocity());
abortScrollerAnimation(false);
onEdgeAbsorbingScroll();
} else if (newPos > mMaxScroll && oldPos <= mMaxScroll) {
mEdgeGlowRight.onAbsorb((int) mScroller.getCurrVelocity());
abortScrollerAnimation(false);
onEdgeAbsorbingScroll();
}
}
// If the scroller has scrolled to the final position and there is no edge effect, then
// finish the scroller to skip waiting for additional settling
int finalPos = mOrientationHandler.getPrimaryValue(mScroller.getFinalX(),
mScroller.getFinalY());
if (newPos == finalPos && mEdgeGlowLeft.isFinished() && mEdgeGlowRight.isFinished()) {
abortScrollerAnimation(false);
}
invalidate();
return true;
} else if (mNextPage != INVALID_PAGE) {
sendScrollAccessibilityEvent();
int prevPage = mCurrentPage;
mCurrentPage = validateNewPage(mNextPage);
mCurrentScrollOverPage = mCurrentPage;
mNextPage = INVALID_PAGE;
notifyPageSwitchListener(prevPage);
// We don't want to trigger a page end moving unless the page has settled
// and the user has stopped scrolling
if (!mIsBeingDragged) {
pageEndTransition();
}
if (canAnnouncePageDescription()) {
announcePageForAccessibility();
}
}
return false;
}
@Override
public void computeScroll() {
computeScrollHelper();
}
public int getExpectedHeight() {
return getMeasuredHeight();
}
public int getNormalChildHeight() {
return getExpectedHeight() - getPaddingTop() - getPaddingBottom()
- mInsets.top - mInsets.bottom;
}
public int getExpectedWidth() {
return getMeasuredWidth();
}
public int getNormalChildWidth() {
return getExpectedWidth() - getPaddingLeft() - getPaddingRight()
- mInsets.left - mInsets.right;
}
private void updateVelocityValues() {
Resources res = getResources();
mFlingThresholdVelocity = res.getDimensionPixelSize(R.dimen.fling_threshold_velocity);
mEasyFlingThresholdVelocity =
res.getDimensionPixelSize(R.dimen.easy_fling_threshold_velocity);
mMinFlingVelocity = res.getDimensionPixelSize(R.dimen.min_fling_velocity);
mMinSnapVelocity = res.getDimensionPixelSize(R.dimen.min_page_snap_velocity);
mPageSnapAnimationDuration = res.getInteger(R.integer.config_pageSnapAnimationDuration);
onVelocityValuesUpdated();
}
protected void onVelocityValuesUpdated() {
// Overridden in RecentsView
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
updateVelocityValues();
}
@Override
public void requestLayout() {
mIsLayoutValid = false;
super.requestLayout();
}
@Override
public void forceLayout() {
mIsLayoutValid = false;
super.forceLayout();
}
private int getPageWidthSize(int widthSize) {
// It's necessary to add the padding back because it is remove when measuring children,
// like when MeasureSpec.getSize in CellLayout.
return (widthSize - mInsets.left - mInsets.right - getPaddingLeft() - getPaddingRight())
/ getPanelCount() + getPaddingLeft() + getPaddingRight();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getChildCount() == 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// We measure the dimensions of the PagedView to be larger than the pages so that when we
// zoom out (and scale down), the view is still contained in the parent
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// Return early if we aren't given a proper dimension
if (widthSize <= 0 || heightSize <= 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// The children are given the same width and height as the workspace
// unless they were set to WRAP_CONTENT
if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
int myWidthSpec = MeasureSpec.makeMeasureSpec(
getPageWidthSize(widthSize), MeasureSpec.EXACTLY);
int myHeightSpec = MeasureSpec.makeMeasureSpec(
heightSize - mInsets.top - mInsets.bottom, MeasureSpec.EXACTLY);
// measureChildren takes accounts for content padding, we only need to care about extra
// space due to insets.
measureChildren(myWidthSpec, myHeightSpec);
setMeasuredDimension(widthSize, heightSize);
}
/** Returns true iff this PagedView's scroll amounts are initialized to each page index. */
protected boolean isPageScrollsInitialized() {
return mPageScrolls != null && mPageScrolls.length == getChildCount();
}
/**
* Queues the given callback to be run once {@code mPageScrolls} has been initialized.
*/
public void runOnPageScrollsInitialized(Runnable callback) {
mOnPageScrollsInitializedCallbacks.add(callback);
if (isPageScrollsInitialized()) {
onPageScrollsInitialized();
}
}
protected void onPageScrollsInitialized() {
for (Runnable callback : mOnPageScrollsInitializedCallbacks) {
callback.run();
}
mOnPageScrollsInitializedCallbacks.clear();
}
@SuppressLint("DrawAllocation")
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mIsLayoutValid = true;
final int childCount = getChildCount();
int[] pageScrolls = mPageScrolls;
boolean pageScrollChanged = false;
if (!isPageScrollsInitialized()) {
pageScrolls = new int[childCount];
pageScrollChanged = true;
}
if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
pageScrollChanged |= getPageScrolls(pageScrolls, true, SIMPLE_SCROLL_LOGIC);
mPageScrolls = pageScrolls;
if (childCount == 0) {
onPageScrollsInitialized();
return;
}
final LayoutTransition transition = getLayoutTransition();
// If the transition is running defer updating max scroll, as some empty pages could
// still be present, and a max scroll change could cause sudden jumps in scroll.
if (transition != null && transition.isRunning()) {
transition.addTransitionListener(new LayoutTransition.TransitionListener() {
@Override
public void startTransition(LayoutTransition transition, ViewGroup container,
View view, int transitionType) { }
@Override
public void endTransition(LayoutTransition transition, ViewGroup container,
View view, int transitionType) {
// Wait until all transitions are complete.
if (!transition.isRunning()) {
transition.removeTransitionListener(this);
updateMinAndMaxScrollX();
}
}
});
} else {
updateMinAndMaxScrollX();
}
if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < childCount) {
updateCurrentPageScroll();
mFirstLayout = false;
}
if (mScroller.isFinished() && pageScrollChanged) {
// TODO(b/246283207): Remove logging once root cause of flake detected.
if (Utilities.isRunningInTestHarness() && !(this instanceof Workspace)) {
Log.d("b/246283207", TAG + "#onLayout() -> "
+ "if(mScroller.isFinished() && pageScrollChanged) -> getNextPage(): "
+ getNextPage() + ", getScrollForPage(getNextPage()): "
+ getScrollForPage(getNextPage()));
}
setCurrentPage(getNextPage());
}
onPageScrollsInitialized();
}
/**
* Initializes {@code outPageScrolls} with scroll positions for view at that index. The length
* of {@code outPageScrolls} should be same as the the childCount
*/
protected boolean getPageScrolls(int[] outPageScrolls, boolean layoutChildren,
ComputePageScrollsLogic scrollLogic) {
final int childCount = getChildCount();
final int startIndex = mIsRtl ? childCount - 1 : 0;
final int endIndex = mIsRtl ? -1 : childCount;
final int delta = mIsRtl ? -1 : 1;
final int pageCenter = mOrientationHandler.getCenterForPage(this, mInsets);
final int scrollOffsetStart = mOrientationHandler.getScrollOffsetStart(this, mInsets);
final int scrollOffsetEnd = mOrientationHandler.getScrollOffsetEnd(this, mInsets);
boolean pageScrollChanged = false;
int panelCount = getPanelCount();
for (int i = startIndex, childStart = scrollOffsetStart; i != endIndex; i += delta) {
final View child = getPageAt(i);
if (scrollLogic.shouldIncludeView(child)) {
ChildBounds bounds = mOrientationHandler.getChildBounds(child, childStart,
pageCenter, layoutChildren);
final int primaryDimension = bounds.primaryDimension;
final int childPrimaryEnd = bounds.childPrimaryEnd;
// In case the pages are of different width, align the page to left edge for non-RTL
// or right edge for RTL.
final int pageScroll =
mIsRtl ? childPrimaryEnd - scrollOffsetEnd : childStart - scrollOffsetStart;
// If there's more than one panel, only update scroll on leftmost panel.
if (outPageScrolls[i] != pageScroll
&& (panelCount <= 1 || i == getLeftmostVisiblePageForIndex(i))) {
pageScrollChanged = true;
outPageScrolls[i] = pageScroll;
}
childStart += primaryDimension + getChildGap(i, i + delta);
// This makes sure that the space is added after the page, not after each panel
int lastPanel = mIsRtl ? 0 : panelCount - 1;
if (i % panelCount == lastPanel) {
childStart += mPageSpacing;
}
}
}
if (panelCount > 1) {
for (int i = 0; i < childCount; i++) {
// In case we have multiple panels, always use leftmost panel's page scroll for all
// panels on the screen.
int adjustedScroll = outPageScrolls[getLeftmostVisiblePageForIndex(i)];
if (outPageScrolls[i] != adjustedScroll) {
outPageScrolls[i] = adjustedScroll;
pageScrollChanged = true;
}
}
}
return pageScrollChanged;
}
protected int getChildGap(int fromIndex, int toIndex) {
return 0;
}
protected void updateMinAndMaxScrollX() {
mMinScroll = computeMinScroll();
mMaxScroll = computeMaxScroll();
}
protected int computeMinScroll() {
return 0;
}
protected int computeMaxScroll() {
int childCount = getChildCount();
if (childCount > 0) {
final int index = mIsRtl ? 0 : childCount - 1;
return getScrollForPage(index);
} else {
return 0;
}
}
public void setPageSpacing(int pageSpacing) {
mPageSpacing = pageSpacing;
requestLayout();
}
public int getPageSpacing() {
return mPageSpacing;
}
private void dispatchPageCountChanged() {
if (mPageIndicator != null) {
mPageIndicator.setMarkersCount(getChildCount() / getPanelCount());
}
// This ensures that when children are added, they get the correct transforms / alphas
// in accordance with any scroll effects.
invalidate();
}
@Override
public void onViewAdded(View child) {
super.onViewAdded(child);
dispatchPageCountChanged();
}
@Override
public void onViewRemoved(View child) {
super.onViewRemoved(child);
runOnPageScrollsInitialized(() -> {
mCurrentPage = validateNewPage(mCurrentPage);
mCurrentScrollOverPage = mCurrentPage;
});
dispatchPageCountChanged();
}
protected int getChildOffset(int index) {
if (index < 0 || index > getChildCount() - 1) return 0;
View pageAtIndex = getPageAt(index);
return mOrientationHandler.getChildStart(pageAtIndex);
}
protected int getChildVisibleSize(int index) {
View layout = getPageAt(index);
return mOrientationHandler.getMeasuredSize(layout);
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
int page = indexOfChild(child);
if (!isVisible(page) || !mScroller.isFinished()) {
if (immediate) {
setCurrentPage(page);
} else {
snapToPage(page);
}
return true;
}
return false;
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
int focusablePage;
if (mNextPage != INVALID_PAGE) {
focusablePage = mNextPage;
} else {
focusablePage = mCurrentPage;
}
View v = getPageAt(focusablePage);
if (v != null) {
return v.requestFocus(direction, previouslyFocusedRect);
}
return false;
}
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
if (super.dispatchUnhandledMove(focused, direction)) {
return true;
}
if (mIsRtl) {
if (direction == View.FOCUS_LEFT) {
direction = View.FOCUS_RIGHT;
} else if (direction == View.FOCUS_RIGHT) {
direction = View.FOCUS_LEFT;
}
}
int currentPage = getNextPage();
int closestNeighbourIndex = -1;
int closestNeighbourDistance = Integer.MAX_VALUE;
// Find the closest neighbour page
for (int neighbourPageIndex : getNeighbourPageIndices(direction)) {
int distance = Math.abs(neighbourPageIndex - currentPage);
if (closestNeighbourDistance > distance) {
closestNeighbourDistance = distance;
closestNeighbourIndex = neighbourPageIndex;
}
}
if (closestNeighbourIndex != -1) {
View page = getPageAt(closestNeighbourIndex);
snapToPage(closestNeighbourIndex);
page.requestFocus(direction);
return true;
}
return false;
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
return;
}
// nextPage is more reliable when multiple control movements have been done in a short