PagedView.java revision e670159cfe255693f829f3e2857bbd8c52731e9d
1/*
2 * Copyright (C) 2012 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
17package com.android.launcher3;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.LayoutTransition;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
24import android.annotation.SuppressLint;
25import android.annotation.TargetApi;
26import android.content.Context;
27import android.content.res.TypedArray;
28import android.graphics.Canvas;
29import android.graphics.Matrix;
30import android.graphics.Rect;
31import android.graphics.RectF;
32import android.os.Build;
33import android.os.Bundle;
34import android.os.Parcel;
35import android.os.Parcelable;
36import android.util.AttributeSet;
37import android.util.DisplayMetrics;
38import android.util.Log;
39import android.view.InputDevice;
40import android.view.KeyEvent;
41import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewDebug;
46import android.view.ViewGroup;
47import android.view.ViewParent;
48import android.view.accessibility.AccessibilityEvent;
49import android.view.accessibility.AccessibilityManager;
50import android.view.accessibility.AccessibilityNodeInfo;
51import android.view.animation.Interpolator;
52import com.android.launcher3.util.LauncherEdgeEffect;
53import com.android.launcher3.util.Thunk;
54import java.util.ArrayList;
55
56/**
57 * An abstraction of the original Workspace which supports browsing through a
58 * sequential list of "pages"
59 */
60public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
61    private static final String TAG = "PagedView";
62    private static final boolean DEBUG = false;
63    protected static final int INVALID_PAGE = -1;
64
65    // the min drag distance for a fling to register, to prevent random page shifts
66    private static final int MIN_LENGTH_FOR_FLING = 25;
67
68    public static final int PAGE_SNAP_ANIMATION_DURATION = 750;
69    protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
70
71    private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
72    // The page is moved more than halfway, automatically move to the next page on touch up.
73    private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
74
75    private static final float MAX_SCROLL_PROGRESS = 1.0f;
76
77    // The following constants need to be scaled based on density. The scaled versions will be
78    // assigned to the corresponding member variables below.
79    private static final int FLING_THRESHOLD_VELOCITY = 500;
80    private static final int MIN_SNAP_VELOCITY = 1500;
81    private static final int MIN_FLING_VELOCITY = 250;
82
83    public static final int INVALID_RESTORE_PAGE = -1001;
84
85    private boolean mFreeScroll = false;
86    private int mFreeScrollMinScrollX = -1;
87    private int mFreeScrollMaxScrollX = -1;
88
89    protected int mFlingThresholdVelocity;
90    protected int mMinFlingVelocity;
91    protected int mMinSnapVelocity;
92
93    protected boolean mFirstLayout = true;
94    private int mNormalChildHeight;
95
96    @ViewDebug.ExportedProperty(category = "launcher")
97    protected int mCurrentPage;
98    protected int mRestorePage = INVALID_RESTORE_PAGE;
99    private int mChildCountOnLastLayout;
100
101    @ViewDebug.ExportedProperty(category = "launcher")
102    protected int mNextPage = INVALID_PAGE;
103    protected int mMaxScrollX;
104    protected LauncherScroller mScroller;
105    private Interpolator mDefaultInterpolator;
106    private VelocityTracker mVelocityTracker;
107    @Thunk int mPageSpacing = 0;
108
109    private float mParentDownMotionX;
110    private float mParentDownMotionY;
111    private float mDownMotionX;
112    private float mDownMotionY;
113    private float mDownScrollX;
114    private float mDragViewBaselineLeft;
115    private float mLastMotionX;
116    private float mLastMotionXRemainder;
117    private float mLastMotionY;
118    private float mTotalMotionX;
119    private int mLastScreenCenter = -1;
120
121    private boolean mCancelTap;
122
123    private int[] mPageScrolls;
124
125    protected final static int TOUCH_STATE_REST = 0;
126    protected final static int TOUCH_STATE_SCROLLING = 1;
127    protected final static int TOUCH_STATE_PREV_PAGE = 2;
128    protected final static int TOUCH_STATE_NEXT_PAGE = 3;
129    protected final static int TOUCH_STATE_REORDERING = 4;
130
131    protected int mTouchState = TOUCH_STATE_REST;
132    private boolean mForceScreenScrolled = false;
133
134    protected OnLongClickListener mLongClickListener;
135
136    protected int mTouchSlop;
137    private int mMaximumVelocity;
138    protected boolean mAllowOverScroll = true;
139    protected int[] mTempVisiblePagesRange = new int[2];
140
141    protected static final int INVALID_POINTER = -1;
142
143    protected int mActivePointerId = INVALID_POINTER;
144
145    private PageSwitchListener mPageSwitchListener;
146
147    // If true, modify alpha of neighboring pages as user scrolls left/right
148    protected boolean mFadeInAdjacentScreens = false;
149
150    protected boolean mIsPageMoving = false;
151
152    protected boolean mWasInOverscroll = false;
153
154    // Page Indicator
155    @Thunk int mPageIndicatorViewId;
156    @Thunk PageIndicator mPageIndicator;
157    // The viewport whether the pages are to be contained (the actual view may be larger than the
158    // viewport)
159    @ViewDebug.ExportedProperty(category = "launcher")
160    private Rect mViewport = new Rect();
161
162    // Reordering
163    // We use the min scale to determine how much to expand the actually PagedView measured
164    // dimensions such that when we are zoomed out, the view is not clipped
165    private static int REORDERING_DROP_REPOSITION_DURATION = 200;
166    @Thunk static int REORDERING_REORDER_REPOSITION_DURATION = 300;
167    private static int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
168
169    private float mMinScale = 1f;
170    private boolean mUseMinScale = false;
171    @Thunk View mDragView;
172    private Runnable mSidePageHoverRunnable;
173    @Thunk int mSidePageHoverIndex = -1;
174    // This variable's scope is only for the duration of startReordering() and endReordering()
175    private boolean mReorderingStarted = false;
176    // This variable's scope is for the duration of startReordering() and after the zoomIn()
177    // animation after endReordering()
178    private boolean mIsReordering;
179    // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
180    private static final int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
181    private int mPostReorderingPreZoomInRemainingAnimationCount;
182    private Runnable mPostReorderingPreZoomInRunnable;
183
184    // Convenience/caching
185    private static final Matrix sTmpInvMatrix = new Matrix();
186    private static final float[] sTmpPoint = new float[2];
187    private static final int[] sTmpIntPoint = new int[2];
188    private static final Rect sTmpRect = new Rect();
189    private static final RectF sTmpRectF = new RectF();
190
191    protected final Rect mInsets = new Rect();
192    protected final boolean mIsRtl;
193
194    // Edge effect
195    private final LauncherEdgeEffect mEdgeGlowLeft = new LauncherEdgeEffect();
196    private final LauncherEdgeEffect mEdgeGlowRight = new LauncherEdgeEffect();
197
198    public interface PageSwitchListener {
199        void onPageSwitch(View newPage, int newPageIndex);
200    }
201
202    public PagedView(Context context) {
203        this(context, null);
204    }
205
206    public PagedView(Context context, AttributeSet attrs) {
207        this(context, attrs, 0);
208    }
209
210    public PagedView(Context context, AttributeSet attrs, int defStyle) {
211        super(context, attrs, defStyle);
212
213        TypedArray a = context.obtainStyledAttributes(attrs,
214                R.styleable.PagedView, defStyle, 0);
215        mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
216        a.recycle();
217
218        setHapticFeedbackEnabled(false);
219        mIsRtl = Utilities.isRtl(getResources());
220        init();
221    }
222
223    /**
224     * Initializes various states for this workspace.
225     */
226    protected void init() {
227        mScroller = new LauncherScroller(getContext());
228        setDefaultInterpolator(new ScrollInterpolator());
229        mCurrentPage = 0;
230
231        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
232        mTouchSlop = configuration.getScaledPagingTouchSlop();
233        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
234
235        float density = getResources().getDisplayMetrics().density;
236        mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * density);
237        mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * density);
238        mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * density);
239        setOnHierarchyChangeListener(this);
240        setWillNotDraw(false);
241    }
242
243    protected void setEdgeGlowColor(int color) {
244        mEdgeGlowLeft.setColor(color);
245        mEdgeGlowRight.setColor(color);
246    }
247
248    protected void setDefaultInterpolator(Interpolator interpolator) {
249        mDefaultInterpolator = interpolator;
250        mScroller.setInterpolator(mDefaultInterpolator);
251    }
252
253    protected void onAttachedToWindow() {
254        super.onAttachedToWindow();
255
256        // Hook up the page indicator
257        ViewGroup parent = (ViewGroup) getParent();
258        ViewGroup grandParent = (ViewGroup) parent.getParent();
259        if (mPageIndicator == null && mPageIndicatorViewId > -1) {
260            mPageIndicator = (PageIndicator) grandParent.findViewById(mPageIndicatorViewId);
261            mPageIndicator.removeAllMarkers(true);
262
263            ArrayList<PageIndicator.PageMarkerResources> markers =
264                    new ArrayList<PageIndicator.PageMarkerResources>();
265            for (int i = 0; i < getChildCount(); ++i) {
266                markers.add(getPageIndicatorMarker(i));
267            }
268
269            mPageIndicator.addMarkers(markers, true);
270
271            OnClickListener listener = getPageIndicatorClickListener();
272            if (listener != null) {
273                mPageIndicator.setOnClickListener(listener);
274            }
275            mPageIndicator.setContentDescription(getPageIndicatorDescription());
276        }
277    }
278
279    protected String getPageIndicatorDescription() {
280        return getCurrentPageDescription();
281    }
282
283    protected OnClickListener getPageIndicatorClickListener() {
284        return null;
285    }
286
287    @Override
288    protected void onDetachedFromWindow() {
289        super.onDetachedFromWindow();
290        // Unhook the page indicator
291        mPageIndicator = null;
292    }
293
294    // Convenience methods to map points from self to parent and vice versa
295    private float[] mapPointFromViewToParent(View v, float x, float y) {
296        sTmpPoint[0] = x;
297        sTmpPoint[1] = y;
298        v.getMatrix().mapPoints(sTmpPoint);
299        sTmpPoint[0] += v.getLeft();
300        sTmpPoint[1] += v.getTop();
301        return sTmpPoint;
302    }
303    private float[] mapPointFromParentToView(View v, float x, float y) {
304        sTmpPoint[0] = x - v.getLeft();
305        sTmpPoint[1] = y - v.getTop();
306        v.getMatrix().invert(sTmpInvMatrix);
307        sTmpInvMatrix.mapPoints(sTmpPoint);
308        return sTmpPoint;
309    }
310
311    private void updateDragViewTranslationDuringDrag() {
312        if (mDragView != null) {
313            float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
314                    (mDragViewBaselineLeft - mDragView.getLeft());
315            float y = mLastMotionY - mDownMotionY;
316            mDragView.setTranslationX(x);
317            mDragView.setTranslationY(y);
318
319            if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
320                    + x + ", " + y);
321        }
322    }
323
324    public void setMinScale(float f) {
325        mMinScale = f;
326        mUseMinScale = true;
327        requestLayout();
328    }
329
330    @Override
331    public void setScaleX(float scaleX) {
332        super.setScaleX(scaleX);
333        if (isReordering(true)) {
334            float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
335            mLastMotionX = p[0];
336            mLastMotionY = p[1];
337            updateDragViewTranslationDuringDrag();
338        }
339    }
340
341    // Convenience methods to get the actual width/height of the PagedView (since it is measured
342    // to be larger to account for the minimum possible scale)
343    int getViewportWidth() {
344        return mViewport.width();
345    }
346    public int getViewportHeight() {
347        return mViewport.height();
348    }
349
350    // Convenience methods to get the offset ASSUMING that we are centering the pages in the
351    // PagedView both horizontally and vertically
352    int getViewportOffsetX() {
353        return (getMeasuredWidth() - getViewportWidth()) / 2;
354    }
355
356    int getViewportOffsetY() {
357        return (getMeasuredHeight() - getViewportHeight()) / 2;
358    }
359
360    PageIndicator getPageIndicator() {
361        return mPageIndicator;
362    }
363    protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
364        return new PageIndicator.PageMarkerResources();
365    }
366
367    /**
368     * Add a page change listener which will be called when a page is _finished_ listening.
369     *
370     */
371    public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
372        mPageSwitchListener = pageSwitchListener;
373        if (mPageSwitchListener != null) {
374            mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
375        }
376    }
377
378    /**
379     * Returns the index of the currently displayed page. When in free scroll mode, this is the page
380     * that the user was on before entering free scroll mode (e.g. the home screen page they
381     * long-pressed on to enter the overview). Try using {@link #getPageNearestToCenterOfScreen()}
382     * to get the page the user is currently scrolling over.
383     */
384    public int getCurrentPage() {
385        return mCurrentPage;
386    }
387
388    /**
389     * Returns the index of page to be shown immediately afterwards.
390     */
391    public int getNextPage() {
392        return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
393    }
394
395    public int getPageCount() {
396        return getChildCount();
397    }
398
399    public View getPageAt(int index) {
400        return getChildAt(index);
401    }
402
403    protected int indexToPage(int index) {
404        return index;
405    }
406
407    /**
408     * Updates the scroll of the current page immediately to its final scroll position.  We use this
409     * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
410     * the previous tab page.
411     */
412    protected void updateCurrentPageScroll() {
413        // If the current page is invalid, just reset the scroll position to zero
414        int newX = 0;
415        if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
416            newX = getScrollForPage(mCurrentPage);
417        }
418        scrollTo(newX, 0);
419        mScroller.setFinalX(newX);
420        forceFinishScroller();
421    }
422
423    private void abortScrollerAnimation(boolean resetNextPage) {
424        mScroller.abortAnimation();
425        // We need to clean up the next page here to avoid computeScrollHelper from
426        // updating current page on the pass.
427        if (resetNextPage) {
428            mNextPage = INVALID_PAGE;
429        }
430    }
431
432    private void forceFinishScroller() {
433        mScroller.forceFinished(true);
434        // We need to clean up the next page here to avoid computeScrollHelper from
435        // updating current page on the pass.
436        mNextPage = INVALID_PAGE;
437    }
438
439    private int validateNewPage(int newPage) {
440        int validatedPage = newPage;
441        // When in free scroll mode, we need to clamp to the free scroll page range.
442        if (mFreeScroll) {
443            getFreeScrollPageRange(mTempVisiblePagesRange);
444            validatedPage = Math.max(mTempVisiblePagesRange[0],
445                    Math.min(newPage, mTempVisiblePagesRange[1]));
446        }
447        // Ensure that it is clamped by the actual set of children in all cases
448        validatedPage = Utilities.boundInRange(validatedPage, 0, getPageCount() - 1);
449        return validatedPage;
450    }
451
452    /**
453     * Sets the current page.
454     */
455    public void setCurrentPage(int currentPage) {
456        if (!mScroller.isFinished()) {
457            abortScrollerAnimation(true);
458        }
459        // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
460        // the default
461        if (getChildCount() == 0) {
462            return;
463        }
464        mForceScreenScrolled = true;
465        mCurrentPage = validateNewPage(currentPage);
466        updateCurrentPageScroll();
467        notifyPageSwitchListener();
468        invalidate();
469    }
470
471    /**
472     * The restore page will be set in place of the current page at the next (likely first)
473     * layout.
474     */
475    void setRestorePage(int restorePage) {
476        mRestorePage = restorePage;
477    }
478    int getRestorePage() {
479        return mRestorePage;
480    }
481
482    /**
483     * Should be called whenever the page changes. In the case of a scroll, we wait until the page
484     * has settled.
485     */
486    protected void notifyPageSwitchListener() {
487        if (mPageSwitchListener != null) {
488            mPageSwitchListener.onPageSwitch(getPageAt(getNextPage()), getNextPage());
489        }
490
491        updatePageIndicator();
492    }
493
494    private void updatePageIndicator() {
495        // Update the page indicator (when we aren't reordering)
496        if (mPageIndicator != null) {
497            mPageIndicator.setContentDescription(getPageIndicatorDescription());
498            if (!isReordering(false)) {
499                mPageIndicator.setActiveMarker(getNextPage());
500            }
501        }
502    }
503    protected void pageBeginMoving() {
504        if (!mIsPageMoving) {
505            mIsPageMoving = true;
506            onPageBeginMoving();
507        }
508    }
509
510    protected void pageEndMoving() {
511        if (mIsPageMoving) {
512            mIsPageMoving = false;
513            onPageEndMoving();
514        }
515    }
516
517    protected boolean isPageMoving() {
518        return mIsPageMoving;
519    }
520
521    // a method that subclasses can override to add behavior
522    protected void onPageBeginMoving() {
523    }
524
525    // a method that subclasses can override to add behavior
526    protected void onPageEndMoving() {
527        mWasInOverscroll = false;
528    }
529
530    /**
531     * Registers the specified listener on each page contained in this workspace.
532     *
533     * @param l The listener used to respond to long clicks.
534     */
535    @Override
536    public void setOnLongClickListener(OnLongClickListener l) {
537        mLongClickListener = l;
538        final int count = getPageCount();
539        for (int i = 0; i < count; i++) {
540            getPageAt(i).setOnLongClickListener(l);
541        }
542        super.setOnLongClickListener(l);
543    }
544
545    protected int getUnboundedScrollX() {
546        return getScrollX();
547    }
548
549    @Override
550    public void scrollBy(int x, int y) {
551        scrollTo(getUnboundedScrollX() + x, getScrollY() + y);
552    }
553
554    @Override
555    public void scrollTo(int x, int y) {
556        // In free scroll mode, we clamp the scrollX
557        if (mFreeScroll) {
558            // If the scroller is trying to move to a location beyond the maximum allowed
559            // in the free scroll mode, we make sure to end the scroll operation.
560            if (!mScroller.isFinished() &&
561                    (x > mFreeScrollMaxScrollX || x < mFreeScrollMinScrollX)) {
562                forceFinishScroller();
563            }
564
565            x = Math.min(x, mFreeScrollMaxScrollX);
566            x = Math.max(x, mFreeScrollMinScrollX);
567        }
568
569        boolean isXBeforeFirstPage = mIsRtl ? (x > mMaxScrollX) : (x < 0);
570        boolean isXAfterLastPage = mIsRtl ? (x < 0) : (x > mMaxScrollX);
571        if (isXBeforeFirstPage) {
572            super.scrollTo(mIsRtl ? mMaxScrollX : 0, y);
573            if (mAllowOverScroll) {
574                mWasInOverscroll = true;
575                if (mIsRtl) {
576                    overScroll(x - mMaxScrollX);
577                } else {
578                    overScroll(x);
579                }
580            }
581        } else if (isXAfterLastPage) {
582            super.scrollTo(mIsRtl ? 0 : mMaxScrollX, y);
583            if (mAllowOverScroll) {
584                mWasInOverscroll = true;
585                if (mIsRtl) {
586                    overScroll(x);
587                } else {
588                    overScroll(x - mMaxScrollX);
589                }
590            }
591        } else {
592            if (mWasInOverscroll) {
593                overScroll(0);
594                mWasInOverscroll = false;
595            }
596            super.scrollTo(x, y);
597        }
598
599        // Update the last motion events when scrolling
600        if (isReordering(true)) {
601            float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
602            mLastMotionX = p[0];
603            mLastMotionY = p[1];
604            updateDragViewTranslationDuringDrag();
605        }
606    }
607
608    private void sendScrollAccessibilityEvent() {
609        AccessibilityManager am =
610                (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
611        if (am.isEnabled()) {
612            if (mCurrentPage != getNextPage()) {
613                AccessibilityEvent ev =
614                        AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
615                ev.setScrollable(true);
616                ev.setScrollX(getScrollX());
617                ev.setScrollY(getScrollY());
618                ev.setMaxScrollX(mMaxScrollX);
619                ev.setMaxScrollY(0);
620
621                sendAccessibilityEventUnchecked(ev);
622            }
623        }
624    }
625
626    // we moved this functionality to a helper function so SmoothPagedView can reuse it
627    protected boolean computeScrollHelper() {
628        if (mScroller.computeScrollOffset()) {
629            // Don't bother scrolling if the page does not need to be moved
630            if (getScrollX() != mScroller.getCurrX()
631                || getScrollY() != mScroller.getCurrY()) {
632                float scaleX = mFreeScroll ? getScaleX() : 1f;
633                int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
634                scrollTo(scrollX, mScroller.getCurrY());
635            }
636            invalidate();
637            return true;
638        } else if (mNextPage != INVALID_PAGE) {
639            sendScrollAccessibilityEvent();
640
641            mCurrentPage = validateNewPage(mNextPage);
642            mNextPage = INVALID_PAGE;
643            notifyPageSwitchListener();
644
645            // We don't want to trigger a page end moving unless the page has settled
646            // and the user has stopped scrolling
647            if (mTouchState == TOUCH_STATE_REST) {
648                pageEndMoving();
649            }
650
651            onPostReorderingAnimationCompleted();
652            AccessibilityManager am = (AccessibilityManager)
653                    getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
654            if (am.isEnabled()) {
655                // Notify the user when the page changes
656                announceForAccessibility(getCurrentPageDescription());
657            }
658            return true;
659        }
660        return false;
661    }
662
663    @Override
664    public void computeScroll() {
665        computeScrollHelper();
666    }
667
668    public static class LayoutParams extends ViewGroup.LayoutParams {
669        public boolean isFullScreenPage = false;
670
671        /**
672         * {@inheritDoc}
673         */
674        public LayoutParams(int width, int height) {
675            super(width, height);
676        }
677
678        public LayoutParams(Context context, AttributeSet attrs) {
679            super(context, attrs);
680        }
681
682        public LayoutParams(ViewGroup.LayoutParams source) {
683            super(source);
684        }
685    }
686
687    @Override
688    public LayoutParams generateLayoutParams(AttributeSet attrs) {
689        return new LayoutParams(getContext(), attrs);
690    }
691
692    @Override
693    protected LayoutParams generateDefaultLayoutParams() {
694        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
695    }
696
697    @Override
698    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
699        return new LayoutParams(p);
700    }
701
702    @Override
703    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
704        return p instanceof LayoutParams;
705    }
706
707    public void addFullScreenPage(View page) {
708        LayoutParams lp = generateDefaultLayoutParams();
709        lp.isFullScreenPage = true;
710        super.addView(page, 0, lp);
711    }
712
713    public int getNormalChildHeight() {
714        return mNormalChildHeight;
715    }
716
717    @Override
718    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
719        if (getChildCount() == 0) {
720            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
721            return;
722        }
723
724        // We measure the dimensions of the PagedView to be larger than the pages so that when we
725        // zoom out (and scale down), the view is still contained in the parent
726        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
727        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
728        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
729        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
730        // NOTE: We multiply by 2f to account for the fact that depending on the offset of the
731        // viewport, we can be at most one and a half screens offset once we scale down
732        DisplayMetrics dm = getResources().getDisplayMetrics();
733        int maxSize = Math.max(dm.widthPixels + mInsets.left + mInsets.right,
734                dm.heightPixels + mInsets.top + mInsets.bottom);
735
736        int parentWidthSize = (int) (2f * maxSize);
737        int parentHeightSize = (int) (2f * maxSize);
738        int scaledWidthSize, scaledHeightSize;
739        if (mUseMinScale) {
740            scaledWidthSize = (int) (parentWidthSize / mMinScale);
741            scaledHeightSize = (int) (parentHeightSize / mMinScale);
742        } else {
743            scaledWidthSize = widthSize;
744            scaledHeightSize = heightSize;
745        }
746        mViewport.set(0, 0, widthSize, heightSize);
747
748        if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
749            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
750            return;
751        }
752
753        // Return early if we aren't given a proper dimension
754        if (widthSize <= 0 || heightSize <= 0) {
755            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
756            return;
757        }
758
759        /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
760         * of the All apps view on XLarge displays to not take up more space then it needs. Width
761         * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
762         * each page to have the same width.
763         */
764        final int verticalPadding = getPaddingTop() + getPaddingBottom();
765        final int horizontalPadding = getPaddingLeft() + getPaddingRight();
766
767        int referenceChildWidth = 0;
768        // The children are given the same width and height as the workspace
769        // unless they were set to WRAP_CONTENT
770        if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
771        if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
772        if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
773        if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
774        if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
775        final int childCount = getChildCount();
776        for (int i = 0; i < childCount; i++) {
777            // disallowing padding in paged view (just pass 0)
778            final View child = getPageAt(i);
779            if (child.getVisibility() != GONE) {
780                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
781
782                int childWidthMode;
783                int childHeightMode;
784                int childWidth;
785                int childHeight;
786
787                if (!lp.isFullScreenPage) {
788                    if (lp.width == LayoutParams.WRAP_CONTENT) {
789                        childWidthMode = MeasureSpec.AT_MOST;
790                    } else {
791                        childWidthMode = MeasureSpec.EXACTLY;
792                    }
793
794                    if (lp.height == LayoutParams.WRAP_CONTENT) {
795                        childHeightMode = MeasureSpec.AT_MOST;
796                    } else {
797                        childHeightMode = MeasureSpec.EXACTLY;
798                    }
799
800                    childWidth = getViewportWidth() - horizontalPadding
801                            - mInsets.left - mInsets.right;
802                    childHeight = getViewportHeight() - verticalPadding
803                            - mInsets.top - mInsets.bottom;
804                    mNormalChildHeight = childHeight;
805                } else {
806                    childWidthMode = MeasureSpec.EXACTLY;
807                    childHeightMode = MeasureSpec.EXACTLY;
808
809                    childWidth = getViewportWidth();
810                    childHeight = getViewportHeight();
811                }
812                if (referenceChildWidth == 0) {
813                    referenceChildWidth = childWidth;
814                }
815
816                final int childWidthMeasureSpec =
817                        MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
818                    final int childHeightMeasureSpec =
819                        MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
820                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
821            }
822        }
823        setMeasuredDimension(scaledWidthSize, scaledHeightSize);
824    }
825
826    @SuppressLint("DrawAllocation")
827    @Override
828    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
829        if (getChildCount() == 0) {
830            return;
831        }
832
833        if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
834        final int childCount = getChildCount();
835
836        int offsetX = getViewportOffsetX();
837        int offsetY = getViewportOffsetY();
838
839        // Update the viewport offsets
840        mViewport.offset(offsetX, offsetY);
841
842        final int startIndex = mIsRtl ? childCount - 1 : 0;
843        final int endIndex = mIsRtl ? -1 : childCount;
844        final int delta = mIsRtl ? -1 : 1;
845
846        int verticalPadding = getPaddingTop() + getPaddingBottom();
847
848        LayoutParams lp = (LayoutParams) getChildAt(startIndex).getLayoutParams();
849        LayoutParams nextLp;
850
851        int childLeft = offsetX + (lp.isFullScreenPage ? 0 : getPaddingLeft());
852        if (mPageScrolls == null || childCount != mChildCountOnLastLayout) {
853            mPageScrolls = new int[childCount];
854        }
855
856        for (int i = startIndex; i != endIndex; i += delta) {
857            final View child = getPageAt(i);
858            if (child.getVisibility() != View.GONE) {
859                lp = (LayoutParams) child.getLayoutParams();
860                int childTop;
861                if (lp.isFullScreenPage) {
862                    childTop = offsetY;
863                } else {
864                    childTop = offsetY + getPaddingTop() + mInsets.top;
865                    childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
866                }
867
868                final int childWidth = child.getMeasuredWidth();
869                final int childHeight = child.getMeasuredHeight();
870
871                if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
872                child.layout(childLeft, childTop,
873                        childLeft + child.getMeasuredWidth(), childTop + childHeight);
874
875                int scrollOffsetLeft = lp.isFullScreenPage ? 0 : getPaddingLeft();
876                mPageScrolls[i] = childLeft - scrollOffsetLeft - offsetX;
877
878                int pageGap = mPageSpacing;
879                int next = i + delta;
880                if (next != endIndex) {
881                    nextLp = (LayoutParams) getPageAt(next).getLayoutParams();
882                } else {
883                    nextLp = null;
884                }
885
886                // Prevent full screen pages from showing in the viewport
887                // when they are not the current page.
888                if (lp.isFullScreenPage) {
889                    pageGap = getPaddingLeft();
890                } else if (nextLp != null && nextLp.isFullScreenPage) {
891                    pageGap = getPaddingRight();
892                }
893
894                childLeft += childWidth + pageGap + getChildGap();
895            }
896        }
897
898        final LayoutTransition transition = getLayoutTransition();
899        // If the transition is running defer updating max scroll, as some empty pages could
900        // still be present, and a max scroll change could cause sudden jumps in scroll.
901        if (transition != null && transition.isRunning()) {
902            transition.addTransitionListener(new LayoutTransition.TransitionListener() {
903
904                @Override
905                public void startTransition(LayoutTransition transition, ViewGroup container,
906                        View view, int transitionType) { }
907
908                @Override
909                public void endTransition(LayoutTransition transition, ViewGroup container,
910                        View view, int transitionType) {
911                    // Wait until all transitions are complete.
912                    if (!transition.isRunning()) {
913                        transition.removeTransitionListener(this);
914                        updateMaxScrollX();
915                    }
916                }
917            });
918        } else {
919            updateMaxScrollX();
920        }
921
922        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < childCount) {
923            updateCurrentPageScroll();
924            mFirstLayout = false;
925        }
926
927        if (mScroller.isFinished() && mChildCountOnLastLayout != childCount) {
928            if (mRestorePage != INVALID_RESTORE_PAGE) {
929                setCurrentPage(mRestorePage);
930                mRestorePage = INVALID_RESTORE_PAGE;
931            } else {
932                setCurrentPage(getNextPage());
933            }
934        }
935        mChildCountOnLastLayout = childCount;
936
937        if (isReordering(true)) {
938            updateDragViewTranslationDuringDrag();
939        }
940    }
941
942    protected int getChildGap() {
943        return 0;
944    }
945
946    @Thunk void updateMaxScrollX() {
947        int childCount = getChildCount();
948        if (childCount > 0) {
949            final int index = mIsRtl ? 0 : childCount - 1;
950            mMaxScrollX = getScrollForPage(index);
951        } else {
952            mMaxScrollX = 0;
953        }
954    }
955
956    public void setPageSpacing(int pageSpacing) {
957        mPageSpacing = pageSpacing;
958        requestLayout();
959    }
960
961    /**
962     * Called when the center screen changes during scrolling.
963     */
964    protected void screenScrolled(int screenCenter) { }
965
966    @Override
967    public void onChildViewAdded(View parent, View child) {
968        // Update the page indicator, we don't update the page indicator as we
969        // add/remove pages
970        if (mPageIndicator != null && !isReordering(false)) {
971            int pageIndex = indexOfChild(child);
972            mPageIndicator.addMarker(pageIndex,
973                    getPageIndicatorMarker(pageIndex),
974                    true);
975        }
976
977        // This ensures that when children are added, they get the correct transforms / alphas
978        // in accordance with any scroll effects.
979        mForceScreenScrolled = true;
980        updateFreescrollBounds();
981        invalidate();
982    }
983
984    @Override
985    public void onChildViewRemoved(View parent, View child) {
986        mForceScreenScrolled = true;
987        updateFreescrollBounds();
988        invalidate();
989    }
990
991    private void removeMarkerForView(int index) {
992        // Update the page indicator, we don't update the page indicator as we
993        // add/remove pages
994        if (mPageIndicator != null && !isReordering(false)) {
995            mPageIndicator.removeMarker(index, true);
996        }
997    }
998
999    @Override
1000    public void removeView(View v) {
1001        // XXX: We should find a better way to hook into this before the view
1002        // gets removed form its parent...
1003        removeMarkerForView(indexOfChild(v));
1004        super.removeView(v);
1005    }
1006    @Override
1007    public void removeViewInLayout(View v) {
1008        // XXX: We should find a better way to hook into this before the view
1009        // gets removed form its parent...
1010        removeMarkerForView(indexOfChild(v));
1011        super.removeViewInLayout(v);
1012    }
1013    @Override
1014    public void removeViewAt(int index) {
1015        // XXX: We should find a better way to hook into this before the view
1016        // gets removed form its parent...
1017        removeMarkerForView(index);
1018        super.removeViewAt(index);
1019    }
1020    @Override
1021    public void removeAllViewsInLayout() {
1022        // Update the page indicator, we don't update the page indicator as we
1023        // add/remove pages
1024        if (mPageIndicator != null) {
1025            mPageIndicator.removeAllMarkers(true);
1026        }
1027
1028        super.removeAllViewsInLayout();
1029    }
1030
1031    protected int getChildOffset(int index) {
1032        if (index < 0 || index > getChildCount() - 1) return 0;
1033
1034        int offset = getPageAt(index).getLeft() - getViewportOffsetX();
1035
1036        return offset;
1037    }
1038
1039    protected void getFreeScrollPageRange(int[] range) {
1040        range[0] = 0;
1041        range[1] = Math.max(0, getChildCount() - 1);
1042    }
1043
1044    protected void getVisiblePages(int[] range) {
1045        final int count = getChildCount();
1046        range[0] = -1;
1047        range[1] = -1;
1048
1049        if (count > 0) {
1050            final int visibleLeft = -getLeft();
1051            final int visibleRight = visibleLeft + getViewportWidth();
1052            final Matrix pageShiftMatrix = getPageShiftMatrix();
1053            int curScreen = 0;
1054
1055            for (int i = 0; i < count; i++) {
1056                View currPage = getPageAt(i);
1057
1058                // Verify if the page bounds are within the visible range.
1059                sTmpRectF.left = 0;
1060                sTmpRectF.right = currPage.getMeasuredWidth();
1061                currPage.getMatrix().mapRect(sTmpRectF);
1062                sTmpRectF.offset(currPage.getLeft() - getScrollX(), 0);
1063                pageShiftMatrix.mapRect(sTmpRectF);
1064
1065                if (sTmpRectF.left > visibleRight || sTmpRectF.right < visibleLeft) {
1066                    if (range[0] == -1) {
1067                        continue;
1068                    } else {
1069                        break;
1070                    }
1071                }
1072                curScreen = i;
1073                if (range[0] < 0) {
1074                    range[0] = curScreen;
1075                }
1076            }
1077
1078            range[1] = curScreen;
1079        } else {
1080            range[0] = -1;
1081            range[1] = -1;
1082        }
1083    }
1084
1085    protected Matrix getPageShiftMatrix() {
1086        return getMatrix();
1087    }
1088
1089    protected boolean shouldDrawChild(View child) {
1090        return child.getVisibility() == VISIBLE;
1091    }
1092
1093    @Override
1094    protected void dispatchDraw(Canvas canvas) {
1095        // Find out which screens are visible; as an optimization we only call draw on them
1096        final int pageCount = getChildCount();
1097        if (pageCount > 0) {
1098            int halfScreenSize = getViewportWidth() / 2;
1099            int screenCenter = getScrollX() + halfScreenSize;
1100
1101            if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
1102                // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1103                // set it for the next frame
1104                mForceScreenScrolled = false;
1105                screenScrolled(screenCenter);
1106                mLastScreenCenter = screenCenter;
1107            }
1108
1109            getVisiblePages(mTempVisiblePagesRange);
1110            final int leftScreen = mTempVisiblePagesRange[0];
1111            final int rightScreen = mTempVisiblePagesRange[1];
1112            if (leftScreen != -1 && rightScreen != -1) {
1113                final long drawingTime = getDrawingTime();
1114                // Clip to the bounds
1115                canvas.save();
1116                canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1117                        getScrollY() + getBottom() - getTop());
1118
1119                // Draw all the children, leaving the drag view for last
1120                for (int i = pageCount - 1; i >= 0; i--) {
1121                    final View v = getPageAt(i);
1122                    if (v == mDragView) continue;
1123                    if (leftScreen <= i && i <= rightScreen && shouldDrawChild(v)) {
1124                        drawChild(canvas, v, drawingTime);
1125                    }
1126                }
1127                // Draw the drag view on top (if there is one)
1128                if (mDragView != null) {
1129                    drawChild(canvas, mDragView, drawingTime);
1130                }
1131
1132                canvas.restore();
1133            }
1134        }
1135    }
1136
1137    @Override
1138    public void draw(Canvas canvas) {
1139        super.draw(canvas);
1140        if (getPageCount() > 0) {
1141            if (!mEdgeGlowLeft.isFinished()) {
1142                final int restoreCount = canvas.save();
1143                Rect display = mViewport;
1144                canvas.translate(display.left, display.top);
1145                canvas.rotate(270);
1146
1147                getEdgeVerticalPostion(sTmpIntPoint);
1148                canvas.translate(display.top - sTmpIntPoint[1], 0);
1149                mEdgeGlowLeft.setSize(sTmpIntPoint[1] - sTmpIntPoint[0], display.width());
1150                if (mEdgeGlowLeft.draw(canvas)) {
1151                    postInvalidateOnAnimation();
1152                }
1153                canvas.restoreToCount(restoreCount);
1154            }
1155            if (!mEdgeGlowRight.isFinished()) {
1156                final int restoreCount = canvas.save();
1157                Rect display = mViewport;
1158                canvas.translate(display.left + mPageScrolls[mIsRtl ? 0 : (getPageCount() - 1)], display.top);
1159                canvas.rotate(90);
1160
1161                getEdgeVerticalPostion(sTmpIntPoint);
1162
1163                canvas.translate(sTmpIntPoint[0] - display.top, -display.width());
1164                mEdgeGlowRight.setSize(sTmpIntPoint[1] - sTmpIntPoint[0], display.width());
1165                if (mEdgeGlowRight.draw(canvas)) {
1166                    postInvalidateOnAnimation();
1167                }
1168                canvas.restoreToCount(restoreCount);
1169            }
1170        }
1171    }
1172
1173    /**
1174     * Returns the top and bottom position for the edge effect.
1175     */
1176    protected abstract void getEdgeVerticalPostion(int[] pos);
1177
1178    @Override
1179    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
1180        int page = indexToPage(indexOfChild(child));
1181        if (page != mCurrentPage || !mScroller.isFinished()) {
1182            snapToPage(page);
1183            return true;
1184        }
1185        return false;
1186    }
1187
1188    @Override
1189    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1190        int focusablePage;
1191        if (mNextPage != INVALID_PAGE) {
1192            focusablePage = mNextPage;
1193        } else {
1194            focusablePage = mCurrentPage;
1195        }
1196        View v = getPageAt(focusablePage);
1197        if (v != null) {
1198            return v.requestFocus(direction, previouslyFocusedRect);
1199        }
1200        return false;
1201    }
1202
1203    @Override
1204    public boolean dispatchUnhandledMove(View focused, int direction) {
1205        if (super.dispatchUnhandledMove(focused, direction)) {
1206            return true;
1207        }
1208
1209        if (mIsRtl) {
1210            if (direction == View.FOCUS_LEFT) {
1211                direction = View.FOCUS_RIGHT;
1212            } else if (direction == View.FOCUS_RIGHT) {
1213                direction = View.FOCUS_LEFT;
1214            }
1215        }
1216        if (direction == View.FOCUS_LEFT) {
1217            if (getCurrentPage() > 0) {
1218                snapToPage(getCurrentPage() - 1);
1219                return true;
1220            }
1221        } else if (direction == View.FOCUS_RIGHT) {
1222            if (getCurrentPage() < getPageCount() - 1) {
1223                snapToPage(getCurrentPage() + 1);
1224                return true;
1225            }
1226        }
1227        return false;
1228    }
1229
1230    @Override
1231    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1232        // XXX-RTL: This will be fixed in a future CL
1233        if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
1234            getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
1235        }
1236        if (direction == View.FOCUS_LEFT) {
1237            if (mCurrentPage > 0) {
1238                getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
1239            }
1240        } else if (direction == View.FOCUS_RIGHT){
1241            if (mCurrentPage < getPageCount() - 1) {
1242                getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
1243            }
1244        }
1245    }
1246
1247    /**
1248     * If one of our descendant views decides that it could be focused now, only
1249     * pass that along if it's on the current page.
1250     *
1251     * This happens when live folders requery, and if they're off page, they
1252     * end up calling requestFocus, which pulls it on page.
1253     */
1254    @Override
1255    public void focusableViewAvailable(View focused) {
1256        View current = getPageAt(mCurrentPage);
1257        View v = focused;
1258        while (true) {
1259            if (v == current) {
1260                super.focusableViewAvailable(focused);
1261                return;
1262            }
1263            if (v == this) {
1264                return;
1265            }
1266            ViewParent parent = v.getParent();
1267            if (parent instanceof View) {
1268                v = (View)v.getParent();
1269            } else {
1270                return;
1271            }
1272        }
1273    }
1274
1275    /**
1276     * {@inheritDoc}
1277     */
1278    @Override
1279    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1280        if (disallowIntercept) {
1281            // We need to make sure to cancel our long press if
1282            // a scrollable widget takes over touch events
1283            final View currentPage = getPageAt(mCurrentPage);
1284            currentPage.cancelLongPress();
1285        }
1286        super.requestDisallowInterceptTouchEvent(disallowIntercept);
1287    }
1288
1289    /**
1290     * Return true if a tap at (x, y) should trigger a flip to the previous page.
1291     */
1292    protected boolean hitsPreviousPage(float x, float y) {
1293        if (mIsRtl) {
1294            return (x > (getViewportOffsetX() + getViewportWidth() -
1295                    getPaddingRight() - mPageSpacing));
1296        }
1297        return (x < getViewportOffsetX() + getPaddingLeft() + mPageSpacing);
1298    }
1299
1300    /**
1301     * Return true if a tap at (x, y) should trigger a flip to the next page.
1302     */
1303    protected boolean hitsNextPage(float x, float y) {
1304        if (mIsRtl) {
1305            return (x < getViewportOffsetX() + getPaddingLeft() + mPageSpacing);
1306        }
1307        return  (x > (getViewportOffsetX() + getViewportWidth() -
1308                getPaddingRight() - mPageSpacing));
1309    }
1310
1311    /** Returns whether x and y originated within the buffered viewport */
1312    private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1313        sTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1314                mViewport.right + mViewport.width() / 2, mViewport.bottom);
1315        return sTmpRect.contains(x, y);
1316    }
1317
1318    @Override
1319    public boolean onInterceptTouchEvent(MotionEvent ev) {
1320        /*
1321         * This method JUST determines whether we want to intercept the motion.
1322         * If we return true, onTouchEvent will be called and we do the actual
1323         * scrolling there.
1324         */
1325        acquireVelocityTrackerAndAddMovement(ev);
1326
1327        // Skip touch handling if there are no pages to swipe
1328        if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1329
1330        /*
1331         * Shortcut the most recurring case: the user is in the dragging
1332         * state and he is moving his finger.  We want to intercept this
1333         * motion.
1334         */
1335        final int action = ev.getAction();
1336        if ((action == MotionEvent.ACTION_MOVE) &&
1337                (mTouchState == TOUCH_STATE_SCROLLING)) {
1338            return true;
1339        }
1340
1341        switch (action & MotionEvent.ACTION_MASK) {
1342            case MotionEvent.ACTION_MOVE: {
1343                /*
1344                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1345                 * whether the user has moved far enough from his original down touch.
1346                 */
1347                if (mActivePointerId != INVALID_POINTER) {
1348                    determineScrollingStart(ev);
1349                }
1350                // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1351                // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1352                // i.e. fall through to the next case (don't break)
1353                // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1354                // while it's small- this was causing a crash before we checked for INVALID_POINTER)
1355                break;
1356            }
1357
1358            case MotionEvent.ACTION_DOWN: {
1359                final float x = ev.getX();
1360                final float y = ev.getY();
1361                // Remember location of down touch
1362                mDownMotionX = x;
1363                mDownMotionY = y;
1364                mDownScrollX = getScrollX();
1365                mLastMotionX = x;
1366                mLastMotionY = y;
1367                float[] p = mapPointFromViewToParent(this, x, y);
1368                mParentDownMotionX = p[0];
1369                mParentDownMotionY = p[1];
1370                mLastMotionXRemainder = 0;
1371                mTotalMotionX = 0;
1372                mActivePointerId = ev.getPointerId(0);
1373
1374                /*
1375                 * If being flinged and user touches the screen, initiate drag;
1376                 * otherwise don't.  mScroller.isFinished should be false when
1377                 * being flinged.
1378                 */
1379                final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
1380                final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop / 3);
1381
1382                if (finishedScrolling) {
1383                    mTouchState = TOUCH_STATE_REST;
1384                    if (!mScroller.isFinished() && !mFreeScroll) {
1385                        setCurrentPage(getNextPage());
1386                        pageEndMoving();
1387                    }
1388                } else {
1389                    if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1390                        mTouchState = TOUCH_STATE_SCROLLING;
1391                    } else {
1392                        mTouchState = TOUCH_STATE_REST;
1393                    }
1394                }
1395
1396                break;
1397            }
1398
1399            case MotionEvent.ACTION_UP:
1400            case MotionEvent.ACTION_CANCEL:
1401                resetTouchState();
1402                break;
1403
1404            case MotionEvent.ACTION_POINTER_UP:
1405                onSecondaryPointerUp(ev);
1406                releaseVelocityTracker();
1407                break;
1408        }
1409
1410        /*
1411         * The only time we want to intercept motion events is if we are in the
1412         * drag mode.
1413         */
1414        return mTouchState != TOUCH_STATE_REST;
1415    }
1416
1417    protected void determineScrollingStart(MotionEvent ev) {
1418        determineScrollingStart(ev, 1.0f);
1419    }
1420
1421    /*
1422     * Determines if we should change the touch state to start scrolling after the
1423     * user moves their touch point too far.
1424     */
1425    protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
1426        // Disallow scrolling if we don't have a valid pointer index
1427        final int pointerIndex = ev.findPointerIndex(mActivePointerId);
1428        if (pointerIndex == -1) return;
1429
1430        // Disallow scrolling if we started the gesture from outside the viewport
1431        final float x = ev.getX(pointerIndex);
1432        final float y = ev.getY(pointerIndex);
1433        if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1434
1435        final int xDiff = (int) Math.abs(x - mLastMotionX);
1436
1437        final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
1438        boolean xMoved = xDiff > touchSlop;
1439
1440        if (xMoved) {
1441            // Scroll if the user moved far enough along the X axis
1442            mTouchState = TOUCH_STATE_SCROLLING;
1443            mTotalMotionX += Math.abs(mLastMotionX - x);
1444            mLastMotionX = x;
1445            mLastMotionXRemainder = 0;
1446            onScrollInteractionBegin();
1447            pageBeginMoving();
1448        }
1449    }
1450
1451    protected void cancelCurrentPageLongPress() {
1452        // Try canceling the long press. It could also have been scheduled
1453        // by a distant descendant, so use the mAllowLongPress flag to block
1454        // everything
1455        final View currentPage = getPageAt(mCurrentPage);
1456        if (currentPage != null) {
1457            currentPage.cancelLongPress();
1458        }
1459    }
1460
1461    protected float getScrollProgress(int screenCenter, View v, int page) {
1462        final int halfScreenSize = getViewportWidth() / 2;
1463
1464        int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
1465        int count = getChildCount();
1466
1467        final int totalDistance;
1468
1469        int adjacentPage = page + 1;
1470        if ((delta < 0 && !mIsRtl) || (delta > 0 && mIsRtl)) {
1471            adjacentPage = page - 1;
1472        }
1473
1474        if (adjacentPage < 0 || adjacentPage > count - 1) {
1475            totalDistance = v.getMeasuredWidth() + mPageSpacing;
1476        } else {
1477            totalDistance = Math.abs(getScrollForPage(adjacentPage) - getScrollForPage(page));
1478        }
1479
1480        float scrollProgress = delta / (totalDistance * 1.0f);
1481        scrollProgress = Math.min(scrollProgress, MAX_SCROLL_PROGRESS);
1482        scrollProgress = Math.max(scrollProgress, - MAX_SCROLL_PROGRESS);
1483        return scrollProgress;
1484    }
1485
1486    public int getScrollForPage(int index) {
1487        if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
1488            return 0;
1489        } else {
1490            return mPageScrolls[index];
1491        }
1492    }
1493
1494    // While layout transitions are occurring, a child's position may stray from its baseline
1495    // position. This method returns the magnitude of this stray at any given time.
1496    public int getLayoutTransitionOffsetForPage(int index) {
1497        if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
1498            return 0;
1499        } else {
1500            View child = getChildAt(index);
1501
1502            int scrollOffset = 0;
1503            LayoutParams lp = (LayoutParams) child.getLayoutParams();
1504            if (!lp.isFullScreenPage) {
1505                scrollOffset = mIsRtl ? getPaddingRight() : getPaddingLeft();
1506            }
1507
1508            int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX();
1509            return (int) (child.getX() - baselineX);
1510        }
1511    }
1512
1513    protected void dampedOverScroll(float amount) {
1514        int screenSize = getViewportWidth();
1515        float f = (amount / screenSize);
1516        if (f < 0) {
1517            mEdgeGlowLeft.onPull(-f);
1518        } else if (f > 0) {
1519            mEdgeGlowRight.onPull(f);
1520        } else {
1521            return;
1522        }
1523        invalidate();
1524    }
1525
1526    protected void overScroll(float amount) {
1527        dampedOverScroll(amount);
1528    }
1529
1530    public void enableFreeScroll() {
1531        setEnableFreeScroll(true);
1532    }
1533
1534    public void disableFreeScroll() {
1535        setEnableFreeScroll(false);
1536    }
1537
1538    void updateFreescrollBounds() {
1539        getFreeScrollPageRange(mTempVisiblePagesRange);
1540        if (mIsRtl) {
1541            mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1542            mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1543        } else {
1544            mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1545            mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1546        }
1547    }
1548
1549    private void setEnableFreeScroll(boolean freeScroll) {
1550        mFreeScroll = freeScroll;
1551
1552        if (mFreeScroll) {
1553            updateFreescrollBounds();
1554            getFreeScrollPageRange(mTempVisiblePagesRange);
1555            if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1556                setCurrentPage(mTempVisiblePagesRange[0]);
1557            } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1558                setCurrentPage(mTempVisiblePagesRange[1]);
1559            }
1560        }
1561
1562        setEnableOverscroll(!freeScroll);
1563    }
1564
1565    protected void setEnableOverscroll(boolean enable) {
1566        mAllowOverScroll = enable;
1567    }
1568
1569    private int getNearestHoverOverPageIndex() {
1570        if (mDragView != null) {
1571            int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1572                    + mDragView.getTranslationX());
1573            getFreeScrollPageRange(mTempVisiblePagesRange);
1574            int minDistance = Integer.MAX_VALUE;
1575            int minIndex = indexOfChild(mDragView);
1576            for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1577                View page = getPageAt(i);
1578                int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1579                int d = Math.abs(dragX - pageX);
1580                if (d < minDistance) {
1581                    minIndex = i;
1582                    minDistance = d;
1583                }
1584            }
1585            return minIndex;
1586        }
1587        return -1;
1588    }
1589
1590    @Override
1591    public boolean onTouchEvent(MotionEvent ev) {
1592        super.onTouchEvent(ev);
1593
1594        // Skip touch handling if there are no pages to swipe
1595        if (getChildCount() <= 0) return super.onTouchEvent(ev);
1596
1597        acquireVelocityTrackerAndAddMovement(ev);
1598
1599        final int action = ev.getAction();
1600
1601        switch (action & MotionEvent.ACTION_MASK) {
1602        case MotionEvent.ACTION_DOWN:
1603            /*
1604             * If being flinged and user touches, stop the fling. isFinished
1605             * will be false if being flinged.
1606             */
1607            if (!mScroller.isFinished()) {
1608                abortScrollerAnimation(false);
1609            }
1610
1611            // Remember where the motion event started
1612            mDownMotionX = mLastMotionX = ev.getX();
1613            mDownMotionY = mLastMotionY = ev.getY();
1614            mDownScrollX = getScrollX();
1615            float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1616            mParentDownMotionX = p[0];
1617            mParentDownMotionY = p[1];
1618            mLastMotionXRemainder = 0;
1619            mTotalMotionX = 0;
1620            mActivePointerId = ev.getPointerId(0);
1621
1622            if (mTouchState == TOUCH_STATE_SCROLLING) {
1623                onScrollInteractionBegin();
1624                pageBeginMoving();
1625            }
1626            break;
1627
1628        case MotionEvent.ACTION_MOVE:
1629            if (mTouchState == TOUCH_STATE_SCROLLING) {
1630                // Scroll to follow the motion event
1631                final int pointerIndex = ev.findPointerIndex(mActivePointerId);
1632
1633                if (pointerIndex == -1) return true;
1634
1635                final float x = ev.getX(pointerIndex);
1636                final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
1637
1638                mTotalMotionX += Math.abs(deltaX);
1639
1640                // Only scroll and update mLastMotionX if we have moved some discrete amount.  We
1641                // keep the remainder because we are actually testing if we've moved from the last
1642                // scrolled position (which is discrete).
1643                if (Math.abs(deltaX) >= 1.0f) {
1644                    scrollBy((int) deltaX, 0);
1645                    mLastMotionX = x;
1646                    mLastMotionXRemainder = deltaX - (int) deltaX;
1647                } else {
1648                    awakenScrollBars();
1649                }
1650            } else if (mTouchState == TOUCH_STATE_REORDERING) {
1651                // Update the last motion position
1652                mLastMotionX = ev.getX();
1653                mLastMotionY = ev.getY();
1654
1655                // Update the parent down so that our zoom animations take this new movement into
1656                // account
1657                float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1658                mParentDownMotionX = pt[0];
1659                mParentDownMotionY = pt[1];
1660                updateDragViewTranslationDuringDrag();
1661
1662                // Find the closest page to the touch point
1663                final int dragViewIndex = indexOfChild(mDragView);
1664
1665                if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1666                if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1667                if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1668                if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1669
1670                final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1671                if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView)) {
1672                    mTempVisiblePagesRange[0] = 0;
1673                    mTempVisiblePagesRange[1] = getPageCount() - 1;
1674                    getFreeScrollPageRange(mTempVisiblePagesRange);
1675                    if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1676                            pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1677                            pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1678                        mSidePageHoverIndex = pageUnderPointIndex;
1679                        mSidePageHoverRunnable = new Runnable() {
1680                            @Override
1681                            public void run() {
1682                                // Setup the scroll to the correct page before we swap the views
1683                                snapToPage(pageUnderPointIndex);
1684
1685                                // For each of the pages between the paged view and the drag view,
1686                                // animate them from the previous position to the new position in
1687                                // the layout (as a result of the drag view moving in the layout)
1688                                int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1689                                int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1690                                        dragViewIndex + 1 : pageUnderPointIndex;
1691                                int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1692                                        dragViewIndex - 1 : pageUnderPointIndex;
1693                                for (int i = lowerIndex; i <= upperIndex; ++i) {
1694                                    View v = getChildAt(i);
1695                                    // dragViewIndex < pageUnderPointIndex, so after we remove the
1696                                    // drag view all subsequent views to pageUnderPointIndex will
1697                                    // shift down.
1698                                    int oldX = getViewportOffsetX() + getChildOffset(i);
1699                                    int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1700
1701                                    // Animate the view translation from its old position to its new
1702                                    // position
1703                                    ObjectAnimator anim = (ObjectAnimator) v.getTag();
1704                                    if (anim != null) {
1705                                        anim.cancel();
1706                                    }
1707
1708                                    v.setTranslationX(oldX - newX);
1709                                    anim = LauncherAnimUtils.ofFloat(v, View.TRANSLATION_X, 0);
1710                                    anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1711                                    anim.start();
1712                                    v.setTag(anim);
1713                                }
1714
1715                                removeView(mDragView);
1716                                addView(mDragView, pageUnderPointIndex);
1717                                mSidePageHoverIndex = -1;
1718                                if (mPageIndicator != null) {
1719                                    mPageIndicator.setActiveMarker(getNextPage());
1720                                }
1721                            }
1722                        };
1723                        postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1724                    }
1725                } else {
1726                    removeCallbacks(mSidePageHoverRunnable);
1727                    mSidePageHoverIndex = -1;
1728                }
1729            } else {
1730                determineScrollingStart(ev);
1731            }
1732            break;
1733
1734        case MotionEvent.ACTION_UP:
1735            if (mTouchState == TOUCH_STATE_SCROLLING) {
1736                final int activePointerId = mActivePointerId;
1737                final int pointerIndex = ev.findPointerIndex(activePointerId);
1738                final float x = ev.getX(pointerIndex);
1739                final VelocityTracker velocityTracker = mVelocityTracker;
1740                velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1741                int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
1742                final int deltaX = (int) (x - mDownMotionX);
1743                final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
1744                boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1745                        SIGNIFICANT_MOVE_THRESHOLD;
1746
1747                mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1748
1749                boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
1750                        Math.abs(velocityX) > mFlingThresholdVelocity;
1751
1752                if (!mFreeScroll) {
1753                    // In the case that the page is moved far to one direction and then is flung
1754                    // in the opposite direction, we use a threshold to determine whether we should
1755                    // just return to the starting page, or if we should skip one further.
1756                    boolean returnToOriginalPage = false;
1757                    if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1758                            Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1759                        returnToOriginalPage = true;
1760                    }
1761
1762                    int finalPage;
1763                    // We give flings precedence over large moves, which is why we short-circuit our
1764                    // test for a large move if a fling has been registered. That is, a large
1765                    // move to the left and fling to the right will register as a fling to the right.
1766                    boolean isDeltaXLeft = mIsRtl ? deltaX > 0 : deltaX < 0;
1767                    boolean isVelocityXLeft = mIsRtl ? velocityX > 0 : velocityX < 0;
1768                    if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1769                            (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1770                        finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1771                        snapToPageWithVelocity(finalPage, velocityX);
1772                    } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1773                            (isFling && isVelocityXLeft)) &&
1774                            mCurrentPage < getChildCount() - 1) {
1775                        finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1776                        snapToPageWithVelocity(finalPage, velocityX);
1777                    } else {
1778                        snapToDestination();
1779                    }
1780                } else {
1781                    if (!mScroller.isFinished()) {
1782                        abortScrollerAnimation(true);
1783                    }
1784
1785                    float scaleX = getScaleX();
1786                    int vX = (int) (-velocityX * scaleX);
1787                    int initialScrollX = (int) (getScrollX() * scaleX);
1788
1789                    mScroller.setInterpolator(mDefaultInterpolator);
1790                    mScroller.fling(initialScrollX,
1791                            getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1792                    invalidate();
1793                }
1794                onScrollInteractionEnd();
1795            } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1796                // at this point we have not moved beyond the touch slop
1797                // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1798                // we can just page
1799                int nextPage = Math.max(0, mCurrentPage - 1);
1800                if (nextPage != mCurrentPage) {
1801                    snapToPage(nextPage);
1802                } else {
1803                    snapToDestination();
1804                }
1805            } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
1806                // at this point we have not moved beyond the touch slop
1807                // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1808                // we can just page
1809                int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1810                if (nextPage != mCurrentPage) {
1811                    snapToPage(nextPage);
1812                } else {
1813                    snapToDestination();
1814                }
1815            } else if (mTouchState == TOUCH_STATE_REORDERING) {
1816                // Update the last motion position
1817                mLastMotionX = ev.getX();
1818                mLastMotionY = ev.getY();
1819
1820                // Update the parent down so that our zoom animations take this new movement into
1821                // account
1822                float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1823                mParentDownMotionX = pt[0];
1824                mParentDownMotionY = pt[1];
1825                updateDragViewTranslationDuringDrag();
1826            } else {
1827                if (!mCancelTap) {
1828                    onUnhandledTap(ev);
1829                }
1830            }
1831
1832            // Remove the callback to wait for the side page hover timeout
1833            removeCallbacks(mSidePageHoverRunnable);
1834            // End any intermediate reordering states
1835            resetTouchState();
1836            break;
1837
1838        case MotionEvent.ACTION_CANCEL:
1839            if (mTouchState == TOUCH_STATE_SCROLLING) {
1840                snapToDestination();
1841            }
1842            resetTouchState();
1843            break;
1844
1845        case MotionEvent.ACTION_POINTER_UP:
1846            onSecondaryPointerUp(ev);
1847            releaseVelocityTracker();
1848            break;
1849        }
1850
1851        return true;
1852    }
1853
1854    private void resetTouchState() {
1855        releaseVelocityTracker();
1856        endReordering();
1857        mCancelTap = false;
1858        mTouchState = TOUCH_STATE_REST;
1859        mActivePointerId = INVALID_POINTER;
1860        mEdgeGlowLeft.onRelease();
1861        mEdgeGlowRight.onRelease();
1862    }
1863
1864    /**
1865     * Triggered by scrolling via touch
1866     */
1867    protected void onScrollInteractionBegin() {
1868    }
1869
1870    protected void onScrollInteractionEnd() {
1871    }
1872
1873    protected void onUnhandledTap(MotionEvent ev) {
1874        ((Launcher) getContext()).onClick(this);
1875    }
1876
1877    @Override
1878    public boolean onGenericMotionEvent(MotionEvent event) {
1879        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1880            switch (event.getAction()) {
1881                case MotionEvent.ACTION_SCROLL: {
1882                    // Handle mouse (or ext. device) by shifting the page depending on the scroll
1883                    final float vscroll;
1884                    final float hscroll;
1885                    if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1886                        vscroll = 0;
1887                        hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1888                    } else {
1889                        vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1890                        hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1891                    }
1892                    if (hscroll != 0 || vscroll != 0) {
1893                        boolean isForwardScroll = mIsRtl ? (hscroll < 0 || vscroll < 0)
1894                                                         : (hscroll > 0 || vscroll > 0);
1895                        if (isForwardScroll) {
1896                            scrollRight();
1897                        } else {
1898                            scrollLeft();
1899                        }
1900                        return true;
1901                    }
1902                }
1903            }
1904        }
1905        return super.onGenericMotionEvent(event);
1906    }
1907
1908    private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1909        if (mVelocityTracker == null) {
1910            mVelocityTracker = VelocityTracker.obtain();
1911        }
1912        mVelocityTracker.addMovement(ev);
1913    }
1914
1915    private void releaseVelocityTracker() {
1916        if (mVelocityTracker != null) {
1917            mVelocityTracker.clear();
1918            mVelocityTracker.recycle();
1919            mVelocityTracker = null;
1920        }
1921    }
1922
1923    private void onSecondaryPointerUp(MotionEvent ev) {
1924        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1925                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1926        final int pointerId = ev.getPointerId(pointerIndex);
1927        if (pointerId == mActivePointerId) {
1928            // This was our active pointer going up. Choose a new
1929            // active pointer and adjust accordingly.
1930            // TODO: Make this decision more intelligent.
1931            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1932            mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1933            mLastMotionY = ev.getY(newPointerIndex);
1934            mLastMotionXRemainder = 0;
1935            mActivePointerId = ev.getPointerId(newPointerIndex);
1936            if (mVelocityTracker != null) {
1937                mVelocityTracker.clear();
1938            }
1939        }
1940    }
1941
1942    @Override
1943    public void requestChildFocus(View child, View focused) {
1944        super.requestChildFocus(child, focused);
1945        int page = indexToPage(indexOfChild(child));
1946        if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
1947            snapToPage(page);
1948        }
1949    }
1950
1951    int getPageNearestToCenterOfScreen() {
1952        int minDistanceFromScreenCenter = Integer.MAX_VALUE;
1953        int minDistanceFromScreenCenterIndex = -1;
1954        int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
1955        final int childCount = getChildCount();
1956        for (int i = 0; i < childCount; ++i) {
1957            View layout = (View) getPageAt(i);
1958            int childWidth = layout.getMeasuredWidth();
1959            int halfChildWidth = (childWidth / 2);
1960            int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
1961            int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1962            if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1963                minDistanceFromScreenCenter = distanceFromScreenCenter;
1964                minDistanceFromScreenCenterIndex = i;
1965            }
1966        }
1967        return minDistanceFromScreenCenterIndex;
1968    }
1969
1970    protected void snapToDestination() {
1971        snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
1972    }
1973
1974    private static class ScrollInterpolator implements Interpolator {
1975        public ScrollInterpolator() {
1976        }
1977
1978        public float getInterpolation(float t) {
1979            t -= 1.0f;
1980            return t*t*t*t*t + 1;
1981        }
1982    }
1983
1984    // We want the duration of the page snap animation to be influenced by the distance that
1985    // the screen has to travel, however, we don't want this duration to be effected in a
1986    // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1987    // of travel has on the overall snap duration.
1988    private float distanceInfluenceForSnapDuration(float f) {
1989        f -= 0.5f; // center the values about 0.
1990        f *= 0.3f * Math.PI / 2.0f;
1991        return (float) Math.sin(f);
1992    }
1993
1994    protected void snapToPageWithVelocity(int whichPage, int velocity) {
1995        whichPage = validateNewPage(whichPage);
1996        int halfScreenSize = getViewportWidth() / 2;
1997
1998        final int newX = getScrollForPage(whichPage);
1999        int delta = newX - getUnboundedScrollX();
2000        int duration = 0;
2001
2002        if (Math.abs(velocity) < mMinFlingVelocity) {
2003            // If the velocity is low enough, then treat this more as an automatic page advance
2004            // as opposed to an apparent physical response to flinging
2005            snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2006            return;
2007        }
2008
2009        // Here we compute a "distance" that will be used in the computation of the overall
2010        // snap duration. This is a function of the actual distance that needs to be traveled;
2011        // we keep this value close to half screen size in order to reduce the variance in snap
2012        // duration as a function of the distance the page needs to travel.
2013        float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
2014        float distance = halfScreenSize + halfScreenSize *
2015                distanceInfluenceForSnapDuration(distanceRatio);
2016
2017        velocity = Math.abs(velocity);
2018        velocity = Math.max(mMinSnapVelocity, velocity);
2019
2020        // we want the page's snap velocity to approximately match the velocity at which the
2021        // user flings, so we scale the duration by a value near to the derivative of the scroll
2022        // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2023        duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
2024
2025        snapToPage(whichPage, delta, duration);
2026    }
2027
2028    public void snapToPage(int whichPage) {
2029        snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2030    }
2031
2032    public void snapToPageImmediately(int whichPage) {
2033        snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true, null);
2034    }
2035
2036    protected void snapToPage(int whichPage, int duration) {
2037        snapToPage(whichPage, duration, false, null);
2038    }
2039
2040    protected void snapToPage(int whichPage, int duration, TimeInterpolator interpolator) {
2041        snapToPage(whichPage, duration, false, interpolator);
2042    }
2043
2044    protected void snapToPage(int whichPage, int duration, boolean immediate,
2045            TimeInterpolator interpolator) {
2046        whichPage = validateNewPage(whichPage);
2047
2048        int newX = getScrollForPage(whichPage);
2049        final int delta = newX - getUnboundedScrollX();
2050        snapToPage(whichPage, delta, duration, immediate, interpolator);
2051    }
2052
2053    protected void snapToPage(int whichPage, int delta, int duration) {
2054        snapToPage(whichPage, delta, duration, false, null);
2055    }
2056
2057    protected void snapToPage(int whichPage, int delta, int duration, boolean immediate,
2058            TimeInterpolator interpolator) {
2059        whichPage = validateNewPage(whichPage);
2060
2061        mNextPage = whichPage;
2062
2063        pageBeginMoving();
2064        awakenScrollBars(duration);
2065        if (immediate) {
2066            duration = 0;
2067        } else if (duration == 0) {
2068            duration = Math.abs(delta);
2069        }
2070
2071        if (!mScroller.isFinished()) {
2072            abortScrollerAnimation(false);
2073        }
2074
2075        if (interpolator != null) {
2076            mScroller.setInterpolator(interpolator);
2077        } else {
2078            mScroller.setInterpolator(mDefaultInterpolator);
2079        }
2080
2081        mScroller.startScroll(getUnboundedScrollX(), 0, delta, 0, duration);
2082
2083        updatePageIndicator();
2084
2085        // Trigger a compute() to finish switching pages if necessary
2086        if (immediate) {
2087            computeScroll();
2088        }
2089
2090        mForceScreenScrolled = true;
2091        invalidate();
2092    }
2093
2094    public void scrollLeft() {
2095        if (getNextPage() > 0) snapToPage(getNextPage() - 1);
2096    }
2097
2098    public void scrollRight() {
2099        if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
2100    }
2101
2102    @Override
2103    public boolean performLongClick() {
2104        mCancelTap = true;
2105        return super.performLongClick();
2106    }
2107
2108    public static class SavedState extends BaseSavedState {
2109        int currentPage = -1;
2110
2111        SavedState(Parcelable superState) {
2112            super(superState);
2113        }
2114
2115        @Thunk SavedState(Parcel in) {
2116            super(in);
2117            currentPage = in.readInt();
2118        }
2119
2120        @Override
2121        public void writeToParcel(Parcel out, int flags) {
2122            super.writeToParcel(out, flags);
2123            out.writeInt(currentPage);
2124        }
2125
2126        public static final Parcelable.Creator<SavedState> CREATOR =
2127                new Parcelable.Creator<SavedState>() {
2128            public SavedState createFromParcel(Parcel in) {
2129                return new SavedState(in);
2130            }
2131
2132            public SavedState[] newArray(int size) {
2133                return new SavedState[size];
2134            }
2135        };
2136    }
2137
2138    // Animate the drag view back to the original position
2139    private void animateDragViewToOriginalPosition() {
2140        if (mDragView != null) {
2141            Animator anim = new LauncherViewPropertyAnimator(mDragView)
2142                    .translationX(0)
2143                    .translationY(0)
2144                    .scaleX(1)
2145                    .scaleY(1)
2146                    .setDuration(REORDERING_DROP_REPOSITION_DURATION);
2147            anim.addListener(new AnimatorListenerAdapter() {
2148                @Override
2149                public void onAnimationEnd(Animator animation) {
2150                    onPostReorderingAnimationCompleted();
2151                }
2152            });
2153            anim.start();
2154        }
2155    }
2156
2157    public void onStartReordering() {
2158        // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2159        mTouchState = TOUCH_STATE_REORDERING;
2160        mIsReordering = true;
2161
2162        // We must invalidate to trigger a redraw to update the layers such that the drag view
2163        // is always drawn on top
2164        invalidate();
2165    }
2166
2167    @Thunk void onPostReorderingAnimationCompleted() {
2168        // Trigger the callback when reordering has settled
2169        --mPostReorderingPreZoomInRemainingAnimationCount;
2170        if (mPostReorderingPreZoomInRunnable != null &&
2171                mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2172            mPostReorderingPreZoomInRunnable.run();
2173            mPostReorderingPreZoomInRunnable = null;
2174        }
2175    }
2176
2177    public void onEndReordering() {
2178        mIsReordering = false;
2179    }
2180
2181    public boolean startReordering(View v) {
2182        int dragViewIndex = indexOfChild(v);
2183
2184        if (mTouchState != TOUCH_STATE_REST || dragViewIndex == -1) return false;
2185
2186        mTempVisiblePagesRange[0] = 0;
2187        mTempVisiblePagesRange[1] = getPageCount() - 1;
2188        getFreeScrollPageRange(mTempVisiblePagesRange);
2189        mReorderingStarted = true;
2190
2191        // Check if we are within the reordering range
2192        if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2193            dragViewIndex <= mTempVisiblePagesRange[1]) {
2194            // Find the drag view under the pointer
2195            mDragView = getChildAt(dragViewIndex);
2196            mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2197            mDragViewBaselineLeft = mDragView.getLeft();
2198            snapToPage(getPageNearestToCenterOfScreen());
2199            disableFreeScroll();
2200            onStartReordering();
2201            return true;
2202        }
2203        return false;
2204    }
2205
2206    boolean isReordering(boolean testTouchState) {
2207        boolean state = mIsReordering;
2208        if (testTouchState) {
2209            state &= (mTouchState == TOUCH_STATE_REORDERING);
2210        }
2211        return state;
2212    }
2213    void endReordering() {
2214        // For simplicity, we call endReordering sometimes even if reordering was never started.
2215        // In that case, we don't want to do anything.
2216        if (!mReorderingStarted) return;
2217        mReorderingStarted = false;
2218
2219        // If we haven't flung-to-delete the current child, then we just animate the drag view
2220        // back into position
2221        final Runnable onCompleteRunnable = new Runnable() {
2222            @Override
2223            public void run() {
2224                onEndReordering();
2225            }
2226        };
2227
2228        mPostReorderingPreZoomInRunnable = new Runnable() {
2229            public void run() {
2230                onCompleteRunnable.run();
2231                enableFreeScroll();
2232            };
2233        };
2234
2235        mPostReorderingPreZoomInRemainingAnimationCount =
2236                NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2237        // Snap to the current page
2238        snapToPage(indexOfChild(mDragView), 0);
2239        // Animate the drag view back to the front position
2240        animateDragViewToOriginalPosition();
2241    }
2242
2243    /* Accessibility */
2244    @SuppressWarnings("deprecation")
2245    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
2246    @Override
2247    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2248        super.onInitializeAccessibilityNodeInfo(info);
2249        info.setScrollable(getPageCount() > 1);
2250        if (getCurrentPage() < getPageCount() - 1) {
2251            info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2252        }
2253        if (getCurrentPage() > 0) {
2254            info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2255        }
2256        info.setClassName(getClass().getName());
2257
2258        // Accessibility-wise, PagedView doesn't support long click, so disabling it.
2259        // Besides disabling the accessibility long-click, this also prevents this view from getting
2260        // accessibility focus.
2261        info.setLongClickable(false);
2262        if (Utilities.ATLEAST_LOLLIPOP) {
2263            info.removeAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_LONG_CLICK);
2264        }
2265    }
2266
2267    @Override
2268    public void sendAccessibilityEvent(int eventType) {
2269        // Don't let the view send real scroll events.
2270        if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2271            super.sendAccessibilityEvent(eventType);
2272        }
2273    }
2274
2275    @Override
2276    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2277        super.onInitializeAccessibilityEvent(event);
2278        event.setScrollable(getPageCount() > 1);
2279    }
2280
2281    @Override
2282    public boolean performAccessibilityAction(int action, Bundle arguments) {
2283        if (super.performAccessibilityAction(action, arguments)) {
2284            return true;
2285        }
2286        switch (action) {
2287            case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2288                if (getCurrentPage() < getPageCount() - 1) {
2289                    scrollRight();
2290                    return true;
2291                }
2292            } break;
2293            case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2294                if (getCurrentPage() > 0) {
2295                    scrollLeft();
2296                    return true;
2297                }
2298            } break;
2299        }
2300        return false;
2301    }
2302
2303    protected String getCurrentPageDescription() {
2304        return getContext().getString(R.string.default_scroll_format,
2305                getNextPage() + 1, getChildCount());
2306    }
2307
2308    @Override
2309    public boolean onHoverEvent(android.view.MotionEvent event) {
2310        return true;
2311    }
2312}
2313