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