TaskStackView.java revision f7bca430d9356c26d6df222d2c90bc7668262f6b
1/*
2 * Copyright (C) 2014 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.recents.views;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.ValueAnimator;
24import android.app.Activity;
25import android.content.Context;
26import android.graphics.Canvas;
27import android.graphics.Rect;
28import android.graphics.Region;
29import android.util.Pair;
30import android.view.LayoutInflater;
31import android.view.MotionEvent;
32import android.view.VelocityTracker;
33import android.view.View;
34import android.view.ViewConfiguration;
35import android.view.ViewParent;
36import android.widget.FrameLayout;
37import android.widget.OverScroller;
38import com.android.systemui.R;
39import com.android.systemui.recents.BakedBezierInterpolator;
40import com.android.systemui.recents.Console;
41import com.android.systemui.recents.Constants;
42import com.android.systemui.recents.RecentsConfiguration;
43import com.android.systemui.recents.RecentsTaskLoader;
44import com.android.systemui.recents.Utilities;
45import com.android.systemui.recents.model.Task;
46import com.android.systemui.recents.model.TaskStack;
47
48import java.util.ArrayList;
49import java.util.HashMap;
50
51
52/* The visual representation of a task stack view */
53public class TaskStackView extends FrameLayout implements TaskStack.TaskStackCallbacks,
54        TaskView.TaskViewCallbacks, ViewPool.ViewPoolConsumer<TaskView, Task>,
55        View.OnClickListener, View.OnLongClickListener {
56
57    /** The TaskView callbacks */
58    interface TaskStackViewCallbacks {
59        public void onTaskLaunched(TaskStackView stackView, TaskView tv, TaskStack stack, Task t);
60        public void onTaskAppInfoLaunched(Task t);
61    }
62
63    TaskStack mStack;
64    TaskStackViewTouchHandler mTouchHandler;
65    TaskStackViewCallbacks mCb;
66    ViewPool<TaskView, Task> mViewPool;
67
68    // The various rects that define the stack view
69    Rect mRect = new Rect();
70    Rect mStackRect = new Rect();
71    Rect mStackRectSansPeek = new Rect();
72    Rect mTaskRect = new Rect();
73
74    // The virtual stack scroll that we use for the card layout
75    int mStackScroll;
76    int mMinScroll;
77    int mMaxScroll;
78    int mStashedScroll;
79    int mLastInfoPaneStackScroll;
80    OverScroller mScroller;
81    ObjectAnimator mScrollAnimator;
82
83    // Optimizations
84    int mHwLayersRefCount;
85    int mStackViewsAnimationDuration;
86    boolean mStackViewsDirty = true;
87    boolean mAwaitingFirstLayout = true;
88    int[] mTmpVisibleRange = new int[2];
89    Rect mTmpRect = new Rect();
90    Rect mTmpRect2 = new Rect();
91    LayoutInflater mInflater;
92
93    public TaskStackView(Context context, TaskStack stack) {
94        super(context);
95        mStack = stack;
96        mStack.setCallbacks(this);
97        mScroller = new OverScroller(context);
98        mTouchHandler = new TaskStackViewTouchHandler(context, this);
99        mViewPool = new ViewPool<TaskView, Task>(context, this);
100        mInflater = LayoutInflater.from(context);
101    }
102
103    /** Sets the callbacks */
104    void setCallbacks(TaskStackViewCallbacks cb) {
105        mCb = cb;
106    }
107
108    /** Requests that the views be synchronized with the model */
109    void requestSynchronizeStackViewsWithModel() {
110        requestSynchronizeStackViewsWithModel(0);
111    }
112    void requestSynchronizeStackViewsWithModel(int duration) {
113        Console.log(Constants.DebugFlags.TaskStack.SynchronizeViewsWithModel,
114                "[TaskStackView|requestSynchronize]", "" + duration + "ms", Console.AnsiYellow);
115        if (!mStackViewsDirty) {
116            invalidate();
117        }
118        if (mAwaitingFirstLayout) {
119            // Skip the animation if we are awaiting first layout
120            mStackViewsAnimationDuration = 0;
121        } else {
122            mStackViewsAnimationDuration = Math.max(mStackViewsAnimationDuration, duration);
123        }
124        mStackViewsDirty = true;
125    }
126
127    // XXX: Optimization: Use a mapping of Task -> View
128    private TaskView getChildViewForTask(Task t) {
129        int childCount = getChildCount();
130        for (int i = 0; i < childCount; i++) {
131            TaskView tv = (TaskView) getChildAt(i);
132            if (tv.getTask() == t) {
133                return tv;
134            }
135        }
136        return null;
137    }
138
139    /** Update/get the transform */
140    public TaskViewTransform getStackTransform(int indexInStack, int stackScroll) {
141        TaskViewTransform transform = new TaskViewTransform();
142
143        // Return early if we have an invalid index
144        if (indexInStack < 0) return transform;
145
146        // Map the items to an continuous position relative to the specified scroll
147        int numPeekCards = Constants.Values.TaskStackView.StackPeekNumCards;
148        float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height();
149        float peekHeight = Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height();
150        float t = ((indexInStack * overlapHeight) - stackScroll) / overlapHeight;
151        float boundedT = Math.max(t, -(numPeekCards + 1));
152
153        // Set the scale relative to its position
154        float minScale = Constants.Values.TaskStackView.StackPeekMinScale;
155        float scaleRange = 1f - minScale;
156        float scaleInc = scaleRange / numPeekCards;
157        float scale = Math.max(minScale, Math.min(1f, 1f + (boundedT * scaleInc)));
158        float scaleYOffset = ((1f - scale) * mTaskRect.height()) / 2;
159        transform.scale = scale;
160
161        // Set the translation
162        if (boundedT < 0f) {
163            transform.translationY = (int) ((Math.max(-numPeekCards, boundedT) /
164                    numPeekCards) * peekHeight - scaleYOffset);
165        } else {
166            transform.translationY = (int) (boundedT * overlapHeight - scaleYOffset);
167        }
168
169        // Update the rect and visibility
170        transform.rect.set(mTaskRect);
171        if (t < -(numPeekCards + 1)) {
172            transform.visible = false;
173        } else {
174            transform.rect.offset(0, transform.translationY);
175            Utilities.scaleRectAboutCenter(transform.rect, transform.scale);
176            transform.visible = Rect.intersects(mRect, transform.rect);
177        }
178        transform.t = t;
179        return transform;
180    }
181
182    /**
183     * Gets the stack transforms of a list of tasks, and returns the visible range of tasks.
184     */
185    private ArrayList<TaskViewTransform> getStackTransforms(ArrayList<Task> tasks,
186                                                            int stackScroll,
187                                                            int[] visibleRangeOut,
188                                                            boolean boundTranslationsToRect) {
189        // XXX: Optimization: Use binary search to find the visible range
190
191        ArrayList<TaskViewTransform> taskTransforms = new ArrayList<TaskViewTransform>();
192        int taskCount = tasks.size();
193        int firstVisibleIndex = -1;
194        int lastVisibleIndex = -1;
195        for (int i = 0; i < taskCount; i++) {
196            TaskViewTransform transform = getStackTransform(i, stackScroll);
197            taskTransforms.add(transform);
198            if (transform.visible) {
199                if (firstVisibleIndex < 0) {
200                    firstVisibleIndex = i;
201                }
202                lastVisibleIndex = i;
203            }
204
205            if (boundTranslationsToRect) {
206                transform.translationY = Math.min(transform.translationY, mRect.bottom);
207            }
208        }
209        if (visibleRangeOut != null) {
210            visibleRangeOut[0] = firstVisibleIndex;
211            visibleRangeOut[1] = lastVisibleIndex;
212        }
213        return taskTransforms;
214    }
215
216    /** Synchronizes the views with the model */
217    void synchronizeStackViewsWithModel() {
218        Console.log(Constants.DebugFlags.TaskStack.SynchronizeViewsWithModel,
219                "[TaskStackView|synchronizeViewsWithModel]",
220                "mStackViewsDirty: " + mStackViewsDirty, Console.AnsiYellow);
221        if (mStackViewsDirty) {
222            // XXX: Consider using TaskViewTransform pool to prevent allocations
223            // XXX: Iterate children views, update transforms and remove all that are not visible
224            //      For all remaining tasks, update transforms and if visible add the view
225
226            // Get all the task transforms
227            int[] visibleRange = mTmpVisibleRange;
228            int stackScroll = getStackScroll();
229            ArrayList<Task> tasks = mStack.getTasks();
230            ArrayList<TaskViewTransform> taskTransforms = getStackTransforms(tasks, stackScroll,
231                    visibleRange, false);
232
233            // Update the visible state of all the tasks
234            int taskCount = tasks.size();
235            for (int i = 0; i < taskCount; i++) {
236                Task task = tasks.get(i);
237                TaskViewTransform transform = taskTransforms.get(i);
238                TaskView tv = getChildViewForTask(task);
239
240                if (transform.visible) {
241                    if (tv == null) {
242                        tv = mViewPool.pickUpViewFromPool(task, task);
243                        // When we are picking up a new view from the view pool, prepare it for any
244                        // following animation by putting it in a reasonable place
245                        if (mStackViewsAnimationDuration > 0 && i != 0) {
246                            int fromIndex = (transform.t < 0) ? (visibleRange[0] - 1) :
247                                    (visibleRange[1] + 1);
248                            tv.updateViewPropertiesToTaskTransform(null,
249                                    getStackTransform(fromIndex, stackScroll), 0);
250                        }
251                    }
252                } else {
253                    if (tv != null) {
254                        mViewPool.returnViewToPool(tv);
255                    }
256                }
257            }
258
259            // Update all the remaining view children
260            // NOTE: We have to iterate in reverse where because we are removing views directly
261            int childCount = getChildCount();
262            for (int i = childCount - 1; i >= 0; i--) {
263                TaskView tv = (TaskView) getChildAt(i);
264                Task task = tv.getTask();
265                int taskIndex = mStack.indexOfTask(task);
266                if (taskIndex < 0 || !taskTransforms.get(taskIndex).visible) {
267                    mViewPool.returnViewToPool(tv);
268                } else {
269                    tv.updateViewPropertiesToTaskTransform(null, taskTransforms.get(taskIndex),
270                            mStackViewsAnimationDuration);
271                }
272            }
273
274            Console.log(Constants.DebugFlags.TaskStack.SynchronizeViewsWithModel,
275                    "  [TaskStackView|viewChildren]", "" + getChildCount());
276
277            mStackViewsAnimationDuration = 0;
278            mStackViewsDirty = false;
279        }
280    }
281
282    /** Sets the current stack scroll */
283    public void setStackScroll(int value) {
284        mStackScroll = value;
285        requestSynchronizeStackViewsWithModel();
286
287        // Close any open info panes if the user has scrolled away from them
288        boolean isAnimatingScroll = (mScrollAnimator != null && mScrollAnimator.isRunning());
289        if (mLastInfoPaneStackScroll > -1 && !isAnimatingScroll) {
290            RecentsConfiguration config = RecentsConfiguration.getInstance();
291            if (Math.abs(mStackScroll - mLastInfoPaneStackScroll) >
292                    config.taskStackScrollDismissInfoPaneDistance) {
293                // Close any open info panes
294                closeOpenInfoPanes();
295            }
296        }
297    }
298    /** Sets the current stack scroll without synchronizing the stack view with the model */
299    public void setStackScrollRaw(int value) {
300        mStackScroll = value;
301    }
302
303    /** Gets the current stack scroll */
304    public int getStackScroll() {
305        return mStackScroll;
306    }
307
308    /** Animates the stack scroll into bounds */
309    ObjectAnimator animateBoundScroll() {
310        int curScroll = getStackScroll();
311        int newScroll = Math.max(mMinScroll, Math.min(mMaxScroll, curScroll));
312        if (newScroll != curScroll) {
313            // Enable hw layers on the stack
314            addHwLayersRefCount("animateBoundScroll");
315
316            // Start a new scroll animation
317            animateScroll(curScroll, newScroll, new Runnable() {
318                @Override
319                public void run() {
320                    // Disable hw layers on the stack
321                    decHwLayersRefCount("animateBoundScroll");
322                }
323            });
324        }
325        return mScrollAnimator;
326    }
327
328    /** Animates the stack scroll */
329    void animateScroll(int curScroll, int newScroll, final Runnable postRunnable) {
330        // Abort any current animations
331        abortScroller();
332        abortBoundScrollAnimation();
333
334        mScrollAnimator = ObjectAnimator.ofInt(this, "stackScroll", curScroll, newScroll);
335        mScrollAnimator.setDuration(Utilities.calculateTranslationAnimationDuration(newScroll -
336                curScroll, 250));
337        mScrollAnimator.setInterpolator(BakedBezierInterpolator.INSTANCE);
338        mScrollAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
339            @Override
340            public void onAnimationUpdate(ValueAnimator animation) {
341                setStackScroll((Integer) animation.getAnimatedValue());
342            }
343        });
344        mScrollAnimator.addListener(new AnimatorListenerAdapter() {
345            @Override
346            public void onAnimationEnd(Animator animation) {
347                if (postRunnable != null) {
348                    postRunnable.run();
349                }
350                mScrollAnimator.removeAllListeners();
351            }
352        });
353        mScrollAnimator.start();
354    }
355
356    /** Aborts any current stack scrolls */
357    void abortBoundScrollAnimation() {
358        if (mScrollAnimator != null) {
359            mScrollAnimator.cancel();
360        }
361    }
362
363    /** Aborts the scroller and any current fling */
364    void abortScroller() {
365        if (!mScroller.isFinished()) {
366            // Abort the scroller
367            mScroller.abortAnimation();
368            // And disable hw layers on the stack
369            decHwLayersRefCount("flingScroll");
370        }
371    }
372
373    /** Bounds the current scroll if necessary */
374    public boolean boundScroll() {
375        int curScroll = getStackScroll();
376        int newScroll = Math.max(mMinScroll, Math.min(mMaxScroll, curScroll));
377        if (newScroll != curScroll) {
378            setStackScroll(newScroll);
379            return true;
380        }
381        return false;
382    }
383
384    /**
385     * Bounds the current scroll if necessary, but does not synchronize the stack view with the
386     * model.
387     */
388    public boolean boundScrollRaw() {
389        int curScroll = getStackScroll();
390        int newScroll = Math.max(mMinScroll, Math.min(mMaxScroll, curScroll));
391        if (newScroll != curScroll) {
392            setStackScrollRaw(newScroll);
393            return true;
394        }
395        return false;
396    }
397
398    /** Returns whether the specified scroll is out of bounds */
399    boolean isScrollOutOfBounds(int scroll) {
400        return (scroll < mMinScroll) || (scroll > mMaxScroll);
401    }
402    boolean isScrollOutOfBounds() {
403        return isScrollOutOfBounds(getStackScroll());
404    }
405
406    /** Updates the min and max virtual scroll bounds */
407    void updateMinMaxScroll(boolean boundScrollToNewMinMax) {
408        // Compute the min and max scroll values
409        int numTasks = Math.max(1, mStack.getTaskCount());
410        int taskHeight = mTaskRect.height();
411        int stackHeight = mStackRectSansPeek.height();
412        int maxScrollHeight = taskHeight + (int) ((numTasks - 1) *
413                Constants.Values.TaskStackView.StackOverlapPct * taskHeight);
414
415        if (numTasks <= 1) {
416            // If there is only one task, then center the task in the stack rect (sans peek)
417            mMinScroll = mMaxScroll = -(stackHeight - taskHeight) / 2;
418        } else {
419            mMinScroll = Math.min(stackHeight, maxScrollHeight) - stackHeight;
420            mMaxScroll = maxScrollHeight - stackHeight;
421        }
422
423        // Debug logging
424        if (Constants.DebugFlags.UI.MeasureAndLayout) {
425            Console.log("  [TaskStack|minScroll] " + mMinScroll);
426            Console.log("  [TaskStack|maxScroll] " + mMaxScroll);
427        }
428
429        if (boundScrollToNewMinMax) {
430            boundScroll();
431        }
432    }
433
434    /** Closes any open info panes. */
435    boolean closeOpenInfoPanes() {
436        if (!Constants.DebugFlags.App.EnableInfoPane) return false;
437
438        int childCount = getChildCount();
439        for (int i = 0; i < childCount; i++) {
440            TaskView tv = (TaskView) getChildAt(i);
441            if (tv.isInfoPaneVisible()) {
442                tv.hideInfoPane();
443                return true;
444            }
445        }
446        return false;
447    }
448
449    /** Enables the hw layers and increments the hw layer requirement ref count */
450    void addHwLayersRefCount(String reason) {
451        Console.log(Constants.DebugFlags.UI.HwLayers,
452                "[TaskStackView|addHwLayersRefCount] refCount: " +
453                        mHwLayersRefCount + "->" + (mHwLayersRefCount + 1) + " " + reason);
454        if (mHwLayersRefCount == 0) {
455            // Enable hw layers on each of the children
456            int childCount = getChildCount();
457            for (int i = 0; i < childCount; i++) {
458                TaskView tv = (TaskView) getChildAt(i);
459                tv.enableHwLayers();
460            }
461        }
462        mHwLayersRefCount++;
463    }
464
465    /** Decrements the hw layer requirement ref count and disables the hw layers when we don't
466        need them anymore. */
467    void decHwLayersRefCount(String reason) {
468        Console.log(Constants.DebugFlags.UI.HwLayers,
469                "[TaskStackView|decHwLayersRefCount] refCount: " +
470                        mHwLayersRefCount + "->" + (mHwLayersRefCount - 1) + " " + reason);
471        mHwLayersRefCount--;
472        if (mHwLayersRefCount == 0) {
473            // Disable hw layers on each of the children
474            int childCount = getChildCount();
475            for (int i = 0; i < childCount; i++) {
476                TaskView tv = (TaskView) getChildAt(i);
477                tv.disableHwLayers();
478            }
479        } else if (mHwLayersRefCount < 0) {
480            new Throwable("Invalid hw layers ref count").printStackTrace();
481            Console.logError(getContext(), "Invalid HW layers ref count");
482        }
483    }
484
485    @Override
486    public void computeScroll() {
487        if (mScroller.computeScrollOffset()) {
488            setStackScroll(mScroller.getCurrY());
489            invalidate();
490
491            // If we just finished scrolling, then disable the hw layers
492            if (mScroller.isFinished()) {
493                decHwLayersRefCount("finishedFlingScroll");
494            }
495        }
496    }
497
498    @Override
499    public boolean onInterceptTouchEvent(MotionEvent ev) {
500        return mTouchHandler.onInterceptTouchEvent(ev);
501    }
502
503    @Override
504    public boolean onTouchEvent(MotionEvent ev) {
505        return mTouchHandler.onTouchEvent(ev);
506    }
507
508    @Override
509    public void dispatchDraw(Canvas canvas) {
510        Console.log(Constants.DebugFlags.UI.Draw, "[TaskStackView|dispatchDraw]", "",
511                Console.AnsiPurple);
512        synchronizeStackViewsWithModel();
513        super.dispatchDraw(canvas);
514    }
515
516    @Override
517    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
518        if (Constants.DebugFlags.App.EnableTaskStackClipping) {
519            TaskView tv = (TaskView) child;
520            TaskView nextTv = null;
521            int curIndex = indexOfChild(tv);
522            if ((curIndex > -1) && (curIndex < (getChildCount() - 1))) {
523                // Clip against the next view (if we aren't animating its alpha)
524                nextTv = (TaskView) getChildAt(curIndex + 1);
525                if (nextTv.getAlpha() == 1f) {
526                    Rect curRect = tv.getClippingRect(mTmpRect);
527                    Rect nextRect = nextTv.getClippingRect(mTmpRect2);
528                    RecentsConfiguration config = RecentsConfiguration.getInstance();
529                    // The hit rects are relative to the task view, which needs to be offset by the
530                    // system bar height
531                    curRect.offset(0, config.systemInsets.top);
532                    nextRect.offset(0, config.systemInsets.top);
533                    // Compute the clip region
534                    Region clipRegion = new Region();
535                    clipRegion.op(curRect, Region.Op.UNION);
536                    clipRegion.op(nextRect, Region.Op.DIFFERENCE);
537                    // Clip the canvas
538                    int saveCount = canvas.save(Canvas.CLIP_SAVE_FLAG);
539                    canvas.clipRegion(clipRegion);
540                    boolean invalidate = super.drawChild(canvas, child, drawingTime);
541                    canvas.restoreToCount(saveCount);
542                    return invalidate;
543                }
544            }
545        }
546        return super.drawChild(canvas, child, drawingTime);
547    }
548
549    /** Computes the stack and task rects */
550    public void computeRects(int width, int height, int insetLeft, int insetBottom) {
551        // Note: We let the stack view be the full height because we want the cards to go under the
552        //       navigation bar if possible.  However, the stack rects which we use to calculate
553        //       max scroll, etc. need to take the nav bar into account
554
555        // Compute the stack rects
556        mRect.set(0, 0, width, height);
557        mStackRect.set(mRect);
558        mStackRect.left += insetLeft;
559        mStackRect.bottom -= insetBottom;
560
561        int smallestDimension = Math.min(width, height);
562        int padding = (int) (Constants.Values.TaskStackView.StackPaddingPct * smallestDimension / 2f);
563        if (Constants.DebugFlags.App.EnableSearchButton) {
564            // Don't need to pad the top since we have some padding on the search bar already
565            mStackRect.left += padding;
566            mStackRect.right -= padding;
567            mStackRect.bottom -= padding;
568        } else {
569            mStackRect.inset(padding, padding);
570        }
571        mStackRectSansPeek.set(mStackRect);
572        mStackRectSansPeek.top += Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height();
573
574        // Compute the task rect
575        int minHeight = (int) (mStackRect.height() -
576                (Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height()));
577        int size = Math.min(minHeight, Math.min(mStackRect.width(), mStackRect.height()));
578        int left = mStackRect.left + (mStackRect.width() - size) / 2;
579        mTaskRect.set(left, mStackRectSansPeek.top,
580                left + size, mStackRectSansPeek.top + size);
581
582        // Update the scroll bounds
583        updateMinMaxScroll(false);
584    }
585
586    /**
587     * This is called with the size of the space not including the top or right insets, or the
588     * search bar height in portrait (but including the search bar width in landscape, since we want
589     * to draw under it.
590     */
591    @Override
592    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
593        int width = MeasureSpec.getSize(widthMeasureSpec);
594        int height = MeasureSpec.getSize(heightMeasureSpec);
595        Console.log(Constants.DebugFlags.UI.MeasureAndLayout, "[TaskStackView|measure]",
596                "width: " + width + " height: " + height +
597                " awaitingFirstLayout: " + mAwaitingFirstLayout, Console.AnsiGreen);
598
599        // Compute our stack/task rects
600        RecentsConfiguration config = RecentsConfiguration.getInstance();
601        Rect taskStackBounds = new Rect();
602        config.getTaskStackBounds(width, height, taskStackBounds);
603        computeRects(width, height, taskStackBounds.left, config.systemInsets.bottom);
604
605        // Debug logging
606        if (Constants.DebugFlags.UI.MeasureAndLayout) {
607            Console.log("  [TaskStack|fullRect] " + mRect);
608            Console.log("  [TaskStack|stackRect] " + mStackRect);
609            Console.log("  [TaskStack|stackRectSansPeek] " + mStackRectSansPeek);
610            Console.log("  [TaskStack|taskRect] " + mTaskRect);
611        }
612
613        // If this is the first layout, then scroll to the front of the stack and synchronize the
614        // stack views immediately
615        if (mAwaitingFirstLayout) {
616            setStackScroll(mMaxScroll);
617            requestSynchronizeStackViewsWithModel();
618            synchronizeStackViewsWithModel();
619
620            // Animate the task bar of the first task view
621            if (config.launchedWithThumbnailAnimation &&
622                    Constants.Values.TaskView.AnimateFrontTaskBarOnEnterRecents) {
623                TaskView tv = (TaskView) getChildAt(getChildCount() - 1);
624                if (tv != null) {
625                    tv.animateOnEnterRecents();
626                }
627            }
628        }
629
630        // Measure each of the children
631        int childCount = getChildCount();
632        for (int i = 0; i < childCount; i++) {
633            TaskView t = (TaskView) getChildAt(i);
634            t.measure(MeasureSpec.makeMeasureSpec(mTaskRect.width(), MeasureSpec.EXACTLY),
635                    MeasureSpec.makeMeasureSpec(mTaskRect.height(), MeasureSpec.EXACTLY));
636        }
637
638        setMeasuredDimension(width, height);
639    }
640
641    /**
642     * This is called with the size of the space not including the top or right insets, or the
643     * search bar height in portrait (but including the search bar width in landscape, since we want
644     * to draw under it.
645     */
646    @Override
647    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
648        Console.log(Constants.DebugFlags.UI.MeasureAndLayout, "[TaskStackView|layout]",
649                "" + new Rect(left, top, right, bottom), Console.AnsiGreen);
650
651        // Debug logging
652        if (Constants.DebugFlags.UI.MeasureAndLayout) {
653            Console.log("  [TaskStack|fullRect] " + mRect);
654            Console.log("  [TaskStack|stackRect] " + mStackRect);
655            Console.log("  [TaskStack|stackRectSansPeek] " + mStackRectSansPeek);
656            Console.log("  [TaskStack|taskRect] " + mTaskRect);
657        }
658
659        // Layout each of the children
660        int childCount = getChildCount();
661        for (int i = 0; i < childCount; i++) {
662            TaskView t = (TaskView) getChildAt(i);
663            t.layout(mTaskRect.left, mStackRectSansPeek.top,
664                    mTaskRect.right, mStackRectSansPeek.top + mTaskRect.height());
665        }
666
667        if (mAwaitingFirstLayout) {
668            mAwaitingFirstLayout = false;
669        }
670    }
671
672    @Override
673    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
674        super.onScrollChanged(l, t, oldl, oldt);
675        requestSynchronizeStackViewsWithModel();
676    }
677
678    public boolean isTransformedTouchPointInView(float x, float y, View child) {
679        return isTransformedTouchPointInView(x, y, child, null);
680    }
681
682    /**** TaskStackCallbacks Implementation ****/
683
684    @Override
685    public void onStackTaskAdded(TaskStack stack, Task t) {
686        requestSynchronizeStackViewsWithModel();
687    }
688
689    @Override
690    public void onStackTaskRemoved(TaskStack stack, Task t) {
691        // Remove the view associated with this task, we can't rely on updateTransforms
692        // to work here because the task is no longer in the list
693        int childCount = getChildCount();
694        for (int i = childCount - 1; i >= 0; i--) {
695            TaskView tv = (TaskView) getChildAt(i);
696            if (tv.getTask() == t) {
697                mViewPool.returnViewToPool(tv);
698                break;
699            }
700        }
701
702        updateMinMaxScroll(true);
703        int movement = (int) (Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height());
704        requestSynchronizeStackViewsWithModel(Utilities.calculateTranslationAnimationDuration(movement));
705    }
706
707    /**
708     * Creates the animations for all the children views that need to be removed or to move views
709     * to their un/filtered position when we are un/filtering a stack, and returns the duration
710     * for these animations.
711     */
712    int getExitTransformsForFilterAnimation(ArrayList<Task> curTasks,
713                        ArrayList<TaskViewTransform> curTaskTransforms,
714                        ArrayList<Task> tasks, ArrayList<TaskViewTransform> taskTransforms,
715                        HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransformsOut,
716                        ArrayList<TaskView> childrenToRemoveOut,
717                        RecentsConfiguration config) {
718        // Animate all of the existing views out of view (if they are not in the visible range in
719        // the new stack) or to their final positions in the new stack
720        int movement = 0;
721        int childCount = getChildCount();
722        for (int i = 0; i < childCount; i++) {
723            TaskView tv = (TaskView) getChildAt(i);
724            Task task = tv.getTask();
725            int taskIndex = tasks.indexOf(task);
726            TaskViewTransform toTransform;
727
728            // If the view is no longer visible, then we should just animate it out
729            boolean willBeInvisible = taskIndex < 0 || !taskTransforms.get(taskIndex).visible;
730            if (willBeInvisible) {
731                if (taskIndex < 0) {
732                    toTransform = curTaskTransforms.get(curTasks.indexOf(task));
733                } else {
734                    toTransform = new TaskViewTransform(taskTransforms.get(taskIndex));
735                }
736                tv.prepareTaskTransformForFilterTaskVisible(toTransform);
737                childrenToRemoveOut.add(tv);
738            } else {
739                toTransform = taskTransforms.get(taskIndex);
740                // Use the movement of the visible views to calculate the duration of the animation
741                movement = Math.max(movement, Math.abs(toTransform.translationY -
742                        (int) tv.getTranslationY()));
743            }
744            childViewTransformsOut.put(tv, new Pair(0, toTransform));
745        }
746        return Utilities.calculateTranslationAnimationDuration(movement,
747                config.filteringCurrentViewsMinAnimDuration);
748    }
749
750    /**
751     * Creates the animations for all the children views that need to be animated in when we are
752     * un/filtering a stack, and returns the duration for these animations.
753     */
754    int getEnterTransformsForFilterAnimation(ArrayList<Task> tasks,
755                         ArrayList<TaskViewTransform> taskTransforms,
756                         HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransformsOut,
757                         RecentsConfiguration config) {
758        int offset = 0;
759        int movement = 0;
760        int taskCount = tasks.size();
761        for (int i = taskCount - 1; i >= 0; i--) {
762            Task task = tasks.get(i);
763            TaskViewTransform toTransform = taskTransforms.get(i);
764            if (toTransform.visible) {
765                TaskView tv = getChildViewForTask(task);
766                if (tv == null) {
767                    // For views that are not already visible, animate them in
768                    tv = mViewPool.pickUpViewFromPool(task, task);
769
770                    // Compose a new transform to fade and slide the new task in
771                    TaskViewTransform fromTransform = new TaskViewTransform(toTransform);
772                    tv.prepareTaskTransformForFilterTaskHidden(fromTransform);
773                    tv.updateViewPropertiesToTaskTransform(null, fromTransform, 0);
774
775                    int startDelay = offset *
776                            Constants.Values.TaskStackView.FilterStartDelay;
777                    childViewTransformsOut.put(tv, new Pair(startDelay, toTransform));
778
779                    // Use the movement of the new views to calculate the duration of the animation
780                    movement = Math.max(movement,
781                            Math.abs(toTransform.translationY - fromTransform.translationY));
782                    offset++;
783                }
784            }
785        }
786        return Utilities.calculateTranslationAnimationDuration(movement,
787                config.filteringNewViewsMinAnimDuration);
788    }
789
790    /** Orchestrates the animations of the current child views and any new views. */
791    void doFilteringAnimation(ArrayList<Task> curTasks,
792                              ArrayList<TaskViewTransform> curTaskTransforms,
793                              final ArrayList<Task> tasks,
794                              final ArrayList<TaskViewTransform> taskTransforms) {
795        final RecentsConfiguration config = RecentsConfiguration.getInstance();
796
797        // Calculate the transforms to animate out all the existing views if they are not in the
798        // new visible range (or to their final positions in the stack if they are)
799        final ArrayList<TaskView> childrenToRemove = new ArrayList<TaskView>();
800        final HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransforms =
801                new HashMap<TaskView, Pair<Integer, TaskViewTransform>>();
802        int duration = getExitTransformsForFilterAnimation(curTasks, curTaskTransforms, tasks,
803                taskTransforms, childViewTransforms, childrenToRemove, config);
804
805        // If all the current views are in the visible range of the new stack, then don't wait for
806        // views to animate out and animate all the new views into their place
807        final boolean unifyNewViewAnimation = childrenToRemove.isEmpty();
808        if (unifyNewViewAnimation) {
809            int inDuration = getEnterTransformsForFilterAnimation(tasks, taskTransforms,
810                    childViewTransforms, config);
811            duration = Math.max(duration, inDuration);
812        }
813
814        // Animate all the views to their final transforms
815        for (final TaskView tv : childViewTransforms.keySet()) {
816            Pair<Integer, TaskViewTransform> t = childViewTransforms.get(tv);
817            tv.animate().cancel();
818            tv.animate()
819                    .setStartDelay(t.first)
820                    .withEndAction(new Runnable() {
821                        @Override
822                        public void run() {
823                            childViewTransforms.remove(tv);
824                            if (childViewTransforms.isEmpty()) {
825                                // Return all the removed children to the view pool
826                                for (TaskView tv : childrenToRemove) {
827                                    mViewPool.returnViewToPool(tv);
828                                }
829
830                                if (!unifyNewViewAnimation) {
831                                    // For views that are not already visible, animate them in
832                                    childViewTransforms.clear();
833                                    int duration = getEnterTransformsForFilterAnimation(tasks,
834                                            taskTransforms, childViewTransforms, config);
835                                    for (final TaskView tv : childViewTransforms.keySet()) {
836                                        Pair<Integer, TaskViewTransform> t = childViewTransforms.get(tv);
837                                        tv.animate().setStartDelay(t.first);
838                                        tv.updateViewPropertiesToTaskTransform(null, t.second, duration);
839                                    }
840                                }
841                            }
842                        }
843                    });
844            tv.updateViewPropertiesToTaskTransform(null, t.second, duration);
845        }
846    }
847
848    @Override
849    public void onStackFiltered(TaskStack newStack, final ArrayList<Task> curTasks,
850                                Task filteredTask) {
851        // Close any open info panes
852        closeOpenInfoPanes();
853
854        // Stash the scroll and filtered task for us to restore to when we unfilter
855        mStashedScroll = getStackScroll();
856
857        // Calculate the current task transforms
858        ArrayList<TaskViewTransform> curTaskTransforms =
859                getStackTransforms(curTasks, getStackScroll(), null, true);
860
861        // Scroll the item to the top of the stack (sans-peek) rect so that we can see it better
862        updateMinMaxScroll(false);
863        float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height();
864        setStackScrollRaw((int) (newStack.indexOfTask(filteredTask) * overlapHeight));
865        boundScrollRaw();
866
867        // Compute the transforms of the items in the new stack after setting the new scroll
868        final ArrayList<Task> tasks = mStack.getTasks();
869        final ArrayList<TaskViewTransform> taskTransforms =
870                getStackTransforms(mStack.getTasks(), getStackScroll(), null, true);
871
872        // Animate
873        doFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms);
874    }
875
876    @Override
877    public void onStackUnfiltered(TaskStack newStack, final ArrayList<Task> curTasks) {
878        // Close any open info panes
879        closeOpenInfoPanes();
880
881        // Calculate the current task transforms
882        final ArrayList<TaskViewTransform> curTaskTransforms =
883                getStackTransforms(curTasks, getStackScroll(), null, true);
884
885        // Restore the stashed scroll
886        updateMinMaxScroll(false);
887        setStackScrollRaw(mStashedScroll);
888        boundScrollRaw();
889
890        // Compute the transforms of the items in the new stack after restoring the stashed scroll
891        final ArrayList<Task> tasks = mStack.getTasks();
892        final ArrayList<TaskViewTransform> taskTransforms =
893                getStackTransforms(tasks, getStackScroll(), null, true);
894
895        // Animate
896        doFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms);
897
898        // Clear the saved vars
899        mStashedScroll = 0;
900    }
901
902    /**** ViewPoolConsumer Implementation ****/
903
904    @Override
905    public TaskView createView(Context context) {
906        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|createPoolView]");
907        return (TaskView) mInflater.inflate(R.layout.recents_task_view, this, false);
908    }
909
910    @Override
911    public void prepareViewToEnterPool(TaskView tv) {
912        Task task = tv.getTask();
913        tv.resetViewProperties();
914        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|returnToPool]",
915                tv.getTask() + " tv: " + tv);
916
917        // Report that this tasks's data is no longer being used
918        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
919        loader.unloadTaskData(task);
920
921        // Detach the view from the hierarchy
922        detachViewFromParent(tv);
923
924        // Disable hw layers on this view
925        tv.disableHwLayers();
926    }
927
928    @Override
929    public void prepareViewToLeavePool(TaskView tv, Task prepareData, boolean isNewView) {
930        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|leavePool]",
931                "isNewView: " + isNewView);
932
933        // Setup and attach the view to the window
934        Task task = prepareData;
935        // We try and rebind the task (this MUST be done before the task filled)
936        tv.onTaskBound(task);
937        // Request that this tasks's data be filled
938        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
939        loader.loadTaskData(task);
940
941        // Find the index where this task should be placed in the children
942        int insertIndex = -1;
943        int childCount = getChildCount();
944        for (int i = 0; i < childCount; i++) {
945            Task tvTask = ((TaskView) getChildAt(i)).getTask();
946            if (mStack.containsTask(task) && (mStack.indexOfTask(task) < mStack.indexOfTask(tvTask))) {
947                insertIndex = i;
948                break;
949            }
950        }
951
952        // Add/attach the view to the hierarchy
953        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "  [TaskStackView|insertIndex]",
954                "" + insertIndex);
955        if (isNewView) {
956            addView(tv, insertIndex);
957
958            // Set the callbacks and listeners for this new view
959            tv.setOnClickListener(this);
960            if (Constants.DebugFlags.App.EnableInfoPane) {
961                tv.setOnLongClickListener(this);
962            }
963            tv.setCallbacks(this);
964        } else {
965            attachViewToParent(tv, insertIndex, tv.getLayoutParams());
966        }
967
968        // Enable hw layers on this view if hw layers are enabled on the stack
969        if (mHwLayersRefCount > 0) {
970            tv.enableHwLayers();
971        }
972    }
973
974    @Override
975    public boolean hasPreferredData(TaskView tv, Task preferredData) {
976        return (tv.getTask() == preferredData);
977    }
978
979    /**** TaskViewCallbacks Implementation ****/
980
981    @Override
982    public void onTaskIconClicked(TaskView tv) {
983        Console.log(Constants.DebugFlags.UI.ClickEvents, "[TaskStack|Clicked|Icon]",
984                tv.getTask() + " is currently filtered: " + mStack.hasFilteredTasks(),
985                Console.AnsiCyan);
986        if (Constants.DebugFlags.App.EnableTaskFiltering) {
987            if (mStack.hasFilteredTasks()) {
988                mStack.unfilterTasks();
989            } else {
990                mStack.filterTasks(tv.getTask());
991            }
992        }
993    }
994
995    @Override
996    public void onTaskInfoPanelShown(TaskView tv) {
997        // Do nothing
998    }
999
1000    @Override
1001    public void onTaskInfoPanelHidden(TaskView tv) {
1002        // Unset the saved scroll
1003        mLastInfoPaneStackScroll = -1;
1004    }
1005
1006    @Override
1007    public void onTaskAppInfoClicked(TaskView tv) {
1008        if (mCb != null) {
1009            mCb.onTaskAppInfoLaunched(tv.getTask());
1010        }
1011    }
1012
1013    /**** View.OnClickListener Implementation ****/
1014
1015    @Override
1016    public void onClick(View v) {
1017        TaskView tv = (TaskView) v;
1018        Task task = tv.getTask();
1019        Console.log(Constants.DebugFlags.UI.ClickEvents, "[TaskStack|Clicked|Thumbnail]",
1020                task + " cb: " + mCb);
1021
1022        // Close any open info panes if the user taps on another task
1023        if (closeOpenInfoPanes()) {
1024            return;
1025        }
1026
1027        if (mCb != null) {
1028            mCb.onTaskLaunched(this, tv, mStack, task);
1029        }
1030    }
1031
1032    @Override
1033    public boolean onLongClick(View v) {
1034        if (!Constants.DebugFlags.App.EnableInfoPane) return false;
1035
1036        TaskView tv = (TaskView) v;
1037
1038        // Close any other task info panels if we launch another info pane
1039        closeOpenInfoPanes();
1040
1041        // Scroll the task view so that it is maximally visible
1042        float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height();
1043        int taskIndex = mStack.indexOfTask(tv.getTask());
1044        int curScroll = getStackScroll();
1045        int newScroll = (int) Math.max(mMinScroll, Math.min(mMaxScroll, taskIndex * overlapHeight));
1046        TaskViewTransform transform = getStackTransform(taskIndex, curScroll);
1047        Rect nonOverlapRect = new Rect(transform.rect);
1048        if (taskIndex < (mStack.getTaskCount() - 1)) {
1049            nonOverlapRect.bottom = nonOverlapRect.top + (int) overlapHeight;
1050        }
1051
1052        // XXX: Use HW Layers
1053        if (transform.t < 0f) {
1054            animateScroll(curScroll, newScroll, null);
1055        } else if (nonOverlapRect.bottom > mStackRectSansPeek.bottom) {
1056            // Check if we are out of bounds, if so, just scroll it in such that the bottom of the
1057            // task view is visible
1058            newScroll = curScroll - (mStackRectSansPeek.bottom - nonOverlapRect.bottom);
1059            animateScroll(curScroll, newScroll, null);
1060        }
1061        mLastInfoPaneStackScroll = newScroll;
1062
1063        // Show the info pane for this task view
1064        tv.showInfoPane(new Rect(0, 0, 0, (int) overlapHeight));
1065        return true;
1066    }
1067}
1068
1069/* Handles touch events */
1070class TaskStackViewTouchHandler implements SwipeHelper.Callback {
1071    static int INACTIVE_POINTER_ID = -1;
1072
1073    TaskStackView mSv;
1074    VelocityTracker mVelocityTracker;
1075
1076    boolean mIsScrolling;
1077
1078    int mInitialMotionX, mInitialMotionY;
1079    int mLastMotionX, mLastMotionY;
1080    int mActivePointerId = INACTIVE_POINTER_ID;
1081    TaskView mActiveTaskView = null;
1082
1083    int mTotalScrollMotion;
1084    int mMinimumVelocity;
1085    int mMaximumVelocity;
1086    // The scroll touch slop is used to calculate when we start scrolling
1087    int mScrollTouchSlop;
1088    // The page touch slop is used to calculate when we start swiping
1089    float mPagingTouchSlop;
1090
1091    SwipeHelper mSwipeHelper;
1092    boolean mInterceptedBySwipeHelper;
1093
1094    public TaskStackViewTouchHandler(Context context, TaskStackView sv) {
1095        ViewConfiguration configuration = ViewConfiguration.get(context);
1096        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
1097        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
1098        mScrollTouchSlop = configuration.getScaledTouchSlop();
1099        mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
1100        mSv = sv;
1101
1102
1103        float densityScale = context.getResources().getDisplayMetrics().density;
1104        mSwipeHelper = new SwipeHelper(SwipeHelper.X, this, densityScale, mPagingTouchSlop);
1105        mSwipeHelper.setMinAlpha(1f);
1106    }
1107
1108    /** Velocity tracker helpers */
1109    void initOrResetVelocityTracker() {
1110        if (mVelocityTracker == null) {
1111            mVelocityTracker = VelocityTracker.obtain();
1112        } else {
1113            mVelocityTracker.clear();
1114        }
1115    }
1116    void initVelocityTrackerIfNotExists() {
1117        if (mVelocityTracker == null) {
1118            mVelocityTracker = VelocityTracker.obtain();
1119        }
1120    }
1121    void recycleVelocityTracker() {
1122        if (mVelocityTracker != null) {
1123            mVelocityTracker.recycle();
1124            mVelocityTracker = null;
1125        }
1126    }
1127
1128    /** Returns the view at the specified coordinates */
1129    TaskView findViewAtPoint(int x, int y) {
1130        int childCount = mSv.getChildCount();
1131        for (int i = childCount - 1; i >= 0; i--) {
1132            TaskView tv = (TaskView) mSv.getChildAt(i);
1133            if (tv.getVisibility() == View.VISIBLE) {
1134                if (mSv.isTransformedTouchPointInView(x, y, tv)) {
1135                    return tv;
1136                }
1137            }
1138        }
1139        return null;
1140    }
1141
1142    /** Touch preprocessing for handling below */
1143    public boolean onInterceptTouchEvent(MotionEvent ev) {
1144        Console.log(Constants.DebugFlags.UI.TouchEvents,
1145                "[TaskStackViewTouchHandler|interceptTouchEvent]",
1146                Console.motionEventActionToString(ev.getAction()), Console.AnsiBlue);
1147
1148        // Return early if we have no children
1149        boolean hasChildren = (mSv.getChildCount() > 0);
1150        if (!hasChildren) {
1151            return false;
1152        }
1153
1154        // Pass through to swipe helper if we are swiping
1155        mInterceptedBySwipeHelper = mSwipeHelper.onInterceptTouchEvent(ev);
1156        if (mInterceptedBySwipeHelper) {
1157            return true;
1158        }
1159
1160        boolean wasScrolling = !mSv.mScroller.isFinished() ||
1161                (mSv.mScrollAnimator != null && mSv.mScrollAnimator.isRunning());
1162        int action = ev.getAction();
1163        switch (action & MotionEvent.ACTION_MASK) {
1164            case MotionEvent.ACTION_DOWN: {
1165                // Save the touch down info
1166                mInitialMotionX = mLastMotionX = (int) ev.getX();
1167                mInitialMotionY = mLastMotionY = (int) ev.getY();
1168                mActivePointerId = ev.getPointerId(0);
1169                mActiveTaskView = findViewAtPoint(mLastMotionX, mLastMotionY);
1170                // Stop the current scroll if it is still flinging
1171                mSv.abortScroller();
1172                mSv.abortBoundScrollAnimation();
1173                // Initialize the velocity tracker
1174                initOrResetVelocityTracker();
1175                mVelocityTracker.addMovement(ev);
1176                // Check if the scroller is finished yet
1177                mIsScrolling = !mSv.mScroller.isFinished();
1178                break;
1179            }
1180            case MotionEvent.ACTION_MOVE: {
1181                if (mActivePointerId == INACTIVE_POINTER_ID) break;
1182
1183                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
1184                int y = (int) ev.getY(activePointerIndex);
1185                int x = (int) ev.getX(activePointerIndex);
1186                if (Math.abs(y - mInitialMotionY) > mScrollTouchSlop) {
1187                    // Save the touch move info
1188                    mIsScrolling = true;
1189                    // Initialize the velocity tracker if necessary
1190                    initVelocityTrackerIfNotExists();
1191                    mVelocityTracker.addMovement(ev);
1192                    // Disallow parents from intercepting touch events
1193                    final ViewParent parent = mSv.getParent();
1194                    if (parent != null) {
1195                        parent.requestDisallowInterceptTouchEvent(true);
1196                    }
1197                    // Enable HW layers
1198                    mSv.addHwLayersRefCount("stackScroll");
1199                }
1200
1201                mLastMotionX = x;
1202                mLastMotionY = y;
1203                break;
1204            }
1205            case MotionEvent.ACTION_CANCEL:
1206            case MotionEvent.ACTION_UP: {
1207                // Animate the scroll back if we've cancelled
1208                mSv.animateBoundScroll();
1209                // Disable HW layers
1210                if (mIsScrolling) {
1211                    mSv.decHwLayersRefCount("stackScroll");
1212                }
1213                // Reset the drag state and the velocity tracker
1214                mIsScrolling = false;
1215                mActivePointerId = INACTIVE_POINTER_ID;
1216                mActiveTaskView = null;
1217                mTotalScrollMotion = 0;
1218                recycleVelocityTracker();
1219                break;
1220            }
1221        }
1222
1223        return wasScrolling || mIsScrolling;
1224    }
1225
1226    /** Handles touch events once we have intercepted them */
1227    public boolean onTouchEvent(MotionEvent ev) {
1228        Console.log(Constants.DebugFlags.UI.TouchEvents,
1229                "[TaskStackViewTouchHandler|touchEvent]",
1230                Console.motionEventActionToString(ev.getAction()), Console.AnsiBlue);
1231
1232        // Short circuit if we have no children
1233        boolean hasChildren = (mSv.getChildCount() > 0);
1234        if (!hasChildren) {
1235            return false;
1236        }
1237
1238        // Pass through to swipe helper if we are swiping
1239        if (mInterceptedBySwipeHelper && mSwipeHelper.onTouchEvent(ev)) {
1240            return true;
1241        }
1242
1243        // Update the velocity tracker
1244        initVelocityTrackerIfNotExists();
1245        mVelocityTracker.addMovement(ev);
1246
1247        int action = ev.getAction();
1248        switch (action & MotionEvent.ACTION_MASK) {
1249            case MotionEvent.ACTION_DOWN: {
1250                // Save the touch down info
1251                mInitialMotionX = mLastMotionX = (int) ev.getX();
1252                mInitialMotionY = mLastMotionY = (int) ev.getY();
1253                mActivePointerId = ev.getPointerId(0);
1254                mActiveTaskView = findViewAtPoint(mLastMotionX, mLastMotionY);
1255                // Stop the current scroll if it is still flinging
1256                mSv.abortScroller();
1257                mSv.abortBoundScrollAnimation();
1258                // Initialize the velocity tracker
1259                initOrResetVelocityTracker();
1260                mVelocityTracker.addMovement(ev);
1261                // Disallow parents from intercepting touch events
1262                final ViewParent parent = mSv.getParent();
1263                if (parent != null) {
1264                    parent.requestDisallowInterceptTouchEvent(true);
1265                }
1266                break;
1267            }
1268            case MotionEvent.ACTION_POINTER_DOWN: {
1269                final int index = ev.getActionIndex();
1270                mActivePointerId = ev.getPointerId(index);
1271                mLastMotionX = (int) ev.getX(index);
1272                mLastMotionY = (int) ev.getY(index);
1273                break;
1274            }
1275            case MotionEvent.ACTION_MOVE: {
1276                if (mActivePointerId == INACTIVE_POINTER_ID) break;
1277
1278                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
1279                int x = (int) ev.getX(activePointerIndex);
1280                int y = (int) ev.getY(activePointerIndex);
1281                int yTotal = Math.abs(y - mInitialMotionY);
1282                int deltaY = mLastMotionY - y;
1283                if (!mIsScrolling) {
1284                    if (yTotal > mScrollTouchSlop) {
1285                        mIsScrolling = true;
1286                        // Initialize the velocity tracker
1287                        initOrResetVelocityTracker();
1288                        mVelocityTracker.addMovement(ev);
1289                        // Disallow parents from intercepting touch events
1290                        final ViewParent parent = mSv.getParent();
1291                        if (parent != null) {
1292                            parent.requestDisallowInterceptTouchEvent(true);
1293                        }
1294                        // Enable HW layers
1295                        mSv.addHwLayersRefCount("stackScroll");
1296                    }
1297                }
1298                if (mIsScrolling) {
1299                    int curStackScroll = mSv.getStackScroll();
1300                    if (mSv.isScrollOutOfBounds(curStackScroll + deltaY)) {
1301                        // Scale the touch if we are overscrolling
1302                        deltaY /= Constants.Values.TaskStackView.TouchOverscrollScaleFactor;
1303                    }
1304                    mSv.setStackScroll(curStackScroll + deltaY);
1305                    if (mSv.isScrollOutOfBounds()) {
1306                        mVelocityTracker.clear();
1307                    }
1308                }
1309                mLastMotionX = x;
1310                mLastMotionY = y;
1311                mTotalScrollMotion += Math.abs(deltaY);
1312                break;
1313            }
1314            case MotionEvent.ACTION_UP: {
1315                final VelocityTracker velocityTracker = mVelocityTracker;
1316                velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1317                int velocity = (int) velocityTracker.getYVelocity(mActivePointerId);
1318
1319                if (mIsScrolling && (Math.abs(velocity) > mMinimumVelocity)) {
1320                    // Enable HW layers on the stack
1321                    mSv.addHwLayersRefCount("flingScroll");
1322                    int overscrollRange = (int) (Math.min(1f,
1323                            Math.abs((float) velocity / mMaximumVelocity)) *
1324                            Constants.Values.TaskStackView.TaskStackOverscrollRange);
1325
1326                    Console.log(Constants.DebugFlags.UI.TouchEvents,
1327                            "[TaskStackViewTouchHandler|fling]",
1328                            "scroll: " + mSv.getStackScroll() + " velocity: " + velocity +
1329                                    " maxVelocity: " + mMaximumVelocity +
1330                                    " overscrollRange: " + overscrollRange,
1331                            Console.AnsiGreen);
1332
1333                    // Fling scroll
1334                    mSv.mScroller.fling(0, mSv.getStackScroll(),
1335                            0, -velocity,
1336                            0, 0,
1337                            mSv.mMinScroll, mSv.mMaxScroll,
1338                            0, overscrollRange);
1339                    // Invalidate to kick off computeScroll
1340                    mSv.invalidate();
1341                } else if (mSv.isScrollOutOfBounds()) {
1342                    // Animate the scroll back into bounds
1343                    // XXX: Make this animation a function of the velocity OR distance
1344                    mSv.animateBoundScroll();
1345                }
1346
1347                if (mIsScrolling) {
1348                    // Disable HW layers
1349                    mSv.decHwLayersRefCount("stackScroll");
1350                }
1351                mActivePointerId = INACTIVE_POINTER_ID;
1352                mIsScrolling = false;
1353                mTotalScrollMotion = 0;
1354                recycleVelocityTracker();
1355                break;
1356            }
1357            case MotionEvent.ACTION_POINTER_UP: {
1358                int pointerIndex = ev.getActionIndex();
1359                int pointerId = ev.getPointerId(pointerIndex);
1360                if (pointerId == mActivePointerId) {
1361                    // Select a new active pointer id and reset the motion state
1362                    final int newPointerIndex = (pointerIndex == 0) ? 1 : 0;
1363                    mActivePointerId = ev.getPointerId(newPointerIndex);
1364                    mLastMotionX = (int) ev.getX(newPointerIndex);
1365                    mLastMotionY = (int) ev.getY(newPointerIndex);
1366                    mVelocityTracker.clear();
1367                }
1368                break;
1369            }
1370            case MotionEvent.ACTION_CANCEL: {
1371                if (mIsScrolling) {
1372                    // Disable HW layers
1373                    mSv.decHwLayersRefCount("stackScroll");
1374                }
1375                if (mSv.isScrollOutOfBounds()) {
1376                    // Animate the scroll back into bounds
1377                    // XXX: Make this animation a function of the velocity OR distance
1378                    mSv.animateBoundScroll();
1379                }
1380                mActivePointerId = INACTIVE_POINTER_ID;
1381                mIsScrolling = false;
1382                mTotalScrollMotion = 0;
1383                recycleVelocityTracker();
1384                break;
1385            }
1386        }
1387        return true;
1388    }
1389
1390    /**** SwipeHelper Implementation ****/
1391
1392    @Override
1393    public View getChildAtPosition(MotionEvent ev) {
1394        return findViewAtPoint((int) ev.getX(), (int) ev.getY());
1395    }
1396
1397    @Override
1398    public boolean canChildBeDismissed(View v) {
1399        return true;
1400    }
1401
1402    @Override
1403    public void onBeginDrag(View v) {
1404        // Enable HW layers
1405        mSv.addHwLayersRefCount("swipeBegin");
1406        // Disallow parents from intercepting touch events
1407        final ViewParent parent = mSv.getParent();
1408        if (parent != null) {
1409            parent.requestDisallowInterceptTouchEvent(true);
1410        }
1411        // If the info panel is currently showing on this view, then we need to dismiss it
1412        if (Constants.DebugFlags.App.EnableInfoPane) {
1413            TaskView tv = (TaskView) v;
1414            if (tv.isInfoPaneVisible()) {
1415                tv.hideInfoPane();
1416            }
1417        }
1418    }
1419
1420    @Override
1421    public void onChildDismissed(View v) {
1422        TaskView tv = (TaskView) v;
1423        Task task = tv.getTask();
1424        Activity activity = (Activity) mSv.getContext();
1425
1426        // Remove the task from the view
1427        mSv.mStack.removeTask(task);
1428
1429        // Remove any stored data from the loader
1430        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
1431        loader.deleteTaskData(task);
1432
1433        // Remove the task from activity manager
1434        RecentsTaskLoader.getInstance().getSystemServicesProxy().removeTask(tv.getTask().key.id);
1435
1436        // If there are no remaining tasks, then either unfilter the current stack, or just close
1437        // the activity if there are no filtered stacks
1438        if (mSv.mStack.getTaskCount() == 0) {
1439            boolean shouldFinishActivity = true;
1440            if (mSv.mStack.hasFilteredTasks()) {
1441                mSv.mStack.unfilterTasks();
1442                shouldFinishActivity = (mSv.mStack.getTaskCount() == 0);
1443            }
1444            if (shouldFinishActivity) {
1445                activity.finish();
1446            }
1447        }
1448
1449        // Disable HW layers
1450        mSv.decHwLayersRefCount("swipeComplete");
1451    }
1452
1453    @Override
1454    public void onSnapBackCompleted(View v) {
1455        // Do Nothing
1456    }
1457
1458    @Override
1459    public void onDragCancelled(View v) {
1460        // Disable HW layers
1461        mSv.decHwLayersRefCount("swipeCancelled");
1462    }
1463}
1464