PanelView.java revision 8dd95e03f8555c278217bac7e4faef865b1850a7
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.animation.AnimationUtils;
31import android.view.animation.Interpolator;
32import android.widget.FrameLayout;
33
34import com.android.systemui.R;
35import com.android.systemui.statusbar.FlingAnimationUtils;
36import com.android.systemui.statusbar.StatusBarState;
37
38import java.io.FileDescriptor;
39import java.io.PrintWriter;
40
41public abstract class PanelView extends FrameLayout {
42    public static final boolean DEBUG = PanelBar.DEBUG;
43    public static final String TAG = PanelView.class.getSimpleName();
44    protected float mOverExpansion;
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    private float mExpandedHeight = 0;
57    private boolean mJustPeeked;
58    private boolean mClosing;
59    protected boolean mTracking;
60    private boolean mTouchSlopExceeded;
61    private int mTrackingPointer;
62    protected int mTouchSlop;
63    protected boolean mHintAnimationRunning;
64
65    private ValueAnimator mHeightAnimator;
66    private ObjectAnimator mPeekAnimator;
67    private VelocityTrackerInterface mVelocityTracker;
68    private FlingAnimationUtils mFlingAnimationUtils;
69
70    PanelBar mBar;
71
72    protected int mMaxPanelHeight = -1;
73    private String mViewName;
74    private float mInitialTouchY;
75    private float mInitialTouchX;
76
77    private Interpolator mLinearOutSlowInInterpolator;
78    private Interpolator mBounceInterpolator;
79
80    protected void onExpandingFinished() {
81        mBar.onExpandingFinished();
82    }
83
84    protected void onExpandingStarted() {
85    }
86
87    private void runPeekAnimation() {
88        if (DEBUG) logf("peek to height=%.1f", mPeekHeight);
89        if (mHeightAnimator != null) {
90            return;
91        }
92        if (mPeekAnimator == null) {
93            mPeekAnimator = ObjectAnimator.ofFloat(this,
94                    "expandedHeight", mPeekHeight)
95                .setDuration(250);
96        }
97        mPeekAnimator.start();
98    }
99
100    public PanelView(Context context, AttributeSet attrs) {
101        super(context, attrs);
102        mFlingAnimationUtils = new FlingAnimationUtils(context, 0.6f);
103        mLinearOutSlowInInterpolator =
104                AnimationUtils.loadInterpolator(context, android.R.interpolator.fast_out_slow_in);
105        mBounceInterpolator = new BounceInterpolator();
106    }
107
108    protected void loadDimens() {
109        final Resources res = getContext().getResources();
110        mPeekHeight = res.getDimension(R.dimen.peek_height)
111            + getPaddingBottom(); // our window might have a dropshadow
112
113        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
114        mTouchSlop = configuration.getScaledTouchSlop();
115        mHintDistance = res.getDimension(R.dimen.hint_move_distance);
116        mEdgeTapAreaWidth = res.getDimensionPixelSize(R.dimen.edge_tap_area_width);
117    }
118
119    private void trackMovement(MotionEvent event) {
120        // Add movement to velocity tracker using raw screen X and Y coordinates instead
121        // of window coordinates because the window frame may be moving at the same time.
122        float deltaX = event.getRawX() - event.getX();
123        float deltaY = event.getRawY() - event.getY();
124        event.offsetLocation(deltaX, deltaY);
125        if (mVelocityTracker != null) mVelocityTracker.addMovement(event);
126        event.offsetLocation(-deltaX, -deltaY);
127    }
128
129    @Override
130    public boolean onTouchEvent(MotionEvent event) {
131
132        /*
133         * We capture touch events here and update the expand height here in case according to
134         * the users fingers. This also handles multi-touch.
135         *
136         * If the user just clicks shortly, we give him a quick peek of the shade.
137         *
138         * Flinging is also enabled in order to open or close the shade.
139         */
140
141        int pointerIndex = event.findPointerIndex(mTrackingPointer);
142        if (pointerIndex < 0) {
143            pointerIndex = 0;
144            mTrackingPointer = event.getPointerId(pointerIndex);
145        }
146        final float y = event.getY(pointerIndex);
147        final float x = event.getX(pointerIndex);
148
149        boolean waitForTouchSlop = hasConflictingGestures();
150
151        switch (event.getActionMasked()) {
152            case MotionEvent.ACTION_DOWN:
153                mInitialTouchY = y;
154                mInitialTouchX = x;
155                mInitialOffsetOnTouch = mExpandedHeight;
156                mTouchSlopExceeded = false;
157                if (mVelocityTracker == null) {
158                    initVelocityTracker();
159                }
160                trackMovement(event);
161                if (!waitForTouchSlop || (mHeightAnimator != null && !mHintAnimationRunning)) {
162                    if (mHeightAnimator != null) {
163                        mHeightAnimator.cancel(); // end any outstanding animations
164                    }
165                    mTouchSlopExceeded = true;
166                    onTrackingStarted();
167                }
168                if (mExpandedHeight == 0) {
169                    mJustPeeked = true;
170                    runPeekAnimation();
171                }
172                break;
173
174            case MotionEvent.ACTION_POINTER_UP:
175                final int upPointer = event.getPointerId(event.getActionIndex());
176                if (mTrackingPointer == upPointer) {
177                    // gesture is ongoing, find a new pointer to track
178                    final int newIndex = event.getPointerId(0) != upPointer ? 0 : 1;
179                    final float newY = event.getY(newIndex);
180                    final float newX = event.getX(newIndex);
181                    mTrackingPointer = event.getPointerId(newIndex);
182                    mInitialOffsetOnTouch = mExpandedHeight;
183                    mInitialTouchY = newY;
184                    mInitialTouchX = newX;
185                }
186                break;
187
188            case MotionEvent.ACTION_MOVE:
189                float h = y - mInitialTouchY;
190                if (Math.abs(h) > mTouchSlop && Math.abs(h) > Math.abs(x - mInitialTouchX)) {
191                    mTouchSlopExceeded = true;
192                    if (waitForTouchSlop && !mTracking) {
193                        mInitialOffsetOnTouch = mExpandedHeight;
194                        mInitialTouchX = x;
195                        mInitialTouchY = y;
196                        if (mHeightAnimator != null) {
197                            mHeightAnimator.cancel(); // end any outstanding animations
198                        }
199                        onTrackingStarted();
200                        h = 0;
201                    }
202                }
203                final float newHeight = h + mInitialOffsetOnTouch;
204                if (newHeight > mPeekHeight) {
205                    if (mPeekAnimator != null && mPeekAnimator.isStarted()) {
206                        mPeekAnimator.cancel();
207                    }
208                    mJustPeeked = false;
209                }
210                if (!mJustPeeked && (!waitForTouchSlop || mTracking)) {
211                    setExpandedHeightInternal(newHeight);
212                    mBar.panelExpansionChanged(PanelView.this, mExpandedFraction);
213                }
214
215                trackMovement(event);
216                break;
217
218            case MotionEvent.ACTION_UP:
219            case MotionEvent.ACTION_CANCEL:
220                mTrackingPointer = -1;
221                trackMovement(event);
222                if (mTracking && mTouchSlopExceeded) {
223                    float vel = getCurrentVelocity();
224                    boolean expand = flingExpands(vel);
225                    onTrackingStopped(expand);
226                    fling(vel, expand);
227                } else {
228                    boolean expands = onEmptySpaceClick(mInitialTouchX);
229                    onTrackingStopped(expands);
230                }
231                if (mVelocityTracker != null) {
232                    mVelocityTracker.recycle();
233                    mVelocityTracker = null;
234                }
235                break;
236        }
237        return !waitForTouchSlop || mTracking;
238    }
239
240    protected abstract boolean hasConflictingGestures();
241
242    protected void onTrackingStopped(boolean expand) {
243        mTracking = false;
244        mBar.onTrackingStopped(PanelView.this, expand);
245    }
246
247    protected void onTrackingStarted() {
248        mTracking = true;
249        mBar.onTrackingStarted(PanelView.this);
250        onExpandingStarted();
251    }
252
253    private float getCurrentVelocity() {
254
255        // the velocitytracker might be null if we got a bad input stream
256        if (mVelocityTracker == null) {
257            return 0;
258        }
259        mVelocityTracker.computeCurrentVelocity(1000);
260        return mVelocityTracker.getYVelocity();
261    }
262
263    @Override
264    public boolean onInterceptTouchEvent(MotionEvent event) {
265
266        /*
267         * If the user drags anywhere inside the panel we intercept it if he moves his finger
268         * upwards. This allows closing the shade from anywhere inside the panel.
269         *
270         * We only do this if the current content is scrolled to the bottom,
271         * i.e isScrolledToBottom() is true and therefore there is no conflicting scrolling gesture
272         * possible.
273         */
274        int pointerIndex = event.findPointerIndex(mTrackingPointer);
275        if (pointerIndex < 0) {
276            pointerIndex = 0;
277            mTrackingPointer = event.getPointerId(pointerIndex);
278        }
279        final float x = event.getX(pointerIndex);
280        final float y = event.getY(pointerIndex);
281        boolean scrolledToBottom = isScrolledToBottom();
282
283        switch (event.getActionMasked()) {
284            case MotionEvent.ACTION_DOWN:
285                if (mHeightAnimator != null && !mHintAnimationRunning) {
286                    mHeightAnimator.cancel(); // end any outstanding animations
287                    mTouchSlopExceeded = true;
288                    return true;
289                }
290                mInitialTouchY = y;
291                mInitialTouchX = x;
292                mTouchSlopExceeded = false;
293                initVelocityTracker();
294                trackMovement(event);
295                break;
296            case MotionEvent.ACTION_POINTER_UP:
297                final int upPointer = event.getPointerId(event.getActionIndex());
298                if (mTrackingPointer == upPointer) {
299                    // gesture is ongoing, find a new pointer to track
300                    final int newIndex = event.getPointerId(0) != upPointer ? 0 : 1;
301                    mTrackingPointer = event.getPointerId(newIndex);
302                    mInitialTouchX = event.getX(newIndex);
303                    mInitialTouchY = event.getY(newIndex);
304                }
305                break;
306
307            case MotionEvent.ACTION_MOVE:
308                final float h = y - mInitialTouchY;
309                trackMovement(event);
310                if (scrolledToBottom) {
311                    if (h < -mTouchSlop && h < -Math.abs(x - mInitialTouchX)) {
312                        if (mHeightAnimator != null) {
313                            mHeightAnimator.cancel();
314                        }
315                        mInitialOffsetOnTouch = mExpandedHeight;
316                        mInitialTouchY = y;
317                        mInitialTouchX = x;
318                        mTracking = true;
319                        mTouchSlopExceeded = true;
320                        onTrackingStarted();
321                        return true;
322                    }
323                }
324                break;
325        }
326        return false;
327    }
328
329    private void initVelocityTracker() {
330        if (mVelocityTracker != null) {
331            mVelocityTracker.recycle();
332        }
333        mVelocityTracker = VelocityTrackerFactory.obtain(getContext());
334    }
335
336    protected boolean isScrolledToBottom() {
337        return true;
338    }
339
340    protected float getContentHeight() {
341        return mExpandedHeight;
342    }
343
344    @Override
345    protected void onFinishInflate() {
346        super.onFinishInflate();
347        loadDimens();
348    }
349
350    @Override
351    protected void onConfigurationChanged(Configuration newConfig) {
352        super.onConfigurationChanged(newConfig);
353        loadDimens();
354        mMaxPanelHeight = -1;
355    }
356
357    /**
358     * @param vel the current velocity of the motion
359     * @return whether a fling should expands the panel; contracts otherwise
360     */
361    private boolean flingExpands(float vel) {
362        if (Math.abs(vel) < mFlingAnimationUtils.getMinVelocityPxPerSecond()) {
363            return getExpandedFraction() > 0.5f;
364        } else {
365            return vel > 0;
366        }
367    }
368
369    protected void fling(float vel, boolean expand) {
370        cancelPeek();
371        float target = expand ? getMaxPanelHeight() : 0.0f;
372        if (target == mExpandedHeight) {
373            onExpandingFinished();
374            mBar.panelExpansionChanged(this, mExpandedFraction);
375            return;
376        }
377        ValueAnimator animator = createHeightAnimator(target);
378        if (expand) {
379            mFlingAnimationUtils.apply(animator, mExpandedHeight, target, vel, getHeight());
380        } else {
381            mFlingAnimationUtils.applyDismissing(animator, mExpandedHeight, target, vel,
382                    getHeight());
383
384            // Make it shorter if we run a canned animation
385            if (vel == 0) {
386                animator.setDuration((long) (animator.getDuration() / 1.75f));
387            }
388        }
389        animator.addListener(new AnimatorListenerAdapter() {
390            @Override
391            public void onAnimationEnd(Animator animation) {
392                mHeightAnimator = null;
393                onExpandingFinished();
394            }
395        });
396        animator.start();
397        mHeightAnimator = animator;
398    }
399
400    @Override
401    protected void onAttachedToWindow() {
402        super.onAttachedToWindow();
403        mViewName = getResources().getResourceName(getId());
404    }
405
406    public String getName() {
407        return mViewName;
408    }
409
410    @Override
411    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
412        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
413
414        if (DEBUG) logf("onMeasure(%d, %d) -> (%d, %d)",
415                widthMeasureSpec, heightMeasureSpec, getMeasuredWidth(), getMeasuredHeight());
416
417        // Did one of our children change size?
418        int newHeight = getMeasuredHeight();
419        if (newHeight > mMaxPanelHeight) {
420            // we only adapt the max height if it's bigger
421            mMaxPanelHeight = newHeight;
422            // If the user isn't actively poking us, let's rubberband to the content
423            if (!mTracking && mHeightAnimator == null
424                    && mExpandedHeight > 0 && mExpandedHeight != mMaxPanelHeight
425                    && mMaxPanelHeight > 0) {
426                mExpandedHeight = mMaxPanelHeight;
427            }
428        }
429    }
430
431    public void setExpandedHeight(float height) {
432        if (DEBUG) logf("setExpandedHeight(%.1f)", height);
433        setExpandedHeightInternal(height);
434        mBar.panelExpansionChanged(PanelView.this, mExpandedFraction);
435    }
436
437    @Override
438    protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
439        if (DEBUG) logf("onLayout: changed=%s, bottom=%d eh=%d fh=%d", changed?"T":"f", bottom,
440                (int)mExpandedHeight, mMaxPanelHeight);
441        super.onLayout(changed, left, top, right, bottom);
442        requestPanelHeightUpdate();
443    }
444
445    protected void requestPanelHeightUpdate() {
446        float currentMaxPanelHeight = getMaxPanelHeight();
447
448        // If the user isn't actively poking us, let's update the height
449        if (!mTracking && mHeightAnimator == null
450                && mExpandedHeight > 0 && currentMaxPanelHeight != mExpandedHeight) {
451            setExpandedHeightInternal(currentMaxPanelHeight);
452        }
453    }
454
455    public void setExpandedHeightInternal(float h) {
456        float fh = getMaxPanelHeight();
457        mExpandedHeight = Math.max(0, Math.min(fh, h));
458        float overExpansion = h - fh;
459        overExpansion = Math.max(0, overExpansion);
460        if (overExpansion != mOverExpansion) {
461            onOverExpansionChanged(overExpansion);
462        }
463
464        if (DEBUG) {
465            logf("setExpansion: height=%.1f fh=%.1f tracking=%s", h, fh, mTracking ? "T" : "f");
466        }
467
468        onHeightUpdated(mExpandedHeight);
469        mExpandedFraction = Math.min(1f, (fh == 0) ? 0 : mExpandedHeight / fh);
470    }
471
472    protected void onOverExpansionChanged(float overExpansion) {
473        mOverExpansion = overExpansion;
474    }
475
476    protected abstract void onHeightUpdated(float expandedHeight);
477
478    /**
479     * This returns the maximum height of the panel. Children should override this if their
480     * desired height is not the full height.
481     *
482     * @return the default implementation simply returns the maximum height.
483     */
484    protected int getMaxPanelHeight() {
485        mMaxPanelHeight = Math.max(mMaxPanelHeight, getHeight());
486        return mMaxPanelHeight;
487    }
488
489    public void setExpandedFraction(float frac) {
490        setExpandedHeight(getMaxPanelHeight() * frac);
491    }
492
493    public float getExpandedHeight() {
494        return mExpandedHeight;
495    }
496
497    public float getExpandedFraction() {
498        return mExpandedFraction;
499    }
500
501    public boolean isFullyExpanded() {
502        return mExpandedHeight >= getMaxPanelHeight();
503    }
504
505    public boolean isFullyCollapsed() {
506        return mExpandedHeight <= 0;
507    }
508
509    public boolean isCollapsing() {
510        return mClosing;
511    }
512
513    public boolean isTracking() {
514        return mTracking;
515    }
516
517    public void setBar(PanelBar panelBar) {
518        mBar = panelBar;
519    }
520
521    public void collapse() {
522        // TODO: abort animation or ongoing touch
523        if (DEBUG) logf("collapse: " + this);
524        if (!isFullyCollapsed()) {
525            if (mHeightAnimator != null) {
526                mHeightAnimator.cancel();
527            }
528            mClosing = true;
529            onExpandingStarted();
530            fling(0, false /* expand */);
531        }
532    }
533
534    public void expand() {
535        if (DEBUG) logf("expand: " + this);
536        if (isFullyCollapsed()) {
537            mBar.startOpeningPanel(this);
538            onExpandingStarted();
539            fling(0, true /* expand */);
540        } else if (DEBUG) {
541            if (DEBUG) logf("skipping expansion: is expanded");
542        }
543    }
544
545    public void cancelPeek() {
546        if (mPeekAnimator != null && mPeekAnimator.isStarted()) {
547            mPeekAnimator.cancel();
548        }
549    }
550
551    protected void startUnlockHintAnimation() {
552
553        // We don't need to hint the user if an animation is already running or the user is changing
554        // the expansion.
555        if (mHeightAnimator != null || mTracking) {
556            return;
557        }
558        cancelPeek();
559        onExpandingStarted();
560        startUnlockHintAnimationPhase1(new Runnable() {
561            @Override
562            public void run() {
563                onExpandingFinished();
564                mStatusBar.onHintFinished();
565                mHintAnimationRunning = false;
566            }
567        });
568        mStatusBar.onUnlockHintStarted();
569        mHintAnimationRunning = true;
570    }
571
572    /**
573     * Phase 1: Move everything upwards.
574     */
575    private void startUnlockHintAnimationPhase1(final Runnable onAnimationFinished) {
576        float target = Math.max(0, getMaxPanelHeight() - mHintDistance);
577        ValueAnimator animator = createHeightAnimator(target);
578        animator.setDuration(250);
579        animator.setInterpolator(mLinearOutSlowInInterpolator);
580        animator.addListener(new AnimatorListenerAdapter() {
581            private boolean mCancelled;
582
583            @Override
584            public void onAnimationCancel(Animator animation) {
585                mCancelled = true;
586            }
587
588            @Override
589            public void onAnimationEnd(Animator animation) {
590                if (mCancelled) {
591                    mHeightAnimator = null;
592                    onAnimationFinished.run();
593                } else {
594                    startUnlockHintAnimationPhase2(onAnimationFinished);
595                }
596            }
597        });
598        animator.start();
599        mHeightAnimator = animator;
600    }
601
602    /**
603     * Phase 2: Bounce down.
604     */
605    private void startUnlockHintAnimationPhase2(final Runnable onAnimationFinished) {
606        ValueAnimator animator = createHeightAnimator(getMaxPanelHeight());
607        animator.setDuration(450);
608        animator.setInterpolator(mBounceInterpolator);
609        animator.addListener(new AnimatorListenerAdapter() {
610            @Override
611            public void onAnimationEnd(Animator animation) {
612                mHeightAnimator = null;
613                onAnimationFinished.run();
614            }
615        });
616        animator.start();
617        mHeightAnimator = animator;
618    }
619
620    private ValueAnimator createHeightAnimator(float targetHeight) {
621        ValueAnimator animator = ValueAnimator.ofFloat(mExpandedHeight, targetHeight);
622        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
623            @Override
624            public void onAnimationUpdate(ValueAnimator animation) {
625                setExpandedHeight((Float) animation.getAnimatedValue());
626            }
627        });
628        return animator;
629    }
630
631    /**
632     * Gets called when the user performs a click anywhere in the empty area of the panel.
633     *
634     * @return whether the panel will be expanded after the action performed by this method
635     */
636    private boolean onEmptySpaceClick(float x) {
637        if (mHintAnimationRunning) {
638            return true;
639        }
640        if (x < mEdgeTapAreaWidth) {
641            onEdgeClicked(false /* right */);
642            return true;
643        } else if (x > getWidth() - mEdgeTapAreaWidth) {
644            onEdgeClicked(true /* right */);
645            return true;
646        } else {
647            return onMiddleClicked();
648        }
649    }
650
651    private boolean onMiddleClicked() {
652        switch (mStatusBar.getBarState()) {
653            case StatusBarState.KEYGUARD:
654                startUnlockHintAnimation();
655                return true;
656            case StatusBarState.SHADE_LOCKED:
657                // TODO: Go to Keyguard again.
658                return true;
659            case StatusBarState.SHADE:
660                collapse();
661                return false;
662            default:
663                return true;
664        }
665    }
666
667    protected abstract void onEdgeClicked(boolean right);
668
669    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
670        pw.println(String.format("[PanelView(%s): expandedHeight=%f maxPanelHeight=%d closing=%s"
671                + " tracking=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s"
672                + "]",
673                this.getClass().getSimpleName(),
674                getExpandedHeight(),
675                getMaxPanelHeight(),
676                mClosing?"T":"f",
677                mTracking?"T":"f",
678                mJustPeeked?"T":"f",
679                mPeekAnimator, ((mPeekAnimator!=null && mPeekAnimator.isStarted())?" (started)":""),
680                mHeightAnimator, ((mHeightAnimator !=null && mHeightAnimator.isStarted())?" (started)":"")
681        ));
682    }
683
684    public abstract void resetViews();
685}
686