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