PanelView.java revision 787a0af8ebba004a6f1cd3bfe8c78d851003d227
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    protected 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 = (mHeightAnimator != null && !mHintAnimationRunning);
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                        || event.getActionMasked() == MotionEvent.ACTION_CANCEL) {
224                    float vel = getCurrentVelocity();
225                    boolean expand = flingExpands(vel);
226                    onTrackingStopped(expand);
227                    fling(vel, expand);
228                } else {
229                    boolean expands = onEmptySpaceClick(mInitialTouchX);
230                    onTrackingStopped(expands);
231                }
232                if (mVelocityTracker != null) {
233                    mVelocityTracker.recycle();
234                    mVelocityTracker = null;
235                }
236                break;
237        }
238        return !waitForTouchSlop || mTracking;
239    }
240
241    protected abstract boolean hasConflictingGestures();
242
243    protected void onTrackingStopped(boolean expand) {
244        mTracking = false;
245        mBar.onTrackingStopped(PanelView.this, expand);
246    }
247
248    protected void onTrackingStarted() {
249        mTracking = true;
250        mBar.onTrackingStarted(PanelView.this);
251        onExpandingStarted();
252    }
253
254    private float getCurrentVelocity() {
255
256        // the velocitytracker might be null if we got a bad input stream
257        if (mVelocityTracker == null) {
258            return 0;
259        }
260        mVelocityTracker.computeCurrentVelocity(1000);
261        return mVelocityTracker.getYVelocity();
262    }
263
264    @Override
265    public boolean onInterceptTouchEvent(MotionEvent event) {
266
267        /*
268         * If the user drags anywhere inside the panel we intercept it if he moves his finger
269         * upwards. This allows closing the shade from anywhere inside the panel.
270         *
271         * We only do this if the current content is scrolled to the bottom,
272         * i.e isScrolledToBottom() is true and therefore there is no conflicting scrolling gesture
273         * possible.
274         */
275        int pointerIndex = event.findPointerIndex(mTrackingPointer);
276        if (pointerIndex < 0) {
277            pointerIndex = 0;
278            mTrackingPointer = event.getPointerId(pointerIndex);
279        }
280        final float x = event.getX(pointerIndex);
281        final float y = event.getY(pointerIndex);
282        boolean scrolledToBottom = isScrolledToBottom();
283
284        switch (event.getActionMasked()) {
285            case MotionEvent.ACTION_DOWN:
286                if (mHeightAnimator != null && !mHintAnimationRunning) {
287                    mHeightAnimator.cancel(); // end any outstanding animations
288                    mTouchSlopExceeded = true;
289                    return true;
290                }
291                mInitialTouchY = y;
292                mInitialTouchX = x;
293                mTouchSlopExceeded = false;
294                initVelocityTracker();
295                trackMovement(event);
296                break;
297            case MotionEvent.ACTION_POINTER_UP:
298                final int upPointer = event.getPointerId(event.getActionIndex());
299                if (mTrackingPointer == upPointer) {
300                    // gesture is ongoing, find a new pointer to track
301                    final int newIndex = event.getPointerId(0) != upPointer ? 0 : 1;
302                    mTrackingPointer = event.getPointerId(newIndex);
303                    mInitialTouchX = event.getX(newIndex);
304                    mInitialTouchY = event.getY(newIndex);
305                }
306                break;
307
308            case MotionEvent.ACTION_MOVE:
309                final float h = y - mInitialTouchY;
310                trackMovement(event);
311                if (scrolledToBottom) {
312                    if (h < -mTouchSlop && h < -Math.abs(x - mInitialTouchX)) {
313                        if (mHeightAnimator != null) {
314                            mHeightAnimator.cancel();
315                        }
316                        mInitialOffsetOnTouch = mExpandedHeight;
317                        mInitialTouchY = y;
318                        mInitialTouchX = x;
319                        mTracking = true;
320                        mTouchSlopExceeded = true;
321                        onTrackingStarted();
322                        return true;
323                    }
324                }
325                break;
326        }
327        return false;
328    }
329
330    private void initVelocityTracker() {
331        if (mVelocityTracker != null) {
332            mVelocityTracker.recycle();
333        }
334        mVelocityTracker = VelocityTrackerFactory.obtain(getContext());
335    }
336
337    protected boolean isScrolledToBottom() {
338        return true;
339    }
340
341    protected float getContentHeight() {
342        return mExpandedHeight;
343    }
344
345    @Override
346    protected void onFinishInflate() {
347        super.onFinishInflate();
348        loadDimens();
349    }
350
351    @Override
352    protected void onConfigurationChanged(Configuration newConfig) {
353        super.onConfigurationChanged(newConfig);
354        loadDimens();
355        mMaxPanelHeight = -1;
356    }
357
358    /**
359     * @param vel the current velocity of the motion
360     * @return whether a fling should expands the panel; contracts otherwise
361     */
362    private boolean flingExpands(float vel) {
363        if (Math.abs(vel) < mFlingAnimationUtils.getMinVelocityPxPerSecond()) {
364            return getExpandedFraction() > 0.5f;
365        } else {
366            return vel > 0;
367        }
368    }
369
370    protected void fling(float vel, boolean expand) {
371        cancelPeek();
372        float target = expand ? getMaxPanelHeight() : 0.0f;
373        if (target == mExpandedHeight || mOverExpansion > 0) {
374            onExpandingFinished();
375            mExpandedHeight = target;
376            mOverExpansion = 0.0f;
377            mBar.panelExpansionChanged(this, mExpandedFraction);
378            return;
379        }
380        ValueAnimator animator = createHeightAnimator(target);
381        if (expand) {
382            mFlingAnimationUtils.apply(animator, mExpandedHeight, target, vel, getHeight());
383        } else {
384            mFlingAnimationUtils.applyDismissing(animator, mExpandedHeight, target, vel,
385                    getHeight());
386
387            // Make it shorter if we run a canned animation
388            if (vel == 0) {
389                animator.setDuration((long) (animator.getDuration() / 1.75f));
390            }
391        }
392        animator.addListener(new AnimatorListenerAdapter() {
393            @Override
394            public void onAnimationEnd(Animator animation) {
395                mHeightAnimator = null;
396                onExpandingFinished();
397            }
398        });
399        animator.start();
400        mHeightAnimator = animator;
401    }
402
403    @Override
404    protected void onAttachedToWindow() {
405        super.onAttachedToWindow();
406        mViewName = getResources().getResourceName(getId());
407    }
408
409    public String getName() {
410        return mViewName;
411    }
412
413    @Override
414    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
415        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
416
417        if (DEBUG) logf("onMeasure(%d, %d) -> (%d, %d)",
418                widthMeasureSpec, heightMeasureSpec, getMeasuredWidth(), getMeasuredHeight());
419
420        // Did one of our children change size?
421        int newHeight = getMeasuredHeight();
422        if (newHeight > mMaxPanelHeight) {
423            // we only adapt the max height if it's bigger
424            mMaxPanelHeight = newHeight;
425            // If the user isn't actively poking us, let's rubberband to the content
426            if (!mTracking && mHeightAnimator == null
427                    && mExpandedHeight > 0 && mExpandedHeight != mMaxPanelHeight
428                    && mMaxPanelHeight > 0) {
429                mExpandedHeight = mMaxPanelHeight;
430            }
431        }
432    }
433
434    public void setExpandedHeight(float height) {
435        if (DEBUG) logf("setExpandedHeight(%.1f)", height);
436        setExpandedHeightInternal(height);
437        mBar.panelExpansionChanged(PanelView.this, mExpandedFraction);
438    }
439
440    @Override
441    protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
442        if (DEBUG) logf("onLayout: changed=%s, bottom=%d eh=%d fh=%d", changed?"T":"f", bottom,
443                (int)mExpandedHeight, mMaxPanelHeight);
444        super.onLayout(changed, left, top, right, bottom);
445        requestPanelHeightUpdate();
446    }
447
448    protected void requestPanelHeightUpdate() {
449        float currentMaxPanelHeight = getMaxPanelHeight();
450
451        // If the user isn't actively poking us, let's update the height
452        if (!mTracking && mHeightAnimator == null
453                && mExpandedHeight > 0 && currentMaxPanelHeight != mExpandedHeight) {
454            setExpandedHeightInternal(currentMaxPanelHeight);
455        }
456    }
457
458    public void setExpandedHeightInternal(float h) {
459        float fh = getMaxPanelHeight();
460        mExpandedHeight = Math.max(0, Math.min(fh, h));
461        float overExpansion = h - fh;
462        overExpansion = Math.max(0, overExpansion);
463        if (overExpansion != mOverExpansion) {
464            onOverExpansionChanged(overExpansion);
465            mOverExpansion = overExpansion;
466        }
467
468        if (DEBUG) {
469            logf("setExpansion: height=%.1f fh=%.1f tracking=%s", h, fh, mTracking ? "T" : "f");
470        }
471
472        onHeightUpdated(mExpandedHeight);
473        mExpandedFraction = Math.min(1f, (fh == 0) ? 0 : mExpandedHeight / fh);
474    }
475
476    protected abstract void onOverExpansionChanged(float overExpansion);
477
478    protected abstract void onHeightUpdated(float expandedHeight);
479
480    /**
481     * This returns the maximum height of the panel. Children should override this if their
482     * desired height is not the full height.
483     *
484     * @return the default implementation simply returns the maximum height.
485     */
486    protected int getMaxPanelHeight() {
487        mMaxPanelHeight = Math.max(mMaxPanelHeight, getHeight());
488        return mMaxPanelHeight;
489    }
490
491    public void setExpandedFraction(float frac) {
492        setExpandedHeight(getMaxPanelHeight() * frac);
493    }
494
495    public float getExpandedHeight() {
496        return mExpandedHeight;
497    }
498
499    public float getExpandedFraction() {
500        return mExpandedFraction;
501    }
502
503    public boolean isFullyExpanded() {
504        return mExpandedHeight >= getMaxPanelHeight();
505    }
506
507    public boolean isFullyCollapsed() {
508        return mExpandedHeight <= 0;
509    }
510
511    public boolean isCollapsing() {
512        return mClosing;
513    }
514
515    public boolean isTracking() {
516        return mTracking;
517    }
518
519    public void setBar(PanelBar panelBar) {
520        mBar = panelBar;
521    }
522
523    public void collapse() {
524        // TODO: abort animation or ongoing touch
525        if (DEBUG) logf("collapse: " + this);
526        if (!isFullyCollapsed()) {
527            if (mHeightAnimator != null) {
528                mHeightAnimator.cancel();
529            }
530            mClosing = true;
531            onExpandingStarted();
532            fling(0, false /* expand */);
533        }
534    }
535
536    public void expand() {
537        if (DEBUG) logf("expand: " + this);
538        if (isFullyCollapsed()) {
539            mBar.startOpeningPanel(this);
540            onExpandingStarted();
541            fling(0, true /* expand */);
542        } else if (DEBUG) {
543            if (DEBUG) logf("skipping expansion: is expanded");
544        }
545    }
546
547    public void cancelPeek() {
548        if (mPeekAnimator != null && mPeekAnimator.isStarted()) {
549            mPeekAnimator.cancel();
550        }
551    }
552
553    protected void startUnlockHintAnimation() {
554
555        // We don't need to hint the user if an animation is already running or the user is changing
556        // the expansion.
557        if (mHeightAnimator != null || mTracking) {
558            return;
559        }
560        cancelPeek();
561        onExpandingStarted();
562        startUnlockHintAnimationPhase1(new Runnable() {
563            @Override
564            public void run() {
565                onExpandingFinished();
566                mStatusBar.onHintFinished();
567                mHintAnimationRunning = false;
568            }
569        });
570        mStatusBar.onUnlockHintStarted();
571        mHintAnimationRunning = true;
572    }
573
574    /**
575     * Phase 1: Move everything upwards.
576     */
577    private void startUnlockHintAnimationPhase1(final Runnable onAnimationFinished) {
578        float target = Math.max(0, getMaxPanelHeight() - mHintDistance);
579        ValueAnimator animator = createHeightAnimator(target);
580        animator.setDuration(250);
581        animator.setInterpolator(mLinearOutSlowInInterpolator);
582        animator.addListener(new AnimatorListenerAdapter() {
583            private boolean mCancelled;
584
585            @Override
586            public void onAnimationCancel(Animator animation) {
587                mCancelled = true;
588            }
589
590            @Override
591            public void onAnimationEnd(Animator animation) {
592                if (mCancelled) {
593                    mHeightAnimator = null;
594                    onAnimationFinished.run();
595                } else {
596                    startUnlockHintAnimationPhase2(onAnimationFinished);
597                }
598            }
599        });
600        animator.start();
601        mHeightAnimator = animator;
602    }
603
604    /**
605     * Phase 2: Bounce down.
606     */
607    private void startUnlockHintAnimationPhase2(final Runnable onAnimationFinished) {
608        ValueAnimator animator = createHeightAnimator(getMaxPanelHeight());
609        animator.setDuration(450);
610        animator.setInterpolator(mBounceInterpolator);
611        animator.addListener(new AnimatorListenerAdapter() {
612            @Override
613            public void onAnimationEnd(Animator animation) {
614                mHeightAnimator = null;
615                onAnimationFinished.run();
616            }
617        });
618        animator.start();
619        mHeightAnimator = animator;
620    }
621
622    private ValueAnimator createHeightAnimator(float targetHeight) {
623        ValueAnimator animator = ValueAnimator.ofFloat(mExpandedHeight, targetHeight);
624        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
625            @Override
626            public void onAnimationUpdate(ValueAnimator animation) {
627                setExpandedHeight((Float) animation.getAnimatedValue());
628            }
629        });
630        return animator;
631    }
632
633    /**
634     * Gets called when the user performs a click anywhere in the empty area of the panel.
635     *
636     * @return whether the panel will be expanded after the action performed by this method
637     */
638    private boolean onEmptySpaceClick(float x) {
639        if (mHintAnimationRunning) {
640            return true;
641        }
642        if (x < mEdgeTapAreaWidth
643                && mStatusBar.getBarState() == StatusBarState.KEYGUARD) {
644            onEdgeClicked(false /* right */);
645            return true;
646        } else if (x > getWidth() - mEdgeTapAreaWidth
647                && mStatusBar.getBarState() == StatusBarState.KEYGUARD) {
648            onEdgeClicked(true /* right */);
649            return true;
650        } else {
651            return onMiddleClicked();
652        }
653    }
654
655    private boolean onMiddleClicked() {
656        switch (mStatusBar.getBarState()) {
657            case StatusBarState.KEYGUARD:
658                startUnlockHintAnimation();
659                return true;
660            case StatusBarState.SHADE_LOCKED:
661                mStatusBar.goToKeyguard();
662                return true;
663            case StatusBarState.SHADE:
664                collapse();
665                return false;
666            default:
667                return true;
668        }
669    }
670
671    protected abstract void onEdgeClicked(boolean right);
672
673    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
674        pw.println(String.format("[PanelView(%s): expandedHeight=%f maxPanelHeight=%d closing=%s"
675                + " tracking=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s"
676                + "]",
677                this.getClass().getSimpleName(),
678                getExpandedHeight(),
679                getMaxPanelHeight(),
680                mClosing?"T":"f",
681                mTracking?"T":"f",
682                mJustPeeked?"T":"f",
683                mPeekAnimator, ((mPeekAnimator!=null && mPeekAnimator.isStarted())?" (started)":""),
684                mHeightAnimator, ((mHeightAnimator !=null && mHeightAnimator.isStarted())?" (started)":"")
685        ));
686    }
687
688    public abstract void resetViews();
689}
690