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