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