PanelView.java revision 98139559af15d85b8a34c02fe9bc97fba901a4b5
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.systemui.statusbar.phone;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.ObjectAnimator;
22import android.animation.ValueAnimator;
23import android.content.Context;
24import android.content.res.Configuration;
25import android.content.res.Resources;
26import android.util.AttributeSet;
27import android.util.Log;
28import android.view.MotionEvent;
29import android.view.ViewConfiguration;
30import android.view.ViewTreeObserver;
31import android.view.animation.AnimationUtils;
32import android.view.animation.Interpolator;
33import android.widget.FrameLayout;
34
35import com.android.systemui.R;
36import com.android.systemui.statusbar.FlingAnimationUtils;
37import com.android.systemui.statusbar.StatusBarState;
38
39import java.io.FileDescriptor;
40import java.io.PrintWriter;
41
42public abstract class PanelView extends FrameLayout {
43    public static final boolean DEBUG = PanelBar.DEBUG;
44    public static final String TAG = PanelView.class.getSimpleName();
45
46    private final void logf(String fmt, Object... args) {
47        Log.v(TAG, (mViewName != null ? (mViewName + ": ") : "") + String.format(fmt, args));
48    }
49
50    protected PhoneStatusBar mStatusBar;
51    private float mPeekHeight;
52    private float mHintDistance;
53    private int mEdgeTapAreaWidth;
54    private float mInitialOffsetOnTouch;
55    private float mExpandedFraction = 0;
56    protected float mExpandedHeight = 0;
57    private boolean mPanelClosedOnDown;
58    private boolean mHasLayoutedSinceDown;
59    private float mUpdateFlingVelocity;
60    private boolean mUpdateFlingOnLayout;
61    private boolean mPeekTouching;
62    private boolean mJustPeeked;
63    private boolean mClosing;
64    protected boolean mTracking;
65    private boolean mTouchSlopExceeded;
66    private int mTrackingPointer;
67    protected int mTouchSlop;
68    protected boolean mHintAnimationRunning;
69    private boolean mOverExpandedBeforeFling;
70    private float mOriginalIndicationY;
71    private boolean mTouchAboveFalsingThreshold;
72    private int mUnlockFalsingThreshold;
73
74    private ValueAnimator mHeightAnimator;
75    private ObjectAnimator mPeekAnimator;
76    private VelocityTrackerInterface mVelocityTracker;
77    private FlingAnimationUtils mFlingAnimationUtils;
78
79    /**
80     * Whether an instant expand request is currently pending and we are just waiting for layout.
81     */
82    private boolean mInstantExpanding;
83
84    PanelBar mBar;
85
86    private String mViewName;
87    private float mInitialTouchY;
88    private float mInitialTouchX;
89
90    private Interpolator mLinearOutSlowInInterpolator;
91    private Interpolator mFastOutSlowInInterpolator;
92    private Interpolator mBounceInterpolator;
93    protected KeyguardBottomAreaView mKeyguardBottomArea;
94
95    private boolean mPeekPending;
96    private boolean mCollapseAfterPeek;
97    private boolean mExpanding;
98    private boolean mGestureWaitForTouchSlop;
99    private Runnable mPeekRunnable = new Runnable() {
100        @Override
101        public void run() {
102            mPeekPending = false;
103            runPeekAnimation();
104        }
105    };
106
107    protected void onExpandingFinished() {
108        mClosing = false;
109        mBar.onExpandingFinished();
110    }
111
112    protected void onExpandingStarted() {
113    }
114
115    private void notifyExpandingStarted() {
116        if (!mExpanding) {
117            mExpanding = true;
118            onExpandingStarted();
119        }
120    }
121
122    private void notifyExpandingFinished() {
123        if (mExpanding) {
124            mExpanding = false;
125            onExpandingFinished();
126        }
127    }
128
129    private void schedulePeek() {
130        mPeekPending = true;
131        long timeout = ViewConfiguration.getTapTimeout();
132        postOnAnimationDelayed(mPeekRunnable, timeout);
133        notifyBarPanelExpansionChanged();
134    }
135
136    private void runPeekAnimation() {
137        mPeekHeight = getPeekHeight();
138        if (DEBUG) logf("peek to height=%.1f", mPeekHeight);
139        if (mHeightAnimator != null) {
140            return;
141        }
142        mPeekAnimator = ObjectAnimator.ofFloat(this, "expandedHeight", mPeekHeight)
143                .setDuration(250);
144        mPeekAnimator.setInterpolator(mLinearOutSlowInInterpolator);
145        mPeekAnimator.addListener(new AnimatorListenerAdapter() {
146            private boolean mCancelled;
147
148            @Override
149            public void onAnimationCancel(Animator animation) {
150                mCancelled = true;
151            }
152
153            @Override
154            public void onAnimationEnd(Animator animation) {
155                mPeekAnimator = null;
156                if (mCollapseAfterPeek && !mCancelled) {
157                    postOnAnimation(new Runnable() {
158                        @Override
159                        public void run() {
160                            collapse(false /* delayed */);
161                        }
162                    });
163                }
164                mCollapseAfterPeek = false;
165            }
166        });
167        notifyExpandingStarted();
168        mPeekAnimator.start();
169        mJustPeeked = true;
170    }
171
172    public PanelView(Context context, AttributeSet attrs) {
173        super(context, attrs);
174        mFlingAnimationUtils = new FlingAnimationUtils(context, 0.6f);
175        mFastOutSlowInInterpolator =
176                AnimationUtils.loadInterpolator(context, android.R.interpolator.fast_out_slow_in);
177        mLinearOutSlowInInterpolator =
178                AnimationUtils.loadInterpolator(context, android.R.interpolator.linear_out_slow_in);
179        mBounceInterpolator = new BounceInterpolator();
180    }
181
182    protected void loadDimens() {
183        final Resources res = getContext().getResources();
184        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
185        mTouchSlop = configuration.getScaledTouchSlop();
186        mHintDistance = res.getDimension(R.dimen.hint_move_distance);
187        mEdgeTapAreaWidth = res.getDimensionPixelSize(R.dimen.edge_tap_area_width);
188        mUnlockFalsingThreshold = res.getDimensionPixelSize(R.dimen.unlock_falsing_threshold);
189    }
190
191    private void trackMovement(MotionEvent event) {
192        // Add movement to velocity tracker using raw screen X and Y coordinates instead
193        // of window coordinates because the window frame may be moving at the same time.
194        float deltaX = event.getRawX() - event.getX();
195        float deltaY = event.getRawY() - event.getY();
196        event.offsetLocation(deltaX, deltaY);
197        if (mVelocityTracker != null) mVelocityTracker.addMovement(event);
198        event.offsetLocation(-deltaX, -deltaY);
199    }
200
201    @Override
202    public boolean onTouchEvent(MotionEvent event) {
203        if (mInstantExpanding) {
204            return false;
205        }
206
207        /*
208         * We capture touch events here and update the expand height here in case according to
209         * the users fingers. This also handles multi-touch.
210         *
211         * If the user just clicks shortly, we give him a quick peek of the shade.
212         *
213         * Flinging is also enabled in order to open or close the shade.
214         */
215
216        int pointerIndex = event.findPointerIndex(mTrackingPointer);
217        if (pointerIndex < 0) {
218            pointerIndex = 0;
219            mTrackingPointer = event.getPointerId(pointerIndex);
220        }
221        final float y = event.getY(pointerIndex);
222        final float x = event.getX(pointerIndex);
223
224        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
225            mGestureWaitForTouchSlop = mExpandedHeight == 0f;
226        }
227        boolean waitForTouchSlop = hasConflictingGestures() || mGestureWaitForTouchSlop;
228
229        switch (event.getActionMasked()) {
230            case MotionEvent.ACTION_DOWN:
231                mInitialTouchY = y;
232                mInitialTouchX = x;
233                mInitialOffsetOnTouch = mExpandedHeight;
234                mTouchSlopExceeded = false;
235                mJustPeeked = false;
236                mPanelClosedOnDown = mExpandedHeight == 0.0f;
237                mHasLayoutedSinceDown = false;
238                mUpdateFlingOnLayout = false;
239                mPeekTouching = mPanelClosedOnDown;
240                mTouchAboveFalsingThreshold = false;
241                if (mVelocityTracker == null) {
242                    initVelocityTracker();
243                }
244                trackMovement(event);
245                if (!waitForTouchSlop || (mHeightAnimator != null && !mHintAnimationRunning) ||
246                        mPeekPending || mPeekAnimator != null) {
247                    if (mHeightAnimator != null) {
248                        mHeightAnimator.cancel(); // end any outstanding animations
249                    }
250                    cancelPeek();
251                    mTouchSlopExceeded = (mHeightAnimator != null && !mHintAnimationRunning)
252                            || mPeekPending || mPeekAnimator != null;
253                    onTrackingStarted();
254                }
255                if (mExpandedHeight == 0) {
256                    schedulePeek();
257                }
258                break;
259
260            case MotionEvent.ACTION_POINTER_UP:
261                final int upPointer = event.getPointerId(event.getActionIndex());
262                if (mTrackingPointer == upPointer) {
263                    // gesture is ongoing, find a new pointer to track
264                    final int newIndex = event.getPointerId(0) != upPointer ? 0 : 1;
265                    final float newY = event.getY(newIndex);
266                    final float newX = event.getX(newIndex);
267                    mTrackingPointer = event.getPointerId(newIndex);
268                    mInitialOffsetOnTouch = mExpandedHeight;
269                    mInitialTouchY = newY;
270                    mInitialTouchX = newX;
271                }
272                break;
273
274            case MotionEvent.ACTION_MOVE:
275                float h = y - mInitialTouchY;
276
277                // If the panel was collapsed when touching, we only need to check for the
278                // y-component of the gesture, as we have no conflicting horizontal gesture.
279                if (Math.abs(h) > mTouchSlop
280                        && (Math.abs(h) > Math.abs(x - mInitialTouchX)
281                                || mInitialOffsetOnTouch == 0f)) {
282                    mTouchSlopExceeded = true;
283                    if (waitForTouchSlop && !mTracking) {
284                        if (!mJustPeeked) {
285                            mInitialOffsetOnTouch = mExpandedHeight;
286                            mInitialTouchX = x;
287                            mInitialTouchY = y;
288                            h = 0;
289                        }
290                        if (mHeightAnimator != null) {
291                            mHeightAnimator.cancel(); // end any outstanding animations
292                        }
293                        removeCallbacks(mPeekRunnable);
294                        mPeekPending = false;
295                        onTrackingStarted();
296                    }
297                }
298                final float newHeight = Math.max(0, h + mInitialOffsetOnTouch);
299                if (newHeight > mPeekHeight) {
300                    if (mPeekAnimator != null) {
301                        mPeekAnimator.cancel();
302                    }
303                    mJustPeeked = false;
304                }
305                if (-h >= mUnlockFalsingThreshold) {
306                    mTouchAboveFalsingThreshold = true;
307                }
308                if (!mJustPeeked && (!waitForTouchSlop || mTracking) && !isTrackingBlocked()) {
309                    setExpandedHeightInternal(newHeight);
310                }
311
312                trackMovement(event);
313                break;
314
315            case MotionEvent.ACTION_UP:
316            case MotionEvent.ACTION_CANCEL:
317                mTrackingPointer = -1;
318                trackMovement(event);
319                if ((mTracking && mTouchSlopExceeded)
320                        || Math.abs(x - mInitialTouchX) > mTouchSlop
321                        || Math.abs(y - mInitialTouchY) > mTouchSlop
322                        || event.getActionMasked() == MotionEvent.ACTION_CANCEL) {
323                    float vel = 0f;
324                    float vectorVel = 0f;
325                    if (mVelocityTracker != null) {
326                        mVelocityTracker.computeCurrentVelocity(1000);
327                        vel = mVelocityTracker.getYVelocity();
328                        vectorVel = (float) Math.hypot(
329                                mVelocityTracker.getXVelocity(), mVelocityTracker.getYVelocity());
330                    }
331                    boolean expand = flingExpands(vel, vectorVel);
332                    onTrackingStopped(expand);
333                    fling(vel, expand);
334                    mUpdateFlingOnLayout = expand && mPanelClosedOnDown && !mHasLayoutedSinceDown;
335                    if (mUpdateFlingOnLayout) {
336                        mUpdateFlingVelocity = vel;
337                    }
338                } else {
339                    boolean expands = onEmptySpaceClick(mInitialTouchX);
340                    onTrackingStopped(expands);
341                }
342
343                if (mVelocityTracker != null) {
344                    mVelocityTracker.recycle();
345                    mVelocityTracker = null;
346                }
347                mPeekTouching = false;
348                break;
349        }
350        return !waitForTouchSlop || mTracking;
351    }
352
353    protected abstract boolean hasConflictingGestures();
354
355    protected void onTrackingStopped(boolean expand) {
356        mTracking = false;
357        mBar.onTrackingStopped(PanelView.this, expand);
358    }
359
360    protected void onTrackingStarted() {
361        mTracking = true;
362        mCollapseAfterPeek = false;
363        mBar.onTrackingStarted(PanelView.this);
364        notifyExpandingStarted();
365    }
366
367    @Override
368    public boolean onInterceptTouchEvent(MotionEvent event) {
369        if (mInstantExpanding) {
370            return false;
371        }
372
373        /*
374         * If the user drags anywhere inside the panel we intercept it if he moves his finger
375         * upwards. This allows closing the shade from anywhere inside the panel.
376         *
377         * We only do this if the current content is scrolled to the bottom,
378         * i.e isScrolledToBottom() is true and therefore there is no conflicting scrolling gesture
379         * possible.
380         */
381        int pointerIndex = event.findPointerIndex(mTrackingPointer);
382        if (pointerIndex < 0) {
383            pointerIndex = 0;
384            mTrackingPointer = event.getPointerId(pointerIndex);
385        }
386        final float x = event.getX(pointerIndex);
387        final float y = event.getY(pointerIndex);
388        boolean scrolledToBottom = isScrolledToBottom();
389
390        switch (event.getActionMasked()) {
391            case MotionEvent.ACTION_DOWN:
392                mStatusBar.userActivity();
393                if (mHeightAnimator != null && !mHintAnimationRunning ||
394                        mPeekPending || mPeekAnimator != null) {
395                    if (mHeightAnimator != null) {
396                        mHeightAnimator.cancel(); // end any outstanding animations
397                    }
398                    cancelPeek();
399                    mTouchSlopExceeded = true;
400                    return true;
401                }
402                mInitialTouchY = y;
403                mInitialTouchX = x;
404                mTouchSlopExceeded = false;
405                mJustPeeked = false;
406                mPanelClosedOnDown = mExpandedHeight == 0.0f;
407                mHasLayoutedSinceDown = false;
408                mUpdateFlingOnLayout = false;
409                mTouchAboveFalsingThreshold = false;
410                initVelocityTracker();
411                trackMovement(event);
412                break;
413            case MotionEvent.ACTION_POINTER_UP:
414                final int upPointer = event.getPointerId(event.getActionIndex());
415                if (mTrackingPointer == upPointer) {
416                    // gesture is ongoing, find a new pointer to track
417                    final int newIndex = event.getPointerId(0) != upPointer ? 0 : 1;
418                    mTrackingPointer = event.getPointerId(newIndex);
419                    mInitialTouchX = event.getX(newIndex);
420                    mInitialTouchY = event.getY(newIndex);
421                }
422                break;
423
424            case MotionEvent.ACTION_MOVE:
425                final float h = y - mInitialTouchY;
426                trackMovement(event);
427                if (scrolledToBottom) {
428                    if (h < -mTouchSlop && h < -Math.abs(x - mInitialTouchX)) {
429                        if (mHeightAnimator != null) {
430                            mHeightAnimator.cancel();
431                        }
432                        mInitialOffsetOnTouch = mExpandedHeight;
433                        mInitialTouchY = y;
434                        mInitialTouchX = x;
435                        mTracking = true;
436                        mTouchSlopExceeded = true;
437                        onTrackingStarted();
438                        return true;
439                    }
440                }
441                break;
442            case MotionEvent.ACTION_CANCEL:
443            case MotionEvent.ACTION_UP:
444                break;
445        }
446        return false;
447    }
448
449    private void initVelocityTracker() {
450        if (mVelocityTracker != null) {
451            mVelocityTracker.recycle();
452        }
453        mVelocityTracker = VelocityTrackerFactory.obtain(getContext());
454    }
455
456    protected boolean isScrolledToBottom() {
457        return true;
458    }
459
460    protected float getContentHeight() {
461        return mExpandedHeight;
462    }
463
464    @Override
465    protected void onFinishInflate() {
466        super.onFinishInflate();
467        loadDimens();
468    }
469
470    @Override
471    protected void onConfigurationChanged(Configuration newConfig) {
472        super.onConfigurationChanged(newConfig);
473        loadDimens();
474    }
475
476    /**
477     * @param vel the current vertical velocity of the motion
478     * @param vectorVel the length of the vectorial velocity
479     * @return whether a fling should expands the panel; contracts otherwise
480     */
481    protected boolean flingExpands(float vel, float vectorVel) {
482        if (isBelowFalsingThreshold()) {
483            return true;
484        }
485        if (Math.abs(vectorVel) < mFlingAnimationUtils.getMinVelocityPxPerSecond()) {
486            return getExpandedFraction() > 0.5f;
487        } else {
488            return vel > 0;
489        }
490    }
491
492    private boolean isBelowFalsingThreshold() {
493        return !mTouchAboveFalsingThreshold && mStatusBar.isFalsingThresholdNeeded();
494    }
495
496    protected void fling(float vel, boolean expand) {
497        cancelPeek();
498        float target = expand ? getMaxPanelHeight() : 0.0f;
499
500        // Hack to make the expand transition look nice when clear all button is visible - we make
501        // the animation only to the last notification, and then jump to the maximum panel height so
502        // clear all just fades in and the decelerating motion is towards the last notification.
503        final boolean clearAllExpandHack = expand && fullyExpandedClearAllVisible()
504                && mExpandedHeight < getMaxPanelHeight() - getClearAllHeight()
505                && !isClearAllVisible();
506        if (clearAllExpandHack) {
507            target = getMaxPanelHeight() - getClearAllHeight();
508        }
509        if (target == mExpandedHeight || getOverExpansionAmount() > 0f && expand) {
510            notifyExpandingFinished();
511            return;
512        }
513        mOverExpandedBeforeFling = getOverExpansionAmount() > 0f;
514        ValueAnimator animator = createHeightAnimator(target);
515        if (expand) {
516            boolean belowFalsingThreshold = isBelowFalsingThreshold();
517            if (belowFalsingThreshold) {
518                vel = 0;
519            }
520            mFlingAnimationUtils.apply(animator, mExpandedHeight, target, vel, getHeight());
521            if (belowFalsingThreshold) {
522                animator.setDuration(350);
523            }
524        } else {
525            mFlingAnimationUtils.applyDismissing(animator, mExpandedHeight, target, vel,
526                    getHeight());
527
528            // Make it shorter if we run a canned animation
529            if (vel == 0) {
530                animator.setDuration((long)
531                        (animator.getDuration() * getCannedFlingDurationFactor()));
532            }
533        }
534        animator.addListener(new AnimatorListenerAdapter() {
535            private boolean mCancelled;
536
537            @Override
538            public void onAnimationCancel(Animator animation) {
539                mCancelled = true;
540            }
541
542            @Override
543            public void onAnimationEnd(Animator animation) {
544                if (clearAllExpandHack && !mCancelled) {
545                    setExpandedHeightInternal(getMaxPanelHeight());
546                }
547                mHeightAnimator = null;
548                if (!mCancelled) {
549                    notifyExpandingFinished();
550                }
551            }
552        });
553        mHeightAnimator = animator;
554        animator.start();
555    }
556
557    @Override
558    protected void onAttachedToWindow() {
559        super.onAttachedToWindow();
560        mViewName = getResources().getResourceName(getId());
561    }
562
563    public String getName() {
564        return mViewName;
565    }
566
567    public void setExpandedHeight(float height) {
568        if (DEBUG) logf("setExpandedHeight(%.1f)", height);
569        setExpandedHeightInternal(height + getOverExpansionPixels());
570    }
571
572    @Override
573    protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
574        super.onLayout(changed, left, top, right, bottom);
575        requestPanelHeightUpdate();
576        mHasLayoutedSinceDown = true;
577        if (mUpdateFlingOnLayout) {
578            abortAnimations();
579            fling(mUpdateFlingVelocity, true);
580            mUpdateFlingOnLayout = false;
581        }
582    }
583
584    protected void requestPanelHeightUpdate() {
585        float currentMaxPanelHeight = getMaxPanelHeight();
586
587        // If the user isn't actively poking us, let's update the height
588        if ((!mTracking || isTrackingBlocked())
589                && mHeightAnimator == null
590                && mExpandedHeight > 0
591                && currentMaxPanelHeight != mExpandedHeight
592                && !mPeekPending
593                && mPeekAnimator == null
594                && !mPeekTouching) {
595            setExpandedHeight(currentMaxPanelHeight);
596        }
597    }
598
599    public void setExpandedHeightInternal(float h) {
600        float fhWithoutOverExpansion = getMaxPanelHeight() - getOverExpansionAmount();
601        if (mHeightAnimator == null) {
602            float overExpansionPixels = Math.max(0, h - fhWithoutOverExpansion);
603            if (getOverExpansionPixels() != overExpansionPixels && mTracking) {
604                setOverExpansion(overExpansionPixels, true /* isPixels */);
605            }
606            mExpandedHeight = Math.min(h, fhWithoutOverExpansion) + getOverExpansionAmount();
607        } else {
608            mExpandedHeight = h;
609            if (mOverExpandedBeforeFling) {
610                setOverExpansion(Math.max(0, h - fhWithoutOverExpansion), false /* isPixels */);
611            }
612        }
613
614        mExpandedHeight = Math.max(0, mExpandedHeight);
615        onHeightUpdated(mExpandedHeight);
616        mExpandedFraction = Math.min(1f, fhWithoutOverExpansion == 0
617                ? 0
618                : mExpandedHeight / fhWithoutOverExpansion);
619        notifyBarPanelExpansionChanged();
620    }
621
622    /**
623     * @return true if the panel tracking should be temporarily blocked; this is used when a
624     *         conflicting gesture (opening QS) is happening
625     */
626    protected abstract boolean isTrackingBlocked();
627
628    protected abstract void setOverExpansion(float overExpansion, boolean isPixels);
629
630    protected abstract void onHeightUpdated(float expandedHeight);
631
632    protected abstract float getOverExpansionAmount();
633
634    protected abstract float getOverExpansionPixels();
635
636    /**
637     * This returns the maximum height of the panel. Children should override this if their
638     * desired height is not the full height.
639     *
640     * @return the default implementation simply returns the maximum height.
641     */
642    protected abstract int getMaxPanelHeight();
643
644    public void setExpandedFraction(float frac) {
645        setExpandedHeight(getMaxPanelHeight() * frac);
646    }
647
648    public float getExpandedHeight() {
649        return mExpandedHeight;
650    }
651
652    public float getExpandedFraction() {
653        return mExpandedFraction;
654    }
655
656    public boolean isFullyExpanded() {
657        return mExpandedHeight >= getMaxPanelHeight();
658    }
659
660    public boolean isFullyCollapsed() {
661        return mExpandedHeight <= 0;
662    }
663
664    public boolean isCollapsing() {
665        return mClosing;
666    }
667
668    public boolean isTracking() {
669        return mTracking;
670    }
671
672    public void setBar(PanelBar panelBar) {
673        mBar = panelBar;
674    }
675
676    public void collapse(boolean delayed) {
677        if (DEBUG) logf("collapse: " + this);
678        if (mPeekPending || mPeekAnimator != null) {
679            mCollapseAfterPeek = true;
680            if (mPeekPending) {
681
682                // We know that the whole gesture is just a peek triggered by a simple click, so
683                // better start it now.
684                removeCallbacks(mPeekRunnable);
685                mPeekRunnable.run();
686            }
687        } else if (!isFullyCollapsed() && !mTracking && !mClosing) {
688            if (mHeightAnimator != null) {
689                mHeightAnimator.cancel();
690            }
691            mClosing = true;
692            notifyExpandingStarted();
693            if (delayed) {
694                postDelayed(new Runnable() {
695                    @Override
696                    public void run() {
697                        fling(0, false /* expand */);
698                    }
699                }, 120);
700            } else {
701                fling(0, false /* expand */);
702            }
703        }
704    }
705
706    public void expand() {
707        if (DEBUG) logf("expand: " + this);
708        if (isFullyCollapsed()) {
709            mBar.startOpeningPanel(this);
710            notifyExpandingStarted();
711            fling(0, true /* expand */);
712        } else if (DEBUG) {
713            if (DEBUG) logf("skipping expansion: is expanded");
714        }
715    }
716
717    public void cancelPeek() {
718        if (mPeekAnimator != null) {
719            mPeekAnimator.cancel();
720        }
721        removeCallbacks(mPeekRunnable);
722        mPeekPending = false;
723
724        // When peeking, we already tell mBar that we expanded ourselves. Make sure that we also
725        // notify mBar that we might have closed ourselves.
726        notifyBarPanelExpansionChanged();
727    }
728
729    public void instantExpand() {
730        mInstantExpanding = true;
731        abortAnimations();
732        if (mTracking) {
733            onTrackingStopped(true /* expands */); // The panel is expanded after this call.
734        }
735        if (mExpanding) {
736            notifyExpandingFinished();
737        }
738        setVisibility(VISIBLE);
739
740        // Wait for window manager to pickup the change, so we know the maximum height of the panel
741        // then.
742        getViewTreeObserver().addOnGlobalLayoutListener(
743                new ViewTreeObserver.OnGlobalLayoutListener() {
744                    @Override
745                    public void onGlobalLayout() {
746                        if (mStatusBar.getStatusBarWindow().getHeight()
747                                != mStatusBar.getStatusBarHeight()) {
748                            getViewTreeObserver().removeOnGlobalLayoutListener(this);
749                            setExpandedFraction(1f);
750                            mInstantExpanding = false;
751                        }
752                    }
753                });
754
755        // Make sure a layout really happens.
756        requestLayout();
757    }
758
759    private void abortAnimations() {
760        cancelPeek();
761        if (mHeightAnimator != null) {
762            mHeightAnimator.cancel();
763        }
764    }
765
766    protected void startUnlockHintAnimation() {
767
768        // We don't need to hint the user if an animation is already running or the user is changing
769        // the expansion.
770        if (mHeightAnimator != null || mTracking) {
771            return;
772        }
773        cancelPeek();
774        notifyExpandingStarted();
775        startUnlockHintAnimationPhase1(new Runnable() {
776            @Override
777            public void run() {
778                notifyExpandingFinished();
779                mStatusBar.onHintFinished();
780                mHintAnimationRunning = false;
781            }
782        });
783        mStatusBar.onUnlockHintStarted();
784        mHintAnimationRunning = true;
785    }
786
787    /**
788     * Phase 1: Move everything upwards.
789     */
790    private void startUnlockHintAnimationPhase1(final Runnable onAnimationFinished) {
791        float target = Math.max(0, getMaxPanelHeight() - mHintDistance);
792        ValueAnimator animator = createHeightAnimator(target);
793        animator.setDuration(250);
794        animator.setInterpolator(mFastOutSlowInInterpolator);
795        animator.addListener(new AnimatorListenerAdapter() {
796            private boolean mCancelled;
797
798            @Override
799            public void onAnimationCancel(Animator animation) {
800                mCancelled = true;
801            }
802
803            @Override
804            public void onAnimationEnd(Animator animation) {
805                if (mCancelled) {
806                    mHeightAnimator = null;
807                    onAnimationFinished.run();
808                } else {
809                    startUnlockHintAnimationPhase2(onAnimationFinished);
810                }
811            }
812        });
813        animator.start();
814        mHeightAnimator = animator;
815        mOriginalIndicationY = mKeyguardBottomArea.getIndicationView().getY();
816        mKeyguardBottomArea.getIndicationView().animate()
817                .y(mOriginalIndicationY - mHintDistance)
818                .setDuration(250)
819                .setInterpolator(mFastOutSlowInInterpolator)
820                .withEndAction(new Runnable() {
821                    @Override
822                    public void run() {
823                        mKeyguardBottomArea.getIndicationView().animate()
824                                .y(mOriginalIndicationY)
825                                .setDuration(450)
826                                .setInterpolator(mBounceInterpolator)
827                                .start();
828                    }
829                })
830                .start();
831    }
832
833    /**
834     * Phase 2: Bounce down.
835     */
836    private void startUnlockHintAnimationPhase2(final Runnable onAnimationFinished) {
837        ValueAnimator animator = createHeightAnimator(getMaxPanelHeight());
838        animator.setDuration(450);
839        animator.setInterpolator(mBounceInterpolator);
840        animator.addListener(new AnimatorListenerAdapter() {
841            @Override
842            public void onAnimationEnd(Animator animation) {
843                mHeightAnimator = null;
844                onAnimationFinished.run();
845            }
846        });
847        animator.start();
848        mHeightAnimator = animator;
849    }
850
851    private ValueAnimator createHeightAnimator(float targetHeight) {
852        ValueAnimator animator = ValueAnimator.ofFloat(mExpandedHeight, targetHeight);
853        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
854            @Override
855            public void onAnimationUpdate(ValueAnimator animation) {
856                setExpandedHeightInternal((Float) animation.getAnimatedValue());
857            }
858        });
859        return animator;
860    }
861
862    private void notifyBarPanelExpansionChanged() {
863        mBar.panelExpansionChanged(this, mExpandedFraction, mExpandedFraction > 0f || mPeekPending
864                || mPeekAnimator != null);
865    }
866
867    /**
868     * Gets called when the user performs a click anywhere in the empty area of the panel.
869     *
870     * @return whether the panel will be expanded after the action performed by this method
871     */
872    private boolean onEmptySpaceClick(float x) {
873        if (mHintAnimationRunning) {
874            return true;
875        }
876        if (x < mEdgeTapAreaWidth
877                && mStatusBar.getBarState() == StatusBarState.KEYGUARD) {
878            onEdgeClicked(false /* right */);
879            return true;
880        } else if (x > getWidth() - mEdgeTapAreaWidth
881                && mStatusBar.getBarState() == StatusBarState.KEYGUARD) {
882            onEdgeClicked(true /* right */);
883            return true;
884        } else {
885            return onMiddleClicked();
886        }
887    }
888
889    private final Runnable mPostCollapseRunnable = new Runnable() {
890        @Override
891        public void run() {
892            collapse(false /* delayed */);
893        }
894    };
895    private boolean onMiddleClicked() {
896        switch (mStatusBar.getBarState()) {
897            case StatusBarState.KEYGUARD:
898                startUnlockHintAnimation();
899                return true;
900            case StatusBarState.SHADE_LOCKED:
901                mStatusBar.goToKeyguard();
902                return true;
903            case StatusBarState.SHADE:
904
905                // This gets called in the middle of the touch handling, where the state is still
906                // that we are tracking the panel. Collapse the panel after this is done.
907                post(mPostCollapseRunnable);
908                return false;
909            default:
910                return true;
911        }
912    }
913
914    protected abstract void onEdgeClicked(boolean right);
915
916    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
917        pw.println(String.format("[PanelView(%s): expandedHeight=%f maxPanelHeight=%d closing=%s"
918                + " tracking=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s"
919                + "]",
920                this.getClass().getSimpleName(),
921                getExpandedHeight(),
922                getMaxPanelHeight(),
923                mClosing?"T":"f",
924                mTracking?"T":"f",
925                mJustPeeked?"T":"f",
926                mPeekAnimator, ((mPeekAnimator!=null && mPeekAnimator.isStarted())?" (started)":""),
927                mHeightAnimator, ((mHeightAnimator !=null && mHeightAnimator.isStarted())?" (started)":"")
928        ));
929    }
930
931    public abstract void resetViews();
932
933    protected abstract float getPeekHeight();
934
935    protected abstract float getCannedFlingDurationFactor();
936
937    /**
938     * @return whether "Clear all" button will be visible when the panel is fully expanded
939     */
940    protected abstract boolean fullyExpandedClearAllVisible();
941
942    protected abstract boolean isClearAllVisible();
943
944    /**
945     * @return the height of the clear all button, in pixels
946     */
947    protected abstract int getClearAllHeight();
948}
949