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