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