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