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