PanelView.java revision 19c8c708f16546fc75ae12659aa190f5e3dfbb52
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 (!mTouchAboveFalsingThreshold && mStatusBar.isFalsingThresholdNeeded()) {
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    protected void fling(float vel, boolean expand) {
493        cancelPeek();
494        float target = expand ? getMaxPanelHeight() : 0.0f;
495
496        // Hack to make the expand transition look nice when clear all button is visible - we make
497        // the animation only to the last notification, and then jump to the maximum panel height so
498        // clear all just fades in and the decelerating motion is towards the last notification.
499        final boolean clearAllExpandHack = expand && fullyExpandedClearAllVisible()
500                && mExpandedHeight < getMaxPanelHeight() - getClearAllHeight()
501                && !isClearAllVisible();
502        if (clearAllExpandHack) {
503            target = getMaxPanelHeight() - getClearAllHeight();
504        }
505        if (target == mExpandedHeight || getOverExpansionAmount() > 0f && expand) {
506            notifyExpandingFinished();
507            return;
508        }
509        mOverExpandedBeforeFling = getOverExpansionAmount() > 0f;
510        ValueAnimator animator = createHeightAnimator(target);
511        if (expand) {
512            mFlingAnimationUtils.apply(animator, mExpandedHeight, target, vel, getHeight());
513        } else {
514            mFlingAnimationUtils.applyDismissing(animator, mExpandedHeight, target, vel,
515                    getHeight());
516
517            // Make it shorter if we run a canned animation
518            if (vel == 0) {
519                animator.setDuration((long)
520                        (animator.getDuration() * getCannedFlingDurationFactor()));
521            }
522        }
523        animator.addListener(new AnimatorListenerAdapter() {
524            private boolean mCancelled;
525
526            @Override
527            public void onAnimationCancel(Animator animation) {
528                mCancelled = true;
529            }
530
531            @Override
532            public void onAnimationEnd(Animator animation) {
533                if (clearAllExpandHack && !mCancelled) {
534                    setExpandedHeightInternal(getMaxPanelHeight());
535                }
536                mHeightAnimator = null;
537                if (!mCancelled) {
538                    notifyExpandingFinished();
539                }
540            }
541        });
542        mHeightAnimator = animator;
543        animator.start();
544    }
545
546    @Override
547    protected void onAttachedToWindow() {
548        super.onAttachedToWindow();
549        mViewName = getResources().getResourceName(getId());
550    }
551
552    public String getName() {
553        return mViewName;
554    }
555
556    public void setExpandedHeight(float height) {
557        if (DEBUG) logf("setExpandedHeight(%.1f)", height);
558        setExpandedHeightInternal(height + getOverExpansionPixels());
559    }
560
561    @Override
562    protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
563        super.onLayout(changed, left, top, right, bottom);
564        requestPanelHeightUpdate();
565        mHasLayoutedSinceDown = true;
566        if (mUpdateFlingOnLayout) {
567            abortAnimations();
568            fling(mUpdateFlingVelocity, true);
569            mUpdateFlingOnLayout = false;
570        }
571    }
572
573    protected void requestPanelHeightUpdate() {
574        float currentMaxPanelHeight = getMaxPanelHeight();
575
576        // If the user isn't actively poking us, let's update the height
577        if ((!mTracking || isTrackingBlocked())
578                && mHeightAnimator == null
579                && mExpandedHeight > 0
580                && currentMaxPanelHeight != mExpandedHeight
581                && !mPeekPending
582                && mPeekAnimator == null
583                && !mPeekTouching) {
584            setExpandedHeight(currentMaxPanelHeight);
585        }
586    }
587
588    public void setExpandedHeightInternal(float h) {
589        float fhWithoutOverExpansion = getMaxPanelHeight() - getOverExpansionAmount();
590        if (mHeightAnimator == null) {
591            float overExpansionPixels = Math.max(0, h - fhWithoutOverExpansion);
592            if (getOverExpansionPixels() != overExpansionPixels && mTracking) {
593                setOverExpansion(overExpansionPixels, true /* isPixels */);
594            }
595            mExpandedHeight = Math.min(h, fhWithoutOverExpansion) + getOverExpansionAmount();
596        } else {
597            mExpandedHeight = h;
598            if (mOverExpandedBeforeFling) {
599                setOverExpansion(Math.max(0, h - fhWithoutOverExpansion), false /* isPixels */);
600            }
601        }
602
603        mExpandedHeight = Math.max(0, mExpandedHeight);
604        onHeightUpdated(mExpandedHeight);
605        mExpandedFraction = Math.min(1f, fhWithoutOverExpansion == 0
606                ? 0
607                : mExpandedHeight / fhWithoutOverExpansion);
608        notifyBarPanelExpansionChanged();
609    }
610
611    /**
612     * @return true if the panel tracking should be temporarily blocked; this is used when a
613     *         conflicting gesture (opening QS) is happening
614     */
615    protected abstract boolean isTrackingBlocked();
616
617    protected abstract void setOverExpansion(float overExpansion, boolean isPixels);
618
619    protected abstract void onHeightUpdated(float expandedHeight);
620
621    protected abstract float getOverExpansionAmount();
622
623    protected abstract float getOverExpansionPixels();
624
625    /**
626     * This returns the maximum height of the panel. Children should override this if their
627     * desired height is not the full height.
628     *
629     * @return the default implementation simply returns the maximum height.
630     */
631    protected abstract int getMaxPanelHeight();
632
633    public void setExpandedFraction(float frac) {
634        setExpandedHeight(getMaxPanelHeight() * frac);
635    }
636
637    public float getExpandedHeight() {
638        return mExpandedHeight;
639    }
640
641    public float getExpandedFraction() {
642        return mExpandedFraction;
643    }
644
645    public boolean isFullyExpanded() {
646        return mExpandedHeight >= getMaxPanelHeight();
647    }
648
649    public boolean isFullyCollapsed() {
650        return mExpandedHeight <= 0;
651    }
652
653    public boolean isCollapsing() {
654        return mClosing;
655    }
656
657    public boolean isTracking() {
658        return mTracking;
659    }
660
661    public void setBar(PanelBar panelBar) {
662        mBar = panelBar;
663    }
664
665    public void collapse(boolean delayed) {
666        if (DEBUG) logf("collapse: " + this);
667        if (mPeekPending || mPeekAnimator != null) {
668            mCollapseAfterPeek = true;
669            if (mPeekPending) {
670
671                // We know that the whole gesture is just a peek triggered by a simple click, so
672                // better start it now.
673                removeCallbacks(mPeekRunnable);
674                mPeekRunnable.run();
675            }
676        } else if (!isFullyCollapsed() && !mTracking) {
677            if (mHeightAnimator != null) {
678                mHeightAnimator.cancel();
679            }
680            mClosing = true;
681            notifyExpandingStarted();
682            if (delayed) {
683                postDelayed(new Runnable() {
684                    @Override
685                    public void run() {
686                        fling(0, false /* expand */);
687                    }
688                }, 120);
689            } else {
690                fling(0, false /* expand */);
691            }
692        }
693    }
694
695    public void expand() {
696        if (DEBUG) logf("expand: " + this);
697        if (isFullyCollapsed()) {
698            mBar.startOpeningPanel(this);
699            notifyExpandingStarted();
700            fling(0, true /* expand */);
701        } else if (DEBUG) {
702            if (DEBUG) logf("skipping expansion: is expanded");
703        }
704    }
705
706    public void cancelPeek() {
707        if (mPeekAnimator != null) {
708            mPeekAnimator.cancel();
709        }
710        removeCallbacks(mPeekRunnable);
711        mPeekPending = false;
712
713        // When peeking, we already tell mBar that we expanded ourselves. Make sure that we also
714        // notify mBar that we might have closed ourselves.
715        notifyBarPanelExpansionChanged();
716    }
717
718    public void instantExpand() {
719        mInstantExpanding = true;
720        abortAnimations();
721        if (mTracking) {
722            onTrackingStopped(true /* expands */); // The panel is expanded after this call.
723            notifyExpandingFinished();
724        }
725        setVisibility(VISIBLE);
726
727        // Wait for window manager to pickup the change, so we know the maximum height of the panel
728        // then.
729        getViewTreeObserver().addOnGlobalLayoutListener(
730                new ViewTreeObserver.OnGlobalLayoutListener() {
731                    @Override
732                    public void onGlobalLayout() {
733                        if (mStatusBar.getStatusBarWindow().getHeight()
734                                != mStatusBar.getStatusBarHeight()) {
735                            getViewTreeObserver().removeOnGlobalLayoutListener(this);
736                            setExpandedFraction(1f);
737                            mInstantExpanding = false;
738                        }
739                    }
740                });
741
742        // Make sure a layout really happens.
743        requestLayout();
744    }
745
746    private void abortAnimations() {
747        cancelPeek();
748        if (mHeightAnimator != null) {
749            mHeightAnimator.cancel();
750        }
751    }
752
753    protected void startUnlockHintAnimation() {
754
755        // We don't need to hint the user if an animation is already running or the user is changing
756        // the expansion.
757        if (mHeightAnimator != null || mTracking) {
758            return;
759        }
760        cancelPeek();
761        notifyExpandingStarted();
762        startUnlockHintAnimationPhase1(new Runnable() {
763            @Override
764            public void run() {
765                notifyExpandingFinished();
766                mStatusBar.onHintFinished();
767                mHintAnimationRunning = false;
768            }
769        });
770        mStatusBar.onUnlockHintStarted();
771        mHintAnimationRunning = true;
772    }
773
774    /**
775     * Phase 1: Move everything upwards.
776     */
777    private void startUnlockHintAnimationPhase1(final Runnable onAnimationFinished) {
778        float target = Math.max(0, getMaxPanelHeight() - mHintDistance);
779        ValueAnimator animator = createHeightAnimator(target);
780        animator.setDuration(250);
781        animator.setInterpolator(mFastOutSlowInInterpolator);
782        animator.addListener(new AnimatorListenerAdapter() {
783            private boolean mCancelled;
784
785            @Override
786            public void onAnimationCancel(Animator animation) {
787                mCancelled = true;
788            }
789
790            @Override
791            public void onAnimationEnd(Animator animation) {
792                if (mCancelled) {
793                    mHeightAnimator = null;
794                    onAnimationFinished.run();
795                } else {
796                    startUnlockHintAnimationPhase2(onAnimationFinished);
797                }
798            }
799        });
800        animator.start();
801        mHeightAnimator = animator;
802        mOriginalIndicationY = mKeyguardBottomArea.getIndicationView().getY();
803        mKeyguardBottomArea.getIndicationView().animate()
804                .y(mOriginalIndicationY - mHintDistance)
805                .setDuration(250)
806                .setInterpolator(mFastOutSlowInInterpolator)
807                .withEndAction(new Runnable() {
808                    @Override
809                    public void run() {
810                        mKeyguardBottomArea.getIndicationView().animate()
811                                .y(mOriginalIndicationY)
812                                .setDuration(450)
813                                .setInterpolator(mBounceInterpolator)
814                                .start();
815                    }
816                })
817                .start();
818    }
819
820    /**
821     * Phase 2: Bounce down.
822     */
823    private void startUnlockHintAnimationPhase2(final Runnable onAnimationFinished) {
824        ValueAnimator animator = createHeightAnimator(getMaxPanelHeight());
825        animator.setDuration(450);
826        animator.setInterpolator(mBounceInterpolator);
827        animator.addListener(new AnimatorListenerAdapter() {
828            @Override
829            public void onAnimationEnd(Animator animation) {
830                mHeightAnimator = null;
831                onAnimationFinished.run();
832            }
833        });
834        animator.start();
835        mHeightAnimator = animator;
836    }
837
838    private ValueAnimator createHeightAnimator(float targetHeight) {
839        ValueAnimator animator = ValueAnimator.ofFloat(mExpandedHeight, targetHeight);
840        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
841            @Override
842            public void onAnimationUpdate(ValueAnimator animation) {
843                setExpandedHeightInternal((Float) animation.getAnimatedValue());
844            }
845        });
846        return animator;
847    }
848
849    private void notifyBarPanelExpansionChanged() {
850        mBar.panelExpansionChanged(this, mExpandedFraction, mExpandedFraction > 0f || mPeekPending
851                || mPeekAnimator != null);
852    }
853
854    /**
855     * Gets called when the user performs a click anywhere in the empty area of the panel.
856     *
857     * @return whether the panel will be expanded after the action performed by this method
858     */
859    private boolean onEmptySpaceClick(float x) {
860        if (mHintAnimationRunning) {
861            return true;
862        }
863        if (x < mEdgeTapAreaWidth
864                && mStatusBar.getBarState() == StatusBarState.KEYGUARD) {
865            onEdgeClicked(false /* right */);
866            return true;
867        } else if (x > getWidth() - mEdgeTapAreaWidth
868                && mStatusBar.getBarState() == StatusBarState.KEYGUARD) {
869            onEdgeClicked(true /* right */);
870            return true;
871        } else {
872            return onMiddleClicked();
873        }
874    }
875
876    private final Runnable mPostCollapseRunnable = new Runnable() {
877        @Override
878        public void run() {
879            collapse(false /* delayed */);
880        }
881    };
882    private boolean onMiddleClicked() {
883        switch (mStatusBar.getBarState()) {
884            case StatusBarState.KEYGUARD:
885                startUnlockHintAnimation();
886                return true;
887            case StatusBarState.SHADE_LOCKED:
888                mStatusBar.goToKeyguard();
889                return true;
890            case StatusBarState.SHADE:
891
892                // This gets called in the middle of the touch handling, where the state is still
893                // that we are tracking the panel. Collapse the panel after this is done.
894                post(mPostCollapseRunnable);
895                return false;
896            default:
897                return true;
898        }
899    }
900
901    protected abstract void onEdgeClicked(boolean right);
902
903    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
904        pw.println(String.format("[PanelView(%s): expandedHeight=%f maxPanelHeight=%d closing=%s"
905                + " tracking=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s"
906                + "]",
907                this.getClass().getSimpleName(),
908                getExpandedHeight(),
909                getMaxPanelHeight(),
910                mClosing?"T":"f",
911                mTracking?"T":"f",
912                mJustPeeked?"T":"f",
913                mPeekAnimator, ((mPeekAnimator!=null && mPeekAnimator.isStarted())?" (started)":""),
914                mHeightAnimator, ((mHeightAnimator !=null && mHeightAnimator.isStarted())?" (started)":"")
915        ));
916    }
917
918    public abstract void resetViews();
919
920    protected abstract float getPeekHeight();
921
922    protected abstract float getCannedFlingDurationFactor();
923
924    /**
925     * @return whether "Clear all" button will be visible when the panel is fully expanded
926     */
927    protected abstract boolean fullyExpandedClearAllVisible();
928
929    protected abstract boolean isClearAllVisible();
930
931    /**
932     * @return the height of the clear all button, in pixels
933     */
934    protected abstract int getClearAllHeight();
935}
936