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