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