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