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