PanelView.java revision 1408eb5a58d669933c701e347fd3498ceab70f3c
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 = 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 || mOverExpansion > 0) {
373            onExpandingFinished();
374            mExpandedHeight = target;
375            mOverExpansion = 0.0f;
376            mBar.panelExpansionChanged(this, mExpandedFraction);
377            return;
378        }
379        ValueAnimator animator = createHeightAnimator(target);
380        if (expand) {
381            mFlingAnimationUtils.apply(animator, mExpandedHeight, target, vel, getHeight());
382        } else {
383            mFlingAnimationUtils.applyDismissing(animator, mExpandedHeight, target, vel,
384                    getHeight());
385
386            // Make it shorter if we run a canned animation
387            if (vel == 0) {
388                animator.setDuration((long) (animator.getDuration() / 1.75f));
389            }
390        }
391        animator.addListener(new AnimatorListenerAdapter() {
392            @Override
393            public void onAnimationEnd(Animator animation) {
394                mHeightAnimator = null;
395                onExpandingFinished();
396            }
397        });
398        animator.start();
399        mHeightAnimator = animator;
400    }
401
402    @Override
403    protected void onAttachedToWindow() {
404        super.onAttachedToWindow();
405        mViewName = getResources().getResourceName(getId());
406    }
407
408    public String getName() {
409        return mViewName;
410    }
411
412    @Override
413    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
414        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
415
416        if (DEBUG) logf("onMeasure(%d, %d) -> (%d, %d)",
417                widthMeasureSpec, heightMeasureSpec, getMeasuredWidth(), getMeasuredHeight());
418
419        // Did one of our children change size?
420        int newHeight = getMeasuredHeight();
421        if (newHeight > mMaxPanelHeight) {
422            // we only adapt the max height if it's bigger
423            mMaxPanelHeight = newHeight;
424            // If the user isn't actively poking us, let's rubberband to the content
425            if (!mTracking && mHeightAnimator == null
426                    && mExpandedHeight > 0 && mExpandedHeight != mMaxPanelHeight
427                    && mMaxPanelHeight > 0) {
428                mExpandedHeight = mMaxPanelHeight;
429            }
430        }
431    }
432
433    public void setExpandedHeight(float height) {
434        if (DEBUG) logf("setExpandedHeight(%.1f)", height);
435        setExpandedHeightInternal(height);
436        mBar.panelExpansionChanged(PanelView.this, mExpandedFraction);
437    }
438
439    @Override
440    protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
441        if (DEBUG) logf("onLayout: changed=%s, bottom=%d eh=%d fh=%d", changed?"T":"f", bottom,
442                (int)mExpandedHeight, mMaxPanelHeight);
443        super.onLayout(changed, left, top, right, bottom);
444        requestPanelHeightUpdate();
445    }
446
447    protected void requestPanelHeightUpdate() {
448        float currentMaxPanelHeight = getMaxPanelHeight();
449
450        // If the user isn't actively poking us, let's update the height
451        if (!mTracking && mHeightAnimator == null
452                && mExpandedHeight > 0 && currentMaxPanelHeight != mExpandedHeight) {
453            setExpandedHeightInternal(currentMaxPanelHeight);
454        }
455    }
456
457    public void setExpandedHeightInternal(float h) {
458        float fh = getMaxPanelHeight();
459        mExpandedHeight = Math.max(0, Math.min(fh, h));
460        float overExpansion = h - fh;
461        overExpansion = Math.max(0, overExpansion);
462        if (overExpansion != mOverExpansion) {
463            onOverExpansionChanged(overExpansion);
464            mOverExpansion = overExpansion;
465        }
466
467        if (DEBUG) {
468            logf("setExpansion: height=%.1f fh=%.1f tracking=%s", h, fh, mTracking ? "T" : "f");
469        }
470
471        onHeightUpdated(mExpandedHeight);
472        mExpandedFraction = Math.min(1f, (fh == 0) ? 0 : mExpandedHeight / fh);
473    }
474
475    protected abstract void onOverExpansionChanged(float overExpansion);
476
477    protected abstract void onHeightUpdated(float expandedHeight);
478
479    /**
480     * This returns the maximum height of the panel. Children should override this if their
481     * desired height is not the full height.
482     *
483     * @return the default implementation simply returns the maximum height.
484     */
485    protected int getMaxPanelHeight() {
486        mMaxPanelHeight = Math.max(mMaxPanelHeight, getHeight());
487        return mMaxPanelHeight;
488    }
489
490    public void setExpandedFraction(float frac) {
491        setExpandedHeight(getMaxPanelHeight() * frac);
492    }
493
494    public float getExpandedHeight() {
495        return mExpandedHeight;
496    }
497
498    public float getExpandedFraction() {
499        return mExpandedFraction;
500    }
501
502    public boolean isFullyExpanded() {
503        return mExpandedHeight >= getMaxPanelHeight();
504    }
505
506    public boolean isFullyCollapsed() {
507        return mExpandedHeight <= 0;
508    }
509
510    public boolean isCollapsing() {
511        return mClosing;
512    }
513
514    public boolean isTracking() {
515        return mTracking;
516    }
517
518    public void setBar(PanelBar panelBar) {
519        mBar = panelBar;
520    }
521
522    public void collapse() {
523        // TODO: abort animation or ongoing touch
524        if (DEBUG) logf("collapse: " + this);
525        if (!isFullyCollapsed()) {
526            if (mHeightAnimator != null) {
527                mHeightAnimator.cancel();
528            }
529            mClosing = true;
530            onExpandingStarted();
531            fling(0, false /* expand */);
532        }
533    }
534
535    public void expand() {
536        if (DEBUG) logf("expand: " + this);
537        if (isFullyCollapsed()) {
538            mBar.startOpeningPanel(this);
539            onExpandingStarted();
540            fling(0, true /* expand */);
541        } else if (DEBUG) {
542            if (DEBUG) logf("skipping expansion: is expanded");
543        }
544    }
545
546    public void cancelPeek() {
547        if (mPeekAnimator != null && mPeekAnimator.isStarted()) {
548            mPeekAnimator.cancel();
549        }
550    }
551
552    protected void startUnlockHintAnimation() {
553
554        // We don't need to hint the user if an animation is already running or the user is changing
555        // the expansion.
556        if (mHeightAnimator != null || mTracking) {
557            return;
558        }
559        cancelPeek();
560        onExpandingStarted();
561        startUnlockHintAnimationPhase1(new Runnable() {
562            @Override
563            public void run() {
564                onExpandingFinished();
565                mStatusBar.onHintFinished();
566                mHintAnimationRunning = false;
567            }
568        });
569        mStatusBar.onUnlockHintStarted();
570        mHintAnimationRunning = true;
571    }
572
573    /**
574     * Phase 1: Move everything upwards.
575     */
576    private void startUnlockHintAnimationPhase1(final Runnable onAnimationFinished) {
577        float target = Math.max(0, getMaxPanelHeight() - mHintDistance);
578        ValueAnimator animator = createHeightAnimator(target);
579        animator.setDuration(250);
580        animator.setInterpolator(mLinearOutSlowInInterpolator);
581        animator.addListener(new AnimatorListenerAdapter() {
582            private boolean mCancelled;
583
584            @Override
585            public void onAnimationCancel(Animator animation) {
586                mCancelled = true;
587            }
588
589            @Override
590            public void onAnimationEnd(Animator animation) {
591                if (mCancelled) {
592                    mHeightAnimator = null;
593                    onAnimationFinished.run();
594                } else {
595                    startUnlockHintAnimationPhase2(onAnimationFinished);
596                }
597            }
598        });
599        animator.start();
600        mHeightAnimator = animator;
601    }
602
603    /**
604     * Phase 2: Bounce down.
605     */
606    private void startUnlockHintAnimationPhase2(final Runnable onAnimationFinished) {
607        ValueAnimator animator = createHeightAnimator(getMaxPanelHeight());
608        animator.setDuration(450);
609        animator.setInterpolator(mBounceInterpolator);
610        animator.addListener(new AnimatorListenerAdapter() {
611            @Override
612            public void onAnimationEnd(Animator animation) {
613                mHeightAnimator = null;
614                onAnimationFinished.run();
615            }
616        });
617        animator.start();
618        mHeightAnimator = animator;
619    }
620
621    private ValueAnimator createHeightAnimator(float targetHeight) {
622        ValueAnimator animator = ValueAnimator.ofFloat(mExpandedHeight, targetHeight);
623        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
624            @Override
625            public void onAnimationUpdate(ValueAnimator animation) {
626                setExpandedHeight((Float) animation.getAnimatedValue());
627            }
628        });
629        return animator;
630    }
631
632    /**
633     * Gets called when the user performs a click anywhere in the empty area of the panel.
634     *
635     * @return whether the panel will be expanded after the action performed by this method
636     */
637    private boolean onEmptySpaceClick(float x) {
638        if (mHintAnimationRunning) {
639            return true;
640        }
641        if (x < mEdgeTapAreaWidth) {
642            onEdgeClicked(false /* right */);
643            return true;
644        } else if (x > getWidth() - mEdgeTapAreaWidth) {
645            onEdgeClicked(true /* right */);
646            return true;
647        } else {
648            return onMiddleClicked();
649        }
650    }
651
652    private boolean onMiddleClicked() {
653        switch (mStatusBar.getBarState()) {
654            case StatusBarState.KEYGUARD:
655                startUnlockHintAnimation();
656                return true;
657            case StatusBarState.SHADE_LOCKED:
658                // TODO: Go to Keyguard again.
659                return true;
660            case StatusBarState.SHADE:
661                collapse();
662                return false;
663            default:
664                return true;
665        }
666    }
667
668    protected abstract void onEdgeClicked(boolean right);
669
670    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
671        pw.println(String.format("[PanelView(%s): expandedHeight=%f maxPanelHeight=%d closing=%s"
672                + " tracking=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s"
673                + "]",
674                this.getClass().getSimpleName(),
675                getExpandedHeight(),
676                getMaxPanelHeight(),
677                mClosing?"T":"f",
678                mTracking?"T":"f",
679                mJustPeeked?"T":"f",
680                mPeekAnimator, ((mPeekAnimator!=null && mPeekAnimator.isStarted())?" (started)":""),
681                mHeightAnimator, ((mHeightAnimator !=null && mHeightAnimator.isStarted())?" (started)":"")
682        ));
683    }
684
685    public abstract void resetViews();
686}
687