NotificationStackScrollLayout.java revision bf370992508c55d1f2493923bdc1834a0710e4ba
1/*
2 * Copyright (C) 2014 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.systemui.statusbar.stack;
18
19import android.content.Context;
20import android.content.res.Configuration;
21import android.graphics.Canvas;
22import android.graphics.Paint;
23import android.util.AttributeSet;
24import android.util.Log;
25import android.view.MotionEvent;
26import android.view.VelocityTracker;
27import android.view.View;
28import android.view.ViewConfiguration;
29import android.view.ViewGroup;
30import android.view.ViewTreeObserver;
31import android.view.animation.AnimationUtils;
32import android.widget.OverScroller;
33import com.android.systemui.ExpandHelper;
34import com.android.systemui.R;
35import com.android.systemui.SwipeHelper;
36import com.android.systemui.statusbar.ActivatableNotificationView;
37import com.android.systemui.statusbar.ExpandableNotificationRow;
38import com.android.systemui.statusbar.ExpandableView;
39import com.android.systemui.statusbar.SpeedBumpView;
40import com.android.systemui.statusbar.policy.ScrollAdapter;
41import com.android.systemui.statusbar.stack.StackScrollState.ViewState;
42
43import java.util.ArrayList;
44
45/**
46 * A layout which handles a dynamic amount of notifications and presents them in a scrollable stack.
47 */
48public class NotificationStackScrollLayout extends ViewGroup
49        implements SwipeHelper.Callback, ExpandHelper.Callback, ScrollAdapter,
50        ExpandableView.OnHeightChangedListener {
51
52    private static final String TAG = "NotificationStackScrollLayout";
53    private static final boolean DEBUG = false;
54    private static final float RUBBER_BAND_FACTOR_NORMAL = 0.35f;
55    private static final float RUBBER_BAND_FACTOR_AFTER_EXPAND = 0.15f;
56    private static final float RUBBER_BAND_FACTOR_ON_PANEL_EXPAND = 0.21f;
57
58    /**
59     * Sentinel value for no current active pointer. Used by {@link #mActivePointerId}.
60     */
61    private static final int INVALID_POINTER = -1;
62
63    private ExpandHelper mExpandHelper;
64    private SwipeHelper mSwipeHelper;
65    private boolean mSwipingInProgress;
66    private int mCurrentStackHeight = Integer.MAX_VALUE;
67    private int mOwnScrollY;
68    private int mMaxLayoutHeight;
69
70    private VelocityTracker mVelocityTracker;
71    private OverScroller mScroller;
72    private int mTouchSlop;
73    private int mMinimumVelocity;
74    private int mMaximumVelocity;
75    private int mOverflingDistance;
76    private float mMaxOverScroll;
77    private boolean mIsBeingDragged;
78    private int mLastMotionY;
79    private int mDownX;
80    private int mActivePointerId;
81
82    private int mSidePaddings;
83    private Paint mDebugPaint;
84    private int mContentHeight;
85    private int mCollapsedSize;
86    private int mBottomStackSlowDownHeight;
87    private int mBottomStackPeekSize;
88    private int mPaddingBetweenElements;
89    private int mPaddingBetweenElementsDimmed;
90    private int mPaddingBetweenElementsNormal;
91    private int mTopPadding;
92
93    /**
94     * The algorithm which calculates the properties for our children
95     */
96    private StackScrollAlgorithm mStackScrollAlgorithm;
97
98    /**
99     * The current State this Layout is in
100     */
101    private StackScrollState mCurrentStackScrollState = new StackScrollState(this);
102    private AmbientState mAmbientState = new AmbientState();
103    private ArrayList<View> mChildrenToAddAnimated = new ArrayList<View>();
104    private ArrayList<View> mChildrenToRemoveAnimated = new ArrayList<View>();
105    private ArrayList<View> mSnappedBackChildren = new ArrayList<View>();
106    private ArrayList<View> mDragAnimPendingChildren = new ArrayList<View>();
107    private ArrayList<View> mChildrenChangingPositions = new ArrayList<View>();
108    private ArrayList<AnimationEvent> mAnimationEvents
109            = new ArrayList<AnimationEvent>();
110    private ArrayList<View> mSwipedOutViews = new ArrayList<View>();
111    private final StackStateAnimator mStateAnimator = new StackStateAnimator(this);
112    private boolean mAnimationsEnabled;
113    private boolean mChangePositionInProgress;
114
115    /**
116     * The raw amount of the overScroll on the top, which is not rubber-banded.
117     */
118    private float mOverScrolledTopPixels;
119
120    /**
121     * The raw amount of the overScroll on the bottom, which is not rubber-banded.
122     */
123    private float mOverScrolledBottomPixels;
124
125    private OnChildLocationsChangedListener mListener;
126    private OnOverscrollTopChangedListener mOverscrollTopChangedListener;
127    private ExpandableView.OnHeightChangedListener mOnHeightChangedListener;
128    private boolean mNeedsAnimation;
129    private boolean mTopPaddingNeedsAnimation;
130    private boolean mDimmedNeedsAnimation;
131    private boolean mDarkNeedsAnimation;
132    private boolean mActivateNeedsAnimation;
133    private boolean mIsExpanded = true;
134    private boolean mChildrenUpdateRequested;
135    private SpeedBumpView mSpeedBumpView;
136    private boolean mIsExpansionChanging;
137    private boolean mExpandingNotification;
138    private boolean mExpandedInThisMotion;
139    private boolean mScrollingEnabled;
140
141    /**
142     * Was the scroller scrolled to the top when the down motion was observed?
143     */
144    private boolean mScrolledToTopOnFirstDown;
145
146    /**
147     * The minimal amount of over scroll which is needed in order to switch to the quick settings
148     * when over scrolling on a expanded card.
149     */
150    private float mMinTopOverScrollToEscape;
151    private int mIntrinsicPadding;
152    private int mNotificationTopPadding;
153    private int mMinStackHeight;
154    private boolean mDontReportNextOverScroll;
155
156    /**
157     * The maximum scrollPosition which we are allowed to reach when a notification was expanded.
158     * This is needed to avoid scrolling too far after the notification was collapsed in the same
159     * motion.
160     */
161    private int mMaxScrollAfterExpand;
162    private OnLongClickListener mLongClickListener;
163
164    /**
165     * Should in this touch motion only be scrolling allowed? It's true when the scroller was
166     * animating.
167     */
168    private boolean mOnlyScrollingInThisMotion;
169    private boolean mTouchEnabled = true;
170    private ViewTreeObserver.OnPreDrawListener mChildrenUpdater
171            = new ViewTreeObserver.OnPreDrawListener() {
172        @Override
173        public boolean onPreDraw() {
174            updateChildren();
175            mChildrenUpdateRequested = false;
176            getViewTreeObserver().removeOnPreDrawListener(this);
177            return true;
178        }
179    };
180
181    public NotificationStackScrollLayout(Context context) {
182        this(context, null);
183    }
184
185    public NotificationStackScrollLayout(Context context, AttributeSet attrs) {
186        this(context, attrs, 0);
187    }
188
189    public NotificationStackScrollLayout(Context context, AttributeSet attrs, int defStyleAttr) {
190        this(context, attrs, defStyleAttr, 0);
191    }
192
193    public NotificationStackScrollLayout(Context context, AttributeSet attrs, int defStyleAttr,
194            int defStyleRes) {
195        super(context, attrs, defStyleAttr, defStyleRes);
196        initView(context);
197        if (DEBUG) {
198            setWillNotDraw(false);
199            mDebugPaint = new Paint();
200            mDebugPaint.setColor(0xffff0000);
201            mDebugPaint.setStrokeWidth(2);
202            mDebugPaint.setStyle(Paint.Style.STROKE);
203        }
204    }
205
206    @Override
207    protected void onDraw(Canvas canvas) {
208        if (DEBUG) {
209            int y = mCollapsedSize;
210            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
211            y = (int) (getLayoutHeight() - mBottomStackPeekSize
212                    - mBottomStackSlowDownHeight);
213            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
214            y = (int) (getLayoutHeight() - mBottomStackPeekSize);
215            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
216            y = (int) getLayoutHeight();
217            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
218            y = getHeight() - getEmptyBottomMargin();
219            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
220        }
221    }
222
223    private void initView(Context context) {
224        mScroller = new OverScroller(getContext());
225        setFocusable(true);
226        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
227        setClipChildren(false);
228        final ViewConfiguration configuration = ViewConfiguration.get(context);
229        mTouchSlop = configuration.getScaledTouchSlop();
230        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
231        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
232        mOverflingDistance = configuration.getScaledOverflingDistance();
233        float densityScale = getResources().getDisplayMetrics().density;
234        float pagingTouchSlop = ViewConfiguration.get(getContext()).getScaledPagingTouchSlop();
235        mSwipeHelper = new SwipeHelper(SwipeHelper.X, this, densityScale, pagingTouchSlop);
236        mSwipeHelper.setLongPressListener(mLongClickListener);
237
238        mSidePaddings = context.getResources()
239                .getDimensionPixelSize(R.dimen.notification_side_padding);
240        mCollapsedSize = context.getResources()
241                .getDimensionPixelSize(R.dimen.notification_min_height);
242        mBottomStackPeekSize = context.getResources()
243                .getDimensionPixelSize(R.dimen.bottom_stack_peek_amount);
244        mStackScrollAlgorithm = new StackScrollAlgorithm(context);
245        mStackScrollAlgorithm.setDimmed(mAmbientState.isDimmed());
246        mPaddingBetweenElementsDimmed = context.getResources()
247                .getDimensionPixelSize(R.dimen.notification_padding_dimmed);
248        mPaddingBetweenElementsNormal = context.getResources()
249                .getDimensionPixelSize(R.dimen.notification_padding);
250        updatePadding(mAmbientState.isDimmed());
251        int minHeight = getResources().getDimensionPixelSize(R.dimen.notification_min_height);
252        int maxHeight = getResources().getDimensionPixelSize(R.dimen.notification_max_height);
253        mExpandHelper = new ExpandHelper(getContext(), this,
254                minHeight, maxHeight);
255        mExpandHelper.setEventSource(this);
256        mExpandHelper.setScrollAdapter(this);
257        mMinTopOverScrollToEscape = getResources().getDimensionPixelSize(
258                R.dimen.min_top_overscroll_to_qs);
259        mNotificationTopPadding = getResources().getDimensionPixelSize(
260                R.dimen.notifications_top_padding);
261        mMinStackHeight = getResources().getDimensionPixelSize(R.dimen.collapsed_stack_height);
262    }
263
264    private void updatePadding(boolean dimmed) {
265        mPaddingBetweenElements = dimmed
266                ? mPaddingBetweenElementsDimmed
267                : mPaddingBetweenElementsNormal;
268        mBottomStackSlowDownHeight = mStackScrollAlgorithm.getBottomStackSlowDownLength();
269        updateContentHeight();
270        notifyHeightChangeListener(null);
271    }
272
273    private void notifyHeightChangeListener(ExpandableView view) {
274        if (mOnHeightChangedListener != null) {
275            mOnHeightChangedListener.onHeightChanged(view);
276        }
277    }
278
279    @Override
280    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
281        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
282        int mode = MeasureSpec.getMode(widthMeasureSpec);
283        int size = MeasureSpec.getSize(widthMeasureSpec);
284        int childMeasureSpec = MeasureSpec.makeMeasureSpec(size - 2 * mSidePaddings, mode);
285        measureChildren(childMeasureSpec, heightMeasureSpec);
286    }
287
288    @Override
289    protected void onLayout(boolean changed, int l, int t, int r, int b) {
290
291        // we layout all our children centered on the top
292        float centerX = getWidth() / 2.0f;
293        for (int i = 0; i < getChildCount(); i++) {
294            View child = getChildAt(i);
295            float width = child.getMeasuredWidth();
296            float height = child.getMeasuredHeight();
297            child.layout((int) (centerX - width / 2.0f),
298                    0,
299                    (int) (centerX + width / 2.0f),
300                    (int) height);
301        }
302        setMaxLayoutHeight(getHeight());
303        updateContentHeight();
304        updateScrollPositionIfNecessary();
305        requestChildrenUpdate();
306    }
307
308    public void updateSpeedBumpIndex(int newIndex) {
309        int currentIndex = indexOfChild(mSpeedBumpView);
310
311        // If we are currently layouted before the new speed bump index, we have to decrease it.
312        boolean validIndex = newIndex > 0;
313        if (newIndex > getChildCount() - 1) {
314            validIndex = false;
315            newIndex = -1;
316        }
317        if (validIndex && currentIndex != newIndex) {
318            changeViewPosition(mSpeedBumpView, newIndex);
319        }
320        updateSpeedBump(validIndex);
321        mAmbientState.setSpeedBumpIndex(newIndex);
322    }
323
324    public void setChildLocationsChangedListener(OnChildLocationsChangedListener listener) {
325        mListener = listener;
326    }
327
328    /**
329     * Returns the location the given child is currently rendered at.
330     *
331     * @param child the child to get the location for
332     * @return one of {@link ViewState}'s <code>LOCATION_*</code> constants
333     */
334    public int getChildLocation(View child) {
335        ViewState childViewState = mCurrentStackScrollState.getViewStateForView(child);
336        if (childViewState == null) {
337            return ViewState.LOCATION_UNKNOWN;
338        }
339        return childViewState.location;
340    }
341
342    private void setMaxLayoutHeight(int maxLayoutHeight) {
343        mMaxLayoutHeight = maxLayoutHeight;
344        updateAlgorithmHeightAndPadding();
345    }
346
347    private void updateAlgorithmHeightAndPadding() {
348        mStackScrollAlgorithm.setLayoutHeight(getLayoutHeight());
349        mStackScrollAlgorithm.setTopPadding(mTopPadding);
350    }
351
352    /**
353     * @return whether the height of the layout needs to be adapted, in order to ensure that the
354     *         last child is not in the bottom stack.
355     */
356    private boolean needsHeightAdaption() {
357        return getNotGoneChildCount() > 1;
358    }
359
360    /**
361     * Updates the children views according to the stack scroll algorithm. Call this whenever
362     * modifications to {@link #mOwnScrollY} are performed to reflect it in the view layout.
363     */
364    private void updateChildren() {
365        mAmbientState.setScrollY(mOwnScrollY);
366        mStackScrollAlgorithm.getStackScrollState(mAmbientState, mCurrentStackScrollState);
367        if (!isCurrentlyAnimating() && !mNeedsAnimation) {
368            applyCurrentState();
369        } else {
370            startAnimationToState();
371        }
372    }
373
374    private void requestChildrenUpdate() {
375        if (!mChildrenUpdateRequested) {
376            getViewTreeObserver().addOnPreDrawListener(mChildrenUpdater);
377            mChildrenUpdateRequested = true;
378            invalidate();
379        }
380    }
381
382    private boolean isCurrentlyAnimating() {
383        return mStateAnimator.isRunning();
384    }
385
386    private void updateScrollPositionIfNecessary() {
387        int scrollRange = getScrollRange();
388        if (scrollRange < mOwnScrollY) {
389            mOwnScrollY = scrollRange;
390        }
391    }
392
393    public int getTopPadding() {
394        return mTopPadding;
395    }
396
397    private void setTopPadding(int topPadding, boolean animate) {
398        if (mTopPadding != topPadding) {
399            mTopPadding = topPadding;
400            updateAlgorithmHeightAndPadding();
401            updateContentHeight();
402            if (animate && mAnimationsEnabled && mIsExpanded) {
403                mTopPaddingNeedsAnimation = true;
404                mNeedsAnimation =  true;
405            }
406            requestChildrenUpdate();
407            notifyHeightChangeListener(null);
408        }
409    }
410
411    /**
412     * Update the height of the stack to a new height.
413     *
414     * @param height the new height of the stack
415     */
416    public void setStackHeight(float height) {
417        setIsExpanded(height > 0.0f);
418        int newStackHeight = (int) height;
419        int itemHeight = getItemHeight();
420        int bottomStackPeekSize = mBottomStackPeekSize;
421        int minStackHeight = itemHeight + bottomStackPeekSize;
422        int stackHeight;
423        if (newStackHeight - mTopPadding >= minStackHeight) {
424            setTranslationY(0);
425            stackHeight = newStackHeight;
426        } else {
427
428            // We did not reach the position yet where we actually start growing,
429            // so we translate the stack upwards.
430            int translationY = (newStackHeight - minStackHeight);
431            // A slight parallax effect is introduced in order for the stack to catch up with
432            // the top card.
433            float partiallyThere = (float) (newStackHeight - mTopPadding) / minStackHeight;
434            partiallyThere = Math.max(0, partiallyThere);
435            translationY += (1 - partiallyThere) * bottomStackPeekSize;
436            setTranslationY(translationY - mTopPadding);
437            stackHeight = (int) (height - (translationY - mTopPadding));
438        }
439        if (stackHeight != mCurrentStackHeight) {
440            mCurrentStackHeight = stackHeight;
441            updateAlgorithmHeightAndPadding();
442            requestChildrenUpdate();
443        }
444    }
445
446    /**
447     * Get the current height of the view. This is at most the msize of the view given by a the
448     * layout but it can also be made smaller by setting {@link #mCurrentStackHeight}
449     *
450     * @return either the layout height or the externally defined height, whichever is smaller
451     */
452    private int getLayoutHeight() {
453        return Math.min(mMaxLayoutHeight, mCurrentStackHeight);
454    }
455
456    public int getItemHeight() {
457        return mCollapsedSize;
458    }
459
460    public int getBottomStackPeekSize() {
461        return mBottomStackPeekSize;
462    }
463
464    public void setLongPressListener(View.OnLongClickListener listener) {
465        mSwipeHelper.setLongPressListener(listener);
466        mLongClickListener = listener;
467    }
468
469    public void onChildDismissed(View v) {
470        if (DEBUG) Log.v(TAG, "onChildDismissed: " + v);
471        final View veto = v.findViewById(R.id.veto);
472        if (veto != null && veto.getVisibility() != View.GONE) {
473            veto.performClick();
474        }
475        setSwipingInProgress(false);
476        if (mDragAnimPendingChildren.contains(v)) {
477            // We start the swipe and finish it in the same frame, we don't want any animation
478            // for the drag
479            mDragAnimPendingChildren.remove(v);
480        }
481        mSwipedOutViews.add(v);
482        mAmbientState.onDragFinished(v);
483    }
484
485    @Override
486    public void onChildSnappedBack(View animView) {
487        mAmbientState.onDragFinished(animView);
488        if (!mDragAnimPendingChildren.contains(animView)) {
489            if (mAnimationsEnabled) {
490                mSnappedBackChildren.add(animView);
491                mNeedsAnimation = true;
492            }
493            requestChildrenUpdate();
494        } else {
495            // We start the swipe and snap back in the same frame, we don't want any animation
496            mDragAnimPendingChildren.remove(animView);
497        }
498    }
499
500    @Override
501    public boolean updateSwipeProgress(View animView, boolean dismissable, float swipeProgress) {
502        return false;
503    }
504
505    public void onBeginDrag(View v) {
506        setSwipingInProgress(true);
507        mAmbientState.onBeginDrag(v);
508        if (mAnimationsEnabled) {
509            mDragAnimPendingChildren.add(v);
510            mNeedsAnimation = true;
511        }
512        requestChildrenUpdate();
513    }
514
515    public void onDragCancelled(View v) {
516        setSwipingInProgress(false);
517    }
518
519    public View getChildAtPosition(MotionEvent ev) {
520        return getChildAtPosition(ev.getX(), ev.getY());
521    }
522
523    public ExpandableView getChildAtRawPosition(float touchX, float touchY) {
524        int[] location = new int[2];
525        getLocationOnScreen(location);
526        return getChildAtPosition(touchX - location[0], touchY - location[1]);
527    }
528
529    public ExpandableView getChildAtPosition(float touchX, float touchY) {
530        // find the view under the pointer, accounting for GONE views
531        final int count = getChildCount();
532        for (int childIdx = 0; childIdx < count; childIdx++) {
533            ExpandableView slidingChild = (ExpandableView) getChildAt(childIdx);
534            if (slidingChild.getVisibility() == GONE) {
535                continue;
536            }
537            float childTop = slidingChild.getTranslationY();
538            float top = childTop + slidingChild.getClipTopAmount();
539            float bottom = childTop + slidingChild.getActualHeight();
540            int left = slidingChild.getLeft();
541            int right = slidingChild.getRight();
542
543            if (touchY >= top && touchY <= bottom && touchX >= left && touchX <= right) {
544                return slidingChild;
545            }
546        }
547        return null;
548    }
549
550    public boolean canChildBeExpanded(View v) {
551        return v instanceof ExpandableNotificationRow
552                && ((ExpandableNotificationRow) v).isExpandable();
553    }
554
555    public void setUserExpandedChild(View v, boolean userExpanded) {
556        if (v instanceof ExpandableNotificationRow) {
557            ((ExpandableNotificationRow) v).setUserExpanded(userExpanded);
558        }
559    }
560
561    public void setUserLockedChild(View v, boolean userLocked) {
562        if (v instanceof ExpandableNotificationRow) {
563            ((ExpandableNotificationRow) v).setUserLocked(userLocked);
564        }
565        removeLongPressCallback();
566        requestDisallowInterceptTouchEvent(true);
567    }
568
569    @Override
570    public void expansionStateChanged(boolean isExpanding) {
571        mExpandingNotification = isExpanding;
572        if (!mExpandedInThisMotion) {
573            mMaxScrollAfterExpand = mOwnScrollY;
574            mExpandedInThisMotion = true;
575        }
576    }
577
578    public void setScrollingEnabled(boolean enable) {
579        mScrollingEnabled = enable;
580    }
581
582    public void setExpandingEnabled(boolean enable) {
583        mExpandHelper.setEnabled(enable);
584    }
585
586    private boolean isScrollingEnabled() {
587        return mScrollingEnabled;
588    }
589
590    public View getChildContentView(View v) {
591        return v;
592    }
593
594    public boolean canChildBeDismissed(View v) {
595        final View veto = v.findViewById(R.id.veto);
596        return (veto != null && veto.getVisibility() != View.GONE);
597    }
598
599    private void setSwipingInProgress(boolean isSwiped) {
600        mSwipingInProgress = isSwiped;
601        if(isSwiped) {
602            requestDisallowInterceptTouchEvent(true);
603        }
604    }
605
606    @Override
607    protected void onConfigurationChanged(Configuration newConfig) {
608        super.onConfigurationChanged(newConfig);
609        float densityScale = getResources().getDisplayMetrics().density;
610        mSwipeHelper.setDensityScale(densityScale);
611        float pagingTouchSlop = ViewConfiguration.get(getContext()).getScaledPagingTouchSlop();
612        mSwipeHelper.setPagingTouchSlop(pagingTouchSlop);
613        initView(getContext());
614    }
615
616    public void dismissRowAnimated(View child, int vel) {
617        mSwipeHelper.dismissChild(child, vel);
618    }
619
620    @Override
621    public boolean onTouchEvent(MotionEvent ev) {
622        if (!isEnabled()) {
623            return false;
624        }
625        boolean isCancelOrUp = ev.getActionMasked() == MotionEvent.ACTION_CANCEL
626                || ev.getActionMasked()== MotionEvent.ACTION_UP;
627        boolean expandWantsIt = false;
628        if (!mSwipingInProgress && !mOnlyScrollingInThisMotion) {
629            if (isCancelOrUp) {
630                mExpandHelper.onlyObserveMovements(false);
631            }
632            boolean wasExpandingBefore = mExpandingNotification;
633            expandWantsIt = mExpandHelper.onTouchEvent(ev);
634            if (mExpandedInThisMotion && !mExpandingNotification && wasExpandingBefore) {
635                dispatchDownEventToScroller(ev);
636            }
637        }
638        boolean scrollerWantsIt = false;
639        if (!mSwipingInProgress && !mExpandingNotification) {
640            scrollerWantsIt = onScrollTouch(ev);
641        }
642        boolean horizontalSwipeWantsIt = false;
643        if (!mIsBeingDragged
644                && !mExpandingNotification
645                && !mExpandedInThisMotion
646                && !mOnlyScrollingInThisMotion) {
647            horizontalSwipeWantsIt = mSwipeHelper.onTouchEvent(ev);
648        }
649        return horizontalSwipeWantsIt || scrollerWantsIt || expandWantsIt || super.onTouchEvent(ev);
650    }
651
652    private void dispatchDownEventToScroller(MotionEvent ev) {
653        MotionEvent downEvent = MotionEvent.obtain(ev);
654        downEvent.setAction(MotionEvent.ACTION_DOWN);
655        onScrollTouch(downEvent);
656        downEvent.recycle();
657    }
658
659    private boolean onScrollTouch(MotionEvent ev) {
660        if (!isScrollingEnabled()) {
661            return false;
662        }
663        initVelocityTrackerIfNotExists();
664        mVelocityTracker.addMovement(ev);
665
666        final int action = ev.getAction();
667
668        switch (action & MotionEvent.ACTION_MASK) {
669            case MotionEvent.ACTION_DOWN: {
670                if (getChildCount() == 0 || !isInContentBounds(ev)) {
671                    return false;
672                }
673                boolean isBeingDragged = !mScroller.isFinished();
674                setIsBeingDragged(isBeingDragged);
675
676                /*
677                 * If being flinged and user touches, stop the fling. isFinished
678                 * will be false if being flinged.
679                 */
680                if (!mScroller.isFinished()) {
681                    mScroller.forceFinished(true);
682                }
683
684                // Remember where the motion event started
685                mLastMotionY = (int) ev.getY();
686                mDownX = (int) ev.getX();
687                mActivePointerId = ev.getPointerId(0);
688                break;
689            }
690            case MotionEvent.ACTION_MOVE:
691                final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
692                if (activePointerIndex == -1) {
693                    Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
694                    break;
695                }
696
697                final int y = (int) ev.getY(activePointerIndex);
698                final int x = (int) ev.getX(activePointerIndex);
699                int deltaY = mLastMotionY - y;
700                final int xDiff = Math.abs(x - mDownX);
701                final int yDiff = Math.abs(deltaY);
702                if (!mIsBeingDragged && yDiff > mTouchSlop && yDiff > xDiff) {
703                    setIsBeingDragged(true);
704                    if (deltaY > 0) {
705                        deltaY -= mTouchSlop;
706                    } else {
707                        deltaY += mTouchSlop;
708                    }
709                }
710                if (mIsBeingDragged) {
711                    // Scroll to follow the motion event
712                    mLastMotionY = y;
713                    int range = getScrollRange();
714                    if (mExpandedInThisMotion) {
715                        range = Math.min(range, mMaxScrollAfterExpand);
716                    }
717
718                    float scrollAmount;
719                    if (deltaY < 0) {
720                        scrollAmount = overScrollDown(deltaY);
721                    } else {
722                        scrollAmount = overScrollUp(deltaY, range);
723                    }
724
725                    // Calling overScrollBy will call onOverScrolled, which
726                    // calls onScrollChanged if applicable.
727                    if (scrollAmount != 0.0f) {
728                        // The scrolling motion could not be compensated with the
729                        // existing overScroll, we have to scroll the view
730                        overScrollBy(0, (int) scrollAmount, 0, mOwnScrollY,
731                                0, range, 0, getHeight() / 2, true);
732                    }
733                }
734                break;
735            case MotionEvent.ACTION_UP:
736                if (mIsBeingDragged) {
737                    final VelocityTracker velocityTracker = mVelocityTracker;
738                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
739                    int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
740
741                    if (shouldOverScrollFling(initialVelocity)) {
742                        onOverScrollFling(true, initialVelocity);
743                    } else {
744                        if (getChildCount() > 0) {
745                            if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
746                                float currentOverScrollTop = getCurrentOverScrollAmount(true);
747                                if (currentOverScrollTop == 0.0f || initialVelocity > 0) {
748                                    fling(-initialVelocity);
749                                } else {
750                                    onOverScrollFling(false, initialVelocity);
751                                }
752                            } else {
753                                if (mScroller.springBack(mScrollX, mOwnScrollY, 0, 0, 0,
754                                        getScrollRange())) {
755                                    postInvalidateOnAnimation();
756                                }
757                            }
758                        }
759                    }
760
761                    mActivePointerId = INVALID_POINTER;
762                    endDrag();
763                }
764
765                break;
766            case MotionEvent.ACTION_CANCEL:
767                if (mIsBeingDragged && getChildCount() > 0) {
768                    if (mScroller.springBack(mScrollX, mOwnScrollY, 0, 0, 0, getScrollRange())) {
769                        postInvalidateOnAnimation();
770                    }
771                    mActivePointerId = INVALID_POINTER;
772                    endDrag();
773                }
774                break;
775            case MotionEvent.ACTION_POINTER_DOWN: {
776                final int index = ev.getActionIndex();
777                mLastMotionY = (int) ev.getY(index);
778                mDownX = (int) ev.getX(index);
779                mActivePointerId = ev.getPointerId(index);
780                break;
781            }
782            case MotionEvent.ACTION_POINTER_UP:
783                onSecondaryPointerUp(ev);
784                mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
785                mDownX = (int) ev.getX(ev.findPointerIndex(mActivePointerId));
786                break;
787        }
788        return true;
789    }
790
791    private void onOverScrollFling(boolean open, int initialVelocity) {
792        if (mOverscrollTopChangedListener != null) {
793            mOverscrollTopChangedListener.flingTopOverscroll(initialVelocity, open);
794        }
795        mDontReportNextOverScroll = true;
796        setOverScrollAmount(0.0f, true, false);
797    }
798
799    /**
800     * Perform a scroll upwards and adapt the overscroll amounts accordingly
801     *
802     * @param deltaY The amount to scroll upwards, has to be positive.
803     * @return The amount of scrolling to be performed by the scroller,
804     *         not handled by the overScroll amount.
805     */
806    private float overScrollUp(int deltaY, int range) {
807        deltaY = Math.max(deltaY, 0);
808        float currentTopAmount = getCurrentOverScrollAmount(true);
809        float newTopAmount = currentTopAmount - deltaY;
810        if (currentTopAmount > 0) {
811            setOverScrollAmount(newTopAmount, true /* onTop */,
812                    false /* animate */);
813        }
814        // Top overScroll might not grab all scrolling motion,
815        // we have to scroll as well.
816        float scrollAmount = newTopAmount < 0 ? -newTopAmount : 0.0f;
817        float newScrollY = mOwnScrollY + scrollAmount;
818        if (newScrollY > range) {
819            if (!mExpandedInThisMotion) {
820                float currentBottomPixels = getCurrentOverScrolledPixels(false);
821                // We overScroll on the top
822                setOverScrolledPixels(currentBottomPixels + newScrollY - range,
823                        false /* onTop */,
824                        false /* animate */);
825            }
826            mOwnScrollY = range;
827            scrollAmount = 0.0f;
828        }
829        return scrollAmount;
830    }
831
832    /**
833     * Perform a scroll downward and adapt the overscroll amounts accordingly
834     *
835     * @param deltaY The amount to scroll downwards, has to be negative.
836     * @return The amount of scrolling to be performed by the scroller,
837     *         not handled by the overScroll amount.
838     */
839    private float overScrollDown(int deltaY) {
840        deltaY = Math.min(deltaY, 0);
841        float currentBottomAmount = getCurrentOverScrollAmount(false);
842        float newBottomAmount = currentBottomAmount + deltaY;
843        if (currentBottomAmount > 0) {
844            setOverScrollAmount(newBottomAmount, false /* onTop */,
845                    false /* animate */);
846        }
847        // Bottom overScroll might not grab all scrolling motion,
848        // we have to scroll as well.
849        float scrollAmount = newBottomAmount < 0 ? newBottomAmount : 0.0f;
850        float newScrollY = mOwnScrollY + scrollAmount;
851        if (newScrollY < 0) {
852            float currentTopPixels = getCurrentOverScrolledPixels(true);
853            // We overScroll on the top
854            setOverScrolledPixels(currentTopPixels - newScrollY,
855                    true /* onTop */,
856                    false /* animate */);
857            mOwnScrollY = 0;
858            scrollAmount = 0.0f;
859        }
860        return scrollAmount;
861    }
862
863    private void onSecondaryPointerUp(MotionEvent ev) {
864        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
865                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
866        final int pointerId = ev.getPointerId(pointerIndex);
867        if (pointerId == mActivePointerId) {
868            // This was our active pointer going up. Choose a new
869            // active pointer and adjust accordingly.
870            // TODO: Make this decision more intelligent.
871            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
872            mLastMotionY = (int) ev.getY(newPointerIndex);
873            mActivePointerId = ev.getPointerId(newPointerIndex);
874            if (mVelocityTracker != null) {
875                mVelocityTracker.clear();
876            }
877        }
878    }
879
880    private void initVelocityTrackerIfNotExists() {
881        if (mVelocityTracker == null) {
882            mVelocityTracker = VelocityTracker.obtain();
883        }
884    }
885
886    private void recycleVelocityTracker() {
887        if (mVelocityTracker != null) {
888            mVelocityTracker.recycle();
889            mVelocityTracker = null;
890        }
891    }
892
893    private void initOrResetVelocityTracker() {
894        if (mVelocityTracker == null) {
895            mVelocityTracker = VelocityTracker.obtain();
896        } else {
897            mVelocityTracker.clear();
898        }
899    }
900
901    @Override
902    public void computeScroll() {
903        if (mScroller.computeScrollOffset()) {
904            // This is called at drawing time by ViewGroup.
905            int oldX = mScrollX;
906            int oldY = mOwnScrollY;
907            int x = mScroller.getCurrX();
908            int y = mScroller.getCurrY();
909
910            if (oldX != x || oldY != y) {
911                final int range = getScrollRange();
912                if (y < 0 && oldY >= 0 || y > range && oldY <= range) {
913                    float currVelocity = mScroller.getCurrVelocity();
914                    if (currVelocity >= mMinimumVelocity) {
915                        mMaxOverScroll = Math.abs(currVelocity) / 1000 * mOverflingDistance;
916                    }
917                }
918
919                overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range,
920                        0, (int) (mMaxOverScroll), false);
921                onScrollChanged(mScrollX, mOwnScrollY, oldX, oldY);
922            }
923
924            // Keep on drawing until the animation has finished.
925            postInvalidateOnAnimation();
926        }
927    }
928
929    @Override
930    protected boolean overScrollBy(int deltaX, int deltaY,
931            int scrollX, int scrollY,
932            int scrollRangeX, int scrollRangeY,
933            int maxOverScrollX, int maxOverScrollY,
934            boolean isTouchEvent) {
935
936        int newScrollY = scrollY + deltaY;
937
938        final int top = -maxOverScrollY;
939        final int bottom = maxOverScrollY + scrollRangeY;
940
941        boolean clampedY = false;
942        if (newScrollY > bottom) {
943            newScrollY = bottom;
944            clampedY = true;
945        } else if (newScrollY < top) {
946            newScrollY = top;
947            clampedY = true;
948        }
949
950        onOverScrolled(0, newScrollY, false, clampedY);
951
952        return clampedY;
953    }
954
955    /**
956     * Set the amount of overScrolled pixels which will force the view to apply a rubber-banded
957     * overscroll effect based on numPixels. By default this will also cancel animations on the
958     * same overScroll edge.
959     *
960     * @param numPixels The amount of pixels to overScroll by. These will be scaled according to
961     *                  the rubber-banding logic.
962     * @param onTop Should the effect be applied on top of the scroller.
963     * @param animate Should an animation be performed.
964     */
965    public void setOverScrolledPixels(float numPixels, boolean onTop, boolean animate) {
966        setOverScrollAmount(numPixels * getRubberBandFactor(onTop), onTop, animate, true);
967    }
968
969    /**
970     * Set the effective overScroll amount which will be directly reflected in the layout.
971     * By default this will also cancel animations on the same overScroll edge.
972     *
973     * @param amount The amount to overScroll by.
974     * @param onTop Should the effect be applied on top of the scroller.
975     * @param animate Should an animation be performed.
976     */
977    public void setOverScrollAmount(float amount, boolean onTop, boolean animate) {
978        setOverScrollAmount(amount, onTop, animate, true);
979    }
980
981    /**
982     * Set the effective overScroll amount which will be directly reflected in the layout.
983     *
984     * @param amount The amount to overScroll by.
985     * @param onTop Should the effect be applied on top of the scroller.
986     * @param animate Should an animation be performed.
987     * @param cancelAnimators Should running animations be cancelled.
988     */
989    public void setOverScrollAmount(float amount, boolean onTop, boolean animate,
990            boolean cancelAnimators) {
991        if (cancelAnimators) {
992            mStateAnimator.cancelOverScrollAnimators(onTop);
993        }
994        setOverScrollAmountInternal(amount, onTop, animate);
995    }
996
997    private void setOverScrollAmountInternal(float amount, boolean onTop, boolean animate) {
998        amount = Math.max(0, amount);
999        if (animate) {
1000            mStateAnimator.animateOverScrollToAmount(amount, onTop);
1001        } else {
1002            setOverScrolledPixels(amount / getRubberBandFactor(onTop), onTop);
1003            mAmbientState.setOverScrollAmount(amount, onTop);
1004            if (onTop) {
1005                notifyOverscrollTopListener(amount);
1006            }
1007            requestChildrenUpdate();
1008        }
1009    }
1010
1011    private void notifyOverscrollTopListener(float amount) {
1012        mExpandHelper.onlyObserveMovements(amount > 1.0f);
1013        if (mDontReportNextOverScroll) {
1014            mDontReportNextOverScroll = false;
1015            return;
1016        }
1017        if (mOverscrollTopChangedListener != null) {
1018            mOverscrollTopChangedListener.onOverscrollTopChanged(amount);
1019        }
1020    }
1021
1022    public void setOverscrollTopChangedListener(
1023            OnOverscrollTopChangedListener overscrollTopChangedListener) {
1024        mOverscrollTopChangedListener = overscrollTopChangedListener;
1025    }
1026
1027    public float getCurrentOverScrollAmount(boolean top) {
1028        return mAmbientState.getOverScrollAmount(top);
1029    }
1030
1031    public float getCurrentOverScrolledPixels(boolean top) {
1032        return top? mOverScrolledTopPixels : mOverScrolledBottomPixels;
1033    }
1034
1035    private void setOverScrolledPixels(float amount, boolean onTop) {
1036        if (onTop) {
1037            mOverScrolledTopPixels = amount;
1038        } else {
1039            mOverScrolledBottomPixels = amount;
1040        }
1041    }
1042
1043    private void customScrollTo(int y) {
1044        mOwnScrollY = y;
1045        updateChildren();
1046    }
1047
1048    @Override
1049    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
1050        // Treat animating scrolls differently; see #computeScroll() for why.
1051        if (!mScroller.isFinished()) {
1052            final int oldX = mScrollX;
1053            final int oldY = mOwnScrollY;
1054            mScrollX = scrollX;
1055            mOwnScrollY = scrollY;
1056            if (clampedY) {
1057                springBack();
1058            } else {
1059                onScrollChanged(mScrollX, mOwnScrollY, oldX, oldY);
1060                invalidateParentIfNeeded();
1061                updateChildren();
1062                float overScrollTop = getCurrentOverScrollAmount(true);
1063                if (mOwnScrollY < 0) {
1064                    notifyOverscrollTopListener(-mOwnScrollY);
1065                } else {
1066                    notifyOverscrollTopListener(overScrollTop);
1067                }
1068            }
1069        } else {
1070            customScrollTo(scrollY);
1071            scrollTo(scrollX, mScrollY);
1072        }
1073    }
1074
1075    private void springBack() {
1076        int scrollRange = getScrollRange();
1077        boolean overScrolledTop = mOwnScrollY <= 0;
1078        boolean overScrolledBottom = mOwnScrollY >= scrollRange;
1079        if (overScrolledTop || overScrolledBottom) {
1080            boolean onTop;
1081            float newAmount;
1082            if (overScrolledTop) {
1083                onTop = true;
1084                newAmount = -mOwnScrollY;
1085                mOwnScrollY = 0;
1086                mDontReportNextOverScroll = true;
1087            } else {
1088                onTop = false;
1089                newAmount = mOwnScrollY - scrollRange;
1090                mOwnScrollY = scrollRange;
1091            }
1092            setOverScrollAmount(newAmount, onTop, false);
1093            setOverScrollAmount(0.0f, onTop, true);
1094            mScroller.forceFinished(true);
1095        }
1096    }
1097
1098    private int getScrollRange() {
1099        int scrollRange = 0;
1100        ExpandableView firstChild = (ExpandableView) getFirstChildNotGone();
1101        if (firstChild != null) {
1102            int contentHeight = getContentHeight();
1103            int firstChildMaxExpandHeight = getMaxExpandHeight(firstChild);
1104            scrollRange = Math.max(0, contentHeight - mMaxLayoutHeight + mBottomStackPeekSize
1105                    + mBottomStackSlowDownHeight);
1106            if (scrollRange > 0) {
1107                View lastChild = getLastChildNotGone();
1108                // We want to at least be able collapse the first item and not ending in a weird
1109                // end state.
1110                scrollRange = Math.max(scrollRange, firstChildMaxExpandHeight - mCollapsedSize);
1111            }
1112        }
1113        return scrollRange;
1114    }
1115
1116    /**
1117     * @return the first child which has visibility unequal to GONE
1118     */
1119    private View getFirstChildNotGone() {
1120        int childCount = getChildCount();
1121        for (int i = 0; i < childCount; i++) {
1122            View child = getChildAt(i);
1123            if (child.getVisibility() != View.GONE) {
1124                return child;
1125            }
1126        }
1127        return null;
1128    }
1129
1130    /**
1131     * @return The first child which has visibility unequal to GONE which is currently below the
1132     *         given translationY or equal to it.
1133     */
1134    private View getFirstChildBelowTranlsationY(float translationY) {
1135        int childCount = getChildCount();
1136        for (int i = 0; i < childCount; i++) {
1137            View child = getChildAt(i);
1138            if (child.getVisibility() != View.GONE && child.getTranslationY() >= translationY) {
1139                return child;
1140            }
1141        }
1142        return null;
1143    }
1144
1145    /**
1146     * @return the last child which has visibility unequal to GONE
1147     */
1148    public View getLastChildNotGone() {
1149        int childCount = getChildCount();
1150        for (int i = childCount - 1; i >= 0; i--) {
1151            View child = getChildAt(i);
1152            if (child.getVisibility() != View.GONE) {
1153                return child;
1154            }
1155        }
1156        return null;
1157    }
1158
1159    /**
1160     * @return the number of children which have visibility unequal to GONE
1161     */
1162    public int getNotGoneChildCount() {
1163        int childCount = getChildCount();
1164        int count = 0;
1165        for (int i = 0; i < childCount; i++) {
1166            View child = getChildAt(i);
1167            if (child.getVisibility() != View.GONE) {
1168                count++;
1169            }
1170        }
1171        return count;
1172    }
1173
1174    private int getMaxExpandHeight(View view) {
1175        if (view instanceof ExpandableNotificationRow) {
1176            ExpandableNotificationRow row = (ExpandableNotificationRow) view;
1177            return row.getIntrinsicHeight();
1178        }
1179        return view.getHeight();
1180    }
1181
1182    private int getContentHeight() {
1183        return mContentHeight;
1184    }
1185
1186    private void updateContentHeight() {
1187        int height = 0;
1188        for (int i = 0; i < getChildCount(); i++) {
1189            View child = getChildAt(i);
1190            if (child.getVisibility() != View.GONE) {
1191                if (height != 0) {
1192                    // add the padding before this element
1193                    height += mPaddingBetweenElements;
1194                }
1195                if (child instanceof ExpandableNotificationRow) {
1196                    ExpandableNotificationRow row = (ExpandableNotificationRow) child;
1197                    height += row.getIntrinsicHeight();
1198                } else if (child instanceof ExpandableView) {
1199                    ExpandableView expandableView = (ExpandableView) child;
1200                    height += expandableView.getActualHeight();
1201                }
1202            }
1203        }
1204        mContentHeight = height + mTopPadding;
1205    }
1206
1207    /**
1208     * Fling the scroll view
1209     *
1210     * @param velocityY The initial velocity in the Y direction. Positive
1211     *                  numbers mean that the finger/cursor is moving down the screen,
1212     *                  which means we want to scroll towards the top.
1213     */
1214    private void fling(int velocityY) {
1215        if (getChildCount() > 0) {
1216            int scrollRange = getScrollRange();
1217
1218            float topAmount = getCurrentOverScrollAmount(true);
1219            float bottomAmount = getCurrentOverScrollAmount(false);
1220            if (velocityY < 0 && topAmount > 0) {
1221                mOwnScrollY -= (int) topAmount;
1222                mDontReportNextOverScroll = true;
1223                setOverScrollAmount(0, true, false);
1224                mMaxOverScroll = Math.abs(velocityY) / 1000f * getRubberBandFactor(true /* onTop */)
1225                        * mOverflingDistance + topAmount;
1226            } else if (velocityY > 0 && bottomAmount > 0) {
1227                mOwnScrollY += bottomAmount;
1228                setOverScrollAmount(0, false, false);
1229                mMaxOverScroll = Math.abs(velocityY) / 1000f
1230                        * getRubberBandFactor(false /* onTop */) * mOverflingDistance
1231                        +  bottomAmount;
1232            } else {
1233                // it will be set once we reach the boundary
1234                mMaxOverScroll = 0.0f;
1235            }
1236            mScroller.fling(mScrollX, mOwnScrollY, 1, velocityY, 0, 0, 0,
1237                    Math.max(0, scrollRange), 0, Integer.MAX_VALUE / 2);
1238
1239            postInvalidateOnAnimation();
1240        }
1241    }
1242
1243    /**
1244     * @return Whether a fling performed on the top overscroll edge lead to the expanded
1245     * overScroll view (i.e QS).
1246     */
1247    private boolean shouldOverScrollFling(int initialVelocity) {
1248        float topOverScroll = getCurrentOverScrollAmount(true);
1249        return mScrolledToTopOnFirstDown
1250                && !mExpandedInThisMotion
1251                && topOverScroll > mMinTopOverScrollToEscape
1252                && initialVelocity > 0;
1253    }
1254
1255    public void updateTopPadding(float qsHeight, int scrollY, boolean animate) {
1256        float start = qsHeight - scrollY + mNotificationTopPadding;
1257        float stackHeight = getHeight() - start;
1258        if (stackHeight <= mMinStackHeight) {
1259            float overflow = mMinStackHeight - stackHeight;
1260            stackHeight = mMinStackHeight;
1261            start = getHeight() - stackHeight;
1262            setTranslationY(overflow);
1263        } else {
1264            setTranslationY(0);
1265        }
1266        setTopPadding(clampPadding((int) start), animate);
1267    }
1268
1269    private int clampPadding(int desiredPadding) {
1270        return Math.max(desiredPadding, mIntrinsicPadding);
1271    }
1272
1273    private float getRubberBandFactor(boolean onTop) {
1274        if (!onTop) {
1275            return RUBBER_BAND_FACTOR_NORMAL;
1276        }
1277        if (mExpandedInThisMotion) {
1278            return RUBBER_BAND_FACTOR_AFTER_EXPAND;
1279        } else if (mIsExpansionChanging) {
1280            return RUBBER_BAND_FACTOR_ON_PANEL_EXPAND;
1281        } else if (mScrolledToTopOnFirstDown) {
1282            return 1.0f;
1283        }
1284        return RUBBER_BAND_FACTOR_NORMAL;
1285    }
1286
1287    private void endDrag() {
1288        setIsBeingDragged(false);
1289
1290        recycleVelocityTracker();
1291
1292        if (getCurrentOverScrollAmount(true /* onTop */) > 0) {
1293            setOverScrollAmount(0, true /* onTop */, true /* animate */);
1294        }
1295        if (getCurrentOverScrollAmount(false /* onTop */) > 0) {
1296            setOverScrollAmount(0, false /* onTop */, true /* animate */);
1297        }
1298    }
1299
1300    @Override
1301    public boolean onInterceptTouchEvent(MotionEvent ev) {
1302        initDownStates(ev);
1303        boolean expandWantsIt = false;
1304        if (!mSwipingInProgress && !mOnlyScrollingInThisMotion) {
1305            expandWantsIt = mExpandHelper.onInterceptTouchEvent(ev);
1306        }
1307        boolean scrollWantsIt = false;
1308        if (!mSwipingInProgress && !mExpandingNotification) {
1309            scrollWantsIt = onInterceptTouchEventScroll(ev);
1310        }
1311        boolean swipeWantsIt = false;
1312        if (!mIsBeingDragged
1313                && !mExpandingNotification
1314                && !mExpandedInThisMotion
1315                && !mOnlyScrollingInThisMotion) {
1316            swipeWantsIt = mSwipeHelper.onInterceptTouchEvent(ev);
1317        }
1318        return swipeWantsIt || scrollWantsIt || expandWantsIt || super.onInterceptTouchEvent(ev);
1319    }
1320
1321    private void initDownStates(MotionEvent ev) {
1322        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
1323            mExpandedInThisMotion = false;
1324            mOnlyScrollingInThisMotion = !mScroller.isFinished();
1325        }
1326    }
1327
1328    @Override
1329    protected void onViewRemoved(View child) {
1330        super.onViewRemoved(child);
1331        mStackScrollAlgorithm.notifyChildrenChanged(this);
1332        if (mChangePositionInProgress) {
1333            // This is only a position change, don't do anything special
1334            return;
1335        }
1336        ((ExpandableView) child).setOnHeightChangedListener(null);
1337        mCurrentStackScrollState.removeViewStateForView(child);
1338        updateScrollStateForRemovedChild(child);
1339        boolean animationGenerated = generateRemoveAnimation(child);
1340        if (animationGenerated && !mSwipedOutViews.contains(child)) {
1341            // Add this view to an overlay in order to ensure that it will still be temporary
1342            // drawn when removed
1343            getOverlay().add(child);
1344        }
1345    }
1346
1347    /**
1348     * Generate a remove animation for a child view.
1349     *
1350     * @param child The view to generate the remove animation for.
1351     * @return Whether an animation was generated.
1352     */
1353    private boolean generateRemoveAnimation(View child) {
1354        if (mIsExpanded && mAnimationsEnabled) {
1355            if (!mChildrenToAddAnimated.contains(child)) {
1356                // Generate Animations
1357                mChildrenToRemoveAnimated.add(child);
1358                mNeedsAnimation = true;
1359                return true;
1360            } else {
1361                mChildrenToAddAnimated.remove(child);
1362                return false;
1363            }
1364        }
1365        return false;
1366    }
1367
1368    /**
1369     * Updates the scroll position when a child was removed
1370     *
1371     * @param removedChild the removed child
1372     */
1373    private void updateScrollStateForRemovedChild(View removedChild) {
1374        int startingPosition = getPositionInLinearLayout(removedChild);
1375        int childHeight = removedChild.getHeight() + mPaddingBetweenElements;
1376        int endPosition = startingPosition + childHeight;
1377        if (endPosition <= mOwnScrollY) {
1378            // This child is fully scrolled of the top, so we have to deduct its height from the
1379            // scrollPosition
1380            mOwnScrollY -= childHeight;
1381        } else if (startingPosition < mOwnScrollY) {
1382            // This child is currently being scrolled into, set the scroll position to the start of
1383            // this child
1384            mOwnScrollY = startingPosition;
1385        }
1386    }
1387
1388    private int getPositionInLinearLayout(View requestedChild) {
1389        int position = 0;
1390        for (int i = 0; i < getChildCount(); i++) {
1391            View child = getChildAt(i);
1392            if (child == requestedChild) {
1393                return position;
1394            }
1395            if (child.getVisibility() != View.GONE) {
1396                position += child.getHeight();
1397                if (i < getChildCount()-1) {
1398                    position += mPaddingBetweenElements;
1399                }
1400            }
1401        }
1402        return 0;
1403    }
1404
1405    @Override
1406    protected void onViewAdded(View child) {
1407        super.onViewAdded(child);
1408        mStackScrollAlgorithm.notifyChildrenChanged(this);
1409        ((ExpandableView) child).setOnHeightChangedListener(this);
1410        generateAddAnimation(child);
1411    }
1412
1413    public void setAnimationsEnabled(boolean animationsEnabled) {
1414        mAnimationsEnabled = animationsEnabled;
1415    }
1416
1417    public boolean isAddOrRemoveAnimationPending() {
1418        return mNeedsAnimation
1419                && (!mChildrenToAddAnimated.isEmpty() || !mChildrenToRemoveAnimated.isEmpty());
1420    }
1421    /**
1422     * Generate an animation for an added child view.
1423     *
1424     * @param child The view to be added.
1425     */
1426    public void generateAddAnimation(View child) {
1427        if (mIsExpanded && mAnimationsEnabled && !mChangePositionInProgress) {
1428            // Generate Animations
1429            mChildrenToAddAnimated.add(child);
1430            mNeedsAnimation = true;
1431        }
1432    }
1433
1434    /**
1435     * Change the position of child to a new location
1436     *
1437     * @param child the view to change the position for
1438     * @param newIndex the new index
1439     */
1440    public void changeViewPosition(View child, int newIndex) {
1441        if (child != null && child.getParent() == this) {
1442            mChangePositionInProgress = true;
1443            removeView(child);
1444            addView(child, newIndex);
1445            mChangePositionInProgress = false;
1446            if (mIsExpanded && mAnimationsEnabled) {
1447                mChildrenChangingPositions.add(child);
1448                mNeedsAnimation = true;
1449            }
1450        }
1451    }
1452
1453    private void startAnimationToState() {
1454        if (mNeedsAnimation) {
1455            generateChildHierarchyEvents();
1456            mNeedsAnimation = false;
1457        }
1458        if (!mAnimationEvents.isEmpty() || isCurrentlyAnimating()) {
1459            mStateAnimator.startAnimationForEvents(mAnimationEvents, mCurrentStackScrollState);
1460            mAnimationEvents.clear();
1461        } else {
1462            applyCurrentState();
1463        }
1464    }
1465
1466    private void generateChildHierarchyEvents() {
1467        generateChildRemovalEvents();
1468        generateChildAdditionEvents();
1469        generatePositionChangeEvents();
1470        generateSnapBackEvents();
1471        generateDragEvents();
1472        generateTopPaddingEvent();
1473        generateActivateEvent();
1474        generateDimmedEvent();
1475        generateDarkEvent();
1476        mNeedsAnimation = false;
1477    }
1478
1479    private void generateSnapBackEvents() {
1480        for (View child : mSnappedBackChildren) {
1481            mAnimationEvents.add(new AnimationEvent(child,
1482                    AnimationEvent.ANIMATION_TYPE_SNAP_BACK));
1483        }
1484        mSnappedBackChildren.clear();
1485    }
1486
1487    private void generateDragEvents() {
1488        for (View child : mDragAnimPendingChildren) {
1489            mAnimationEvents.add(new AnimationEvent(child,
1490                    AnimationEvent.ANIMATION_TYPE_START_DRAG));
1491        }
1492        mDragAnimPendingChildren.clear();
1493    }
1494
1495    private void generateChildRemovalEvents() {
1496        for (View child : mChildrenToRemoveAnimated) {
1497            boolean childWasSwipedOut = mSwipedOutViews.contains(child);
1498            int animationType = childWasSwipedOut
1499                    ? AnimationEvent.ANIMATION_TYPE_REMOVE_SWIPED_OUT
1500                    : AnimationEvent.ANIMATION_TYPE_REMOVE;
1501            AnimationEvent event = new AnimationEvent(child, animationType);
1502
1503            // we need to know the view after this one
1504            event.viewAfterChangingView = getFirstChildBelowTranlsationY(child.getTranslationY());
1505            mAnimationEvents.add(event);
1506        }
1507        mSwipedOutViews.clear();
1508        mChildrenToRemoveAnimated.clear();
1509    }
1510
1511    private void generatePositionChangeEvents() {
1512        for (View child : mChildrenChangingPositions) {
1513            mAnimationEvents.add(new AnimationEvent(child,
1514                    AnimationEvent.ANIMATION_TYPE_CHANGE_POSITION));
1515        }
1516        mChildrenChangingPositions.clear();
1517    }
1518
1519    private void generateChildAdditionEvents() {
1520        for (View child : mChildrenToAddAnimated) {
1521            mAnimationEvents.add(new AnimationEvent(child,
1522                    AnimationEvent.ANIMATION_TYPE_ADD));
1523        }
1524        mChildrenToAddAnimated.clear();
1525    }
1526
1527    private void generateTopPaddingEvent() {
1528        if (mTopPaddingNeedsAnimation) {
1529            mAnimationEvents.add(
1530                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_TOP_PADDING_CHANGED));
1531        }
1532        mTopPaddingNeedsAnimation = false;
1533    }
1534
1535    private void generateActivateEvent() {
1536        if (mActivateNeedsAnimation) {
1537            mAnimationEvents.add(
1538                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_ACTIVATED_CHILD));
1539        }
1540        mActivateNeedsAnimation = false;
1541    }
1542
1543    private void generateDimmedEvent() {
1544        if (mDimmedNeedsAnimation) {
1545            mAnimationEvents.add(
1546                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_DIMMED));
1547        }
1548        mDimmedNeedsAnimation = false;
1549    }
1550
1551    private void generateDarkEvent() {
1552        if (mDarkNeedsAnimation) {
1553            mAnimationEvents.add(
1554                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_DARK));
1555        }
1556        mDarkNeedsAnimation = false;
1557    }
1558
1559    private boolean onInterceptTouchEventScroll(MotionEvent ev) {
1560        if (!isScrollingEnabled()) {
1561            return false;
1562        }
1563        /*
1564         * This method JUST determines whether we want to intercept the motion.
1565         * If we return true, onMotionEvent will be called and we do the actual
1566         * scrolling there.
1567         */
1568
1569        /*
1570        * Shortcut the most recurring case: the user is in the dragging
1571        * state and he is moving his finger.  We want to intercept this
1572        * motion.
1573        */
1574        final int action = ev.getAction();
1575        if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
1576            return true;
1577        }
1578
1579        switch (action & MotionEvent.ACTION_MASK) {
1580            case MotionEvent.ACTION_MOVE: {
1581                /*
1582                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1583                 * whether the user has moved far enough from his original down touch.
1584                 */
1585
1586                /*
1587                * Locally do absolute value. mLastMotionY is set to the y value
1588                * of the down event.
1589                */
1590                final int activePointerId = mActivePointerId;
1591                if (activePointerId == INVALID_POINTER) {
1592                    // If we don't have a valid id, the touch down wasn't on content.
1593                    break;
1594                }
1595
1596                final int pointerIndex = ev.findPointerIndex(activePointerId);
1597                if (pointerIndex == -1) {
1598                    Log.e(TAG, "Invalid pointerId=" + activePointerId
1599                            + " in onInterceptTouchEvent");
1600                    break;
1601                }
1602
1603                final int y = (int) ev.getY(pointerIndex);
1604                final int x = (int) ev.getX(pointerIndex);
1605                final int yDiff = Math.abs(y - mLastMotionY);
1606                final int xDiff = Math.abs(x - mDownX);
1607                if (yDiff > mTouchSlop && yDiff > xDiff) {
1608                    setIsBeingDragged(true);
1609                    mLastMotionY = y;
1610                    mDownX = x;
1611                    initVelocityTrackerIfNotExists();
1612                    mVelocityTracker.addMovement(ev);
1613                }
1614                break;
1615            }
1616
1617            case MotionEvent.ACTION_DOWN: {
1618                final int y = (int) ev.getY();
1619                if (getChildAtPosition(ev.getX(), y) == null) {
1620                    setIsBeingDragged(false);
1621                    recycleVelocityTracker();
1622                    break;
1623                }
1624
1625                /*
1626                 * Remember location of down touch.
1627                 * ACTION_DOWN always refers to pointer index 0.
1628                 */
1629                mLastMotionY = y;
1630                mDownX = (int) ev.getX();
1631                mActivePointerId = ev.getPointerId(0);
1632                mScrolledToTopOnFirstDown = isScrolledToTop();
1633
1634                initOrResetVelocityTracker();
1635                mVelocityTracker.addMovement(ev);
1636                /*
1637                * If being flinged and user touches the screen, initiate drag;
1638                * otherwise don't.  mScroller.isFinished should be false when
1639                * being flinged.
1640                */
1641                boolean isBeingDragged = !mScroller.isFinished();
1642                setIsBeingDragged(isBeingDragged);
1643                break;
1644            }
1645
1646            case MotionEvent.ACTION_CANCEL:
1647            case MotionEvent.ACTION_UP:
1648                /* Release the drag */
1649                setIsBeingDragged(false);
1650                mActivePointerId = INVALID_POINTER;
1651                recycleVelocityTracker();
1652                if (mScroller.springBack(mScrollX, mOwnScrollY, 0, 0, 0, getScrollRange())) {
1653                    postInvalidateOnAnimation();
1654                }
1655                break;
1656            case MotionEvent.ACTION_POINTER_UP:
1657                onSecondaryPointerUp(ev);
1658                break;
1659        }
1660
1661        /*
1662        * The only time we want to intercept motion events is if we are in the
1663        * drag mode.
1664        */
1665        return mIsBeingDragged;
1666    }
1667
1668    /**
1669     * @return Whether the specified motion event is actually happening over the content.
1670     */
1671    private boolean isInContentBounds(MotionEvent event) {
1672        return event.getY() < getHeight() - getEmptyBottomMargin();
1673    }
1674
1675    private void setIsBeingDragged(boolean isDragged) {
1676        mIsBeingDragged = isDragged;
1677        if (isDragged) {
1678            requestDisallowInterceptTouchEvent(true);
1679            removeLongPressCallback();
1680        }
1681    }
1682
1683    @Override
1684    public void onWindowFocusChanged(boolean hasWindowFocus) {
1685        super.onWindowFocusChanged(hasWindowFocus);
1686        if (!hasWindowFocus) {
1687            removeLongPressCallback();
1688        }
1689    }
1690
1691    public void removeLongPressCallback() {
1692        mSwipeHelper.removeLongPressCallback();
1693    }
1694
1695    @Override
1696    public boolean isScrolledToTop() {
1697        return mOwnScrollY == 0;
1698    }
1699
1700    @Override
1701    public boolean isScrolledToBottom() {
1702        return mOwnScrollY >= getScrollRange();
1703    }
1704
1705    @Override
1706    public View getHostView() {
1707        return this;
1708    }
1709
1710    public int getEmptyBottomMargin() {
1711        int emptyMargin = mMaxLayoutHeight - mContentHeight;
1712        if (needsHeightAdaption()) {
1713            emptyMargin = emptyMargin - mBottomStackSlowDownHeight - mBottomStackPeekSize;
1714        } else {
1715            emptyMargin = emptyMargin - mBottomStackPeekSize;
1716        }
1717        return Math.max(emptyMargin, 0);
1718    }
1719
1720    public void onExpansionStarted() {
1721        mIsExpansionChanging = true;
1722        mStackScrollAlgorithm.onExpansionStarted(mCurrentStackScrollState);
1723    }
1724
1725    public void onExpansionStopped() {
1726        mIsExpansionChanging = false;
1727        mStackScrollAlgorithm.onExpansionStopped();
1728    }
1729
1730    private void setIsExpanded(boolean isExpanded) {
1731        mIsExpanded = isExpanded;
1732        mStackScrollAlgorithm.setIsExpanded(isExpanded);
1733        if (!isExpanded) {
1734            mOwnScrollY = 0;
1735        }
1736    }
1737
1738    @Override
1739    public void onHeightChanged(ExpandableView view) {
1740        updateContentHeight();
1741        updateScrollPositionIfNecessary();
1742        notifyHeightChangeListener(view);
1743        requestChildrenUpdate();
1744    }
1745
1746    public void setOnHeightChangedListener(
1747            ExpandableView.OnHeightChangedListener mOnHeightChangedListener) {
1748        this.mOnHeightChangedListener = mOnHeightChangedListener;
1749    }
1750
1751    public void onChildAnimationFinished() {
1752        requestChildrenUpdate();
1753    }
1754
1755    /**
1756     * See {@link AmbientState#setDimmed}.
1757     */
1758    public void setDimmed(boolean dimmed, boolean animate) {
1759        mStackScrollAlgorithm.setDimmed(dimmed);
1760        mAmbientState.setDimmed(dimmed);
1761        updatePadding(dimmed);
1762        if (animate && mAnimationsEnabled) {
1763            mDimmedNeedsAnimation = true;
1764            mNeedsAnimation =  true;
1765        }
1766        requestChildrenUpdate();
1767    }
1768
1769    /**
1770     * See {@link AmbientState#setActivatedChild}.
1771     */
1772    public void setActivatedChild(ActivatableNotificationView activatedChild) {
1773        mAmbientState.setActivatedChild(activatedChild);
1774        if (mAnimationsEnabled) {
1775            mActivateNeedsAnimation = true;
1776            mNeedsAnimation =  true;
1777        }
1778        requestChildrenUpdate();
1779    }
1780
1781    public ActivatableNotificationView getActivatedChild() {
1782        return mAmbientState.getActivatedChild();
1783    }
1784
1785    private void applyCurrentState() {
1786        mCurrentStackScrollState.apply();
1787        if (mListener != null) {
1788            mListener.onChildLocationsChanged(this);
1789        }
1790    }
1791
1792    public void setSpeedBumpView(SpeedBumpView speedBumpView) {
1793        mSpeedBumpView = speedBumpView;
1794        addView(speedBumpView);
1795    }
1796
1797    private void updateSpeedBump(boolean visible) {
1798        boolean notGoneBefore = mSpeedBumpView.getVisibility() != GONE;
1799        if (visible != notGoneBefore) {
1800            int newVisibility = visible ? VISIBLE : GONE;
1801            mSpeedBumpView.setVisibility(newVisibility);
1802            if (visible) {
1803                // Make invisible to ensure that the appear animation is played.
1804                mSpeedBumpView.setInvisible();
1805                if (!mIsExpansionChanging) {
1806                    generateAddAnimation(mSpeedBumpView);
1807                }
1808            } else {
1809                mSpeedBumpView.performVisibilityAnimation(false);
1810                generateRemoveAnimation(mSpeedBumpView);
1811            }
1812        }
1813    }
1814
1815    public void goToFullShade() {
1816        updateSpeedBump(true);
1817    }
1818
1819    public void cancelExpandHelper() {
1820        mExpandHelper.cancel();
1821    }
1822
1823    public void setIntrinsicPadding(int intrinsicPadding) {
1824        mIntrinsicPadding = intrinsicPadding;
1825    }
1826
1827    /**
1828     * @return the y position of the first notification
1829     */
1830    public float getNotificationsTopY() {
1831        return mTopPadding + getTranslationY();
1832    }
1833
1834    public void setTouchEnabled(boolean touchEnabled) {
1835        mTouchEnabled = touchEnabled;
1836    }
1837
1838    @Override
1839    public boolean dispatchTouchEvent(MotionEvent ev) {
1840        if (!mTouchEnabled) {
1841            return false;
1842        }
1843        return super.dispatchTouchEvent(ev);
1844    }
1845
1846    @Override
1847    public boolean shouldDelayChildPressedState() {
1848        return true;
1849    }
1850
1851    public void setScrimAlpha(float progress) {
1852        mAmbientState.setScrimAmount(progress);
1853        requestChildrenUpdate();
1854    }
1855
1856    /**
1857     * See {@link AmbientState#setDark}.
1858     */
1859    public void setDark(boolean dark, boolean animate) {
1860        mAmbientState.setDark(dark);
1861        if (animate && mAnimationsEnabled) {
1862            mDarkNeedsAnimation = true;
1863            mNeedsAnimation =  true;
1864        }
1865        requestChildrenUpdate();
1866    }
1867
1868    /**
1869     * A listener that is notified when some child locations might have changed.
1870     */
1871    public interface OnChildLocationsChangedListener {
1872        public void onChildLocationsChanged(NotificationStackScrollLayout stackScrollLayout);
1873    }
1874
1875    /**
1876     * A listener that gets notified when the overscroll at the top has changed.
1877     */
1878    public interface OnOverscrollTopChangedListener {
1879        public void onOverscrollTopChanged(float amount);
1880
1881        /**
1882         * Notify a listener that the scroller wants to escape from the scrolling motion and
1883         * start a fling animation to the expanded or collapsed overscroll view (e.g expand the QS)
1884         *
1885         * @param velocity The velocity that the Scroller had when over flinging
1886         * @param open Should the fling open or close the overscroll view.
1887         */
1888        public void flingTopOverscroll(float velocity, boolean open);
1889    }
1890
1891    static class AnimationEvent {
1892
1893        static AnimationFilter[] FILTERS = new AnimationFilter[] {
1894
1895                // ANIMATION_TYPE_ADD
1896                new AnimationFilter()
1897                        .animateAlpha()
1898                        .animateHeight()
1899                        .animateTopInset()
1900                        .animateY()
1901                        .animateZ()
1902                        .hasDelays(),
1903
1904                // ANIMATION_TYPE_REMOVE
1905                new AnimationFilter()
1906                        .animateAlpha()
1907                        .animateHeight()
1908                        .animateTopInset()
1909                        .animateY()
1910                        .animateZ()
1911                        .hasDelays(),
1912
1913                // ANIMATION_TYPE_REMOVE_SWIPED_OUT
1914                new AnimationFilter()
1915                        .animateAlpha()
1916                        .animateHeight()
1917                        .animateTopInset()
1918                        .animateY()
1919                        .animateZ()
1920                        .hasDelays(),
1921
1922                // ANIMATION_TYPE_TOP_PADDING_CHANGED
1923                new AnimationFilter()
1924                        .animateAlpha()
1925                        .animateHeight()
1926                        .animateTopInset()
1927                        .animateY()
1928                        .animateDimmed()
1929                        .animateScale()
1930                        .animateZ(),
1931
1932                // ANIMATION_TYPE_START_DRAG
1933                new AnimationFilter()
1934                        .animateAlpha(),
1935
1936                // ANIMATION_TYPE_SNAP_BACK
1937                new AnimationFilter()
1938                        .animateAlpha(),
1939
1940                // ANIMATION_TYPE_ACTIVATED_CHILD
1941                new AnimationFilter()
1942                        .animateScale()
1943                        .animateAlpha(),
1944
1945                // ANIMATION_TYPE_DIMMED
1946                new AnimationFilter()
1947                        .animateY()
1948                        .animateScale()
1949                        .animateDimmed(),
1950
1951                // ANIMATION_TYPE_CHANGE_POSITION
1952                new AnimationFilter()
1953                        .animateAlpha()
1954                        .animateHeight()
1955                        .animateTopInset()
1956                        .animateY()
1957                        .animateZ(),
1958
1959                // ANIMATION_TYPE_DARK
1960                new AnimationFilter()
1961                        .animateDark(),
1962        };
1963
1964        static int[] LENGTHS = new int[] {
1965
1966                // ANIMATION_TYPE_ADD
1967                StackStateAnimator.ANIMATION_DURATION_APPEAR_DISAPPEAR,
1968
1969                // ANIMATION_TYPE_REMOVE
1970                StackStateAnimator.ANIMATION_DURATION_APPEAR_DISAPPEAR,
1971
1972                // ANIMATION_TYPE_REMOVE_SWIPED_OUT
1973                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1974
1975                // ANIMATION_TYPE_TOP_PADDING_CHANGED
1976                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1977
1978                // ANIMATION_TYPE_START_DRAG
1979                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1980
1981                // ANIMATION_TYPE_SNAP_BACK
1982                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1983
1984                // ANIMATION_TYPE_ACTIVATED_CHILD
1985                StackStateAnimator.ANIMATION_DURATION_DIMMED_ACTIVATED,
1986
1987                // ANIMATION_TYPE_DIMMED
1988                StackStateAnimator.ANIMATION_DURATION_DIMMED_ACTIVATED,
1989
1990                // ANIMATION_TYPE_CHANGE_POSITION
1991                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1992
1993                // ANIMATION_TYPE_DARK
1994                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1995        };
1996
1997        static final int ANIMATION_TYPE_ADD = 0;
1998        static final int ANIMATION_TYPE_REMOVE = 1;
1999        static final int ANIMATION_TYPE_REMOVE_SWIPED_OUT = 2;
2000        static final int ANIMATION_TYPE_TOP_PADDING_CHANGED = 3;
2001        static final int ANIMATION_TYPE_START_DRAG = 4;
2002        static final int ANIMATION_TYPE_SNAP_BACK = 5;
2003        static final int ANIMATION_TYPE_ACTIVATED_CHILD = 6;
2004        static final int ANIMATION_TYPE_DIMMED = 7;
2005        static final int ANIMATION_TYPE_CHANGE_POSITION = 8;
2006        static final int ANIMATION_TYPE_DARK = 9;
2007
2008        final long eventStartTime;
2009        final View changingView;
2010        final int animationType;
2011        final AnimationFilter filter;
2012        final long length;
2013        View viewAfterChangingView;
2014
2015        AnimationEvent(View view, int type) {
2016            eventStartTime = AnimationUtils.currentAnimationTimeMillis();
2017            changingView = view;
2018            animationType = type;
2019            filter = FILTERS[type];
2020            length = LENGTHS[type];
2021        }
2022
2023        /**
2024         * Combines the length of several animation events into a single value.
2025         *
2026         * @param events The events of the lengths to combine.
2027         * @return The combined length. This is just the maximum of all length.
2028         */
2029        static long combineLength(ArrayList<AnimationEvent> events) {
2030            long length = 0;
2031            int size = events.size();
2032            for (int i = 0; i < size; i++) {
2033                length = Math.max(length, events.get(i).length);
2034            }
2035            return length;
2036        }
2037    }
2038
2039}
2040