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