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