TaskStackView.java revision ecd9b3031c9a322bd69380eae2810d53839e8f64
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 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.bottom -= insetBottom;
559
560        int smallestDimension = Math.min(width, height);
561        int padding = (int) (Constants.Values.TaskStackView.StackPaddingPct * smallestDimension / 2f);
562        if (Constants.DebugFlags.App.EnableSearchButton) {
563            // Don't need to pad the top since we have some padding on the search bar already
564            mStackRect.left += padding;
565            mStackRect.right -= padding;
566            mStackRect.bottom -= padding;
567        } else {
568            mStackRect.inset(padding, padding);
569        }
570        mStackRectSansPeek.set(mStackRect);
571        mStackRectSansPeek.top += Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height();
572
573        // Compute the task rect
574        int minHeight = (int) (mStackRect.height() -
575                (Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height()));
576        int size = Math.min(minHeight, Math.min(mStackRect.width(), mStackRect.height()));
577        int left = mStackRect.left + (mStackRect.width() - size) / 2;
578        mTaskRect.set(left, mStackRectSansPeek.top,
579                left + size, mStackRectSansPeek.top + size);
580
581        // Update the scroll bounds
582        updateMinMaxScroll(false);
583    }
584
585    @Override
586    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
587        int width = MeasureSpec.getSize(widthMeasureSpec);
588        int height = MeasureSpec.getSize(heightMeasureSpec);
589        Console.log(Constants.DebugFlags.UI.MeasureAndLayout, "[TaskStackView|measure]",
590                "width: " + width + " height: " + height +
591                " awaitingFirstLayout: " + mAwaitingFirstLayout, Console.AnsiGreen);
592
593        // Compute our stack/task rects
594        RecentsConfiguration config = RecentsConfiguration.getInstance();
595        computeRects(width, height, config.systemInsets.bottom);
596
597        // Debug logging
598        if (Constants.DebugFlags.UI.MeasureAndLayout) {
599            Console.log("  [TaskStack|fullRect] " + mRect);
600            Console.log("  [TaskStack|stackRect] " + mStackRect);
601            Console.log("  [TaskStack|stackRectSansPeek] " + mStackRectSansPeek);
602            Console.log("  [TaskStack|taskRect] " + mTaskRect);
603        }
604
605        // If this is the first layout, then scroll to the front of the stack and synchronize the
606        // stack views immediately
607        if (mAwaitingFirstLayout) {
608            setStackScroll(mMaxScroll);
609            requestSynchronizeStackViewsWithModel();
610            synchronizeStackViewsWithModel();
611
612            // Animate the task bar of the first task view
613            if (config.launchedWithThumbnailAnimation &&
614                    Constants.Values.TaskView.AnimateFrontTaskBarOnEnterRecents) {
615                TaskView tv = (TaskView) getChildAt(getChildCount() - 1);
616                if (tv != null) {
617                    tv.animateOnEnterRecents();
618                }
619            }
620        }
621
622        // Measure each of the children
623        int childCount = getChildCount();
624        for (int i = 0; i < childCount; i++) {
625            TaskView t = (TaskView) getChildAt(i);
626            t.measure(MeasureSpec.makeMeasureSpec(mTaskRect.width(), MeasureSpec.EXACTLY),
627                    MeasureSpec.makeMeasureSpec(mTaskRect.height(), MeasureSpec.EXACTLY));
628        }
629
630        setMeasuredDimension(width, height);
631    }
632
633    @Override
634    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
635        Console.log(Constants.DebugFlags.UI.MeasureAndLayout, "[TaskStackView|layout]",
636                "" + new Rect(left, top, right, bottom), Console.AnsiGreen);
637
638        // Debug logging
639        if (Constants.DebugFlags.UI.MeasureAndLayout) {
640            Console.log("  [TaskStack|fullRect] " + mRect);
641            Console.log("  [TaskStack|stackRect] " + mStackRect);
642            Console.log("  [TaskStack|stackRectSansPeek] " + mStackRectSansPeek);
643            Console.log("  [TaskStack|taskRect] " + mTaskRect);
644        }
645
646        // Layout each of the children
647        int childCount = getChildCount();
648        for (int i = 0; i < childCount; i++) {
649            TaskView t = (TaskView) getChildAt(i);
650            t.layout(mTaskRect.left, mStackRectSansPeek.top,
651                    mTaskRect.right, mStackRectSansPeek.top + mTaskRect.height());
652        }
653
654        if (mAwaitingFirstLayout) {
655            mAwaitingFirstLayout = false;
656        }
657    }
658
659    @Override
660    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
661        super.onScrollChanged(l, t, oldl, oldt);
662        requestSynchronizeStackViewsWithModel();
663    }
664
665    public boolean isTransformedTouchPointInView(float x, float y, View child) {
666        return isTransformedTouchPointInView(x, y, child, null);
667    }
668
669    /**** TaskStackCallbacks Implementation ****/
670
671    @Override
672    public void onStackTaskAdded(TaskStack stack, Task t) {
673        requestSynchronizeStackViewsWithModel();
674    }
675
676    @Override
677    public void onStackTaskRemoved(TaskStack stack, Task t) {
678        // Remove the view associated with this task, we can't rely on updateTransforms
679        // to work here because the task is no longer in the list
680        int childCount = getChildCount();
681        for (int i = childCount - 1; i >= 0; i--) {
682            TaskView tv = (TaskView) getChildAt(i);
683            if (tv.getTask() == t) {
684                mViewPool.returnViewToPool(tv);
685                break;
686            }
687        }
688
689        updateMinMaxScroll(true);
690        int movement = (int) (Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height());
691        requestSynchronizeStackViewsWithModel(Utilities.calculateTranslationAnimationDuration(movement));
692    }
693
694    /**
695     * Creates the animations for all the children views that need to be removed or to move views
696     * to their un/filtered position when we are un/filtering a stack, and returns the duration
697     * for these animations.
698     */
699    int getExitTransformsForFilterAnimation(ArrayList<Task> curTasks,
700                        ArrayList<TaskViewTransform> curTaskTransforms,
701                        ArrayList<Task> tasks, ArrayList<TaskViewTransform> taskTransforms,
702                        HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransformsOut,
703                        ArrayList<TaskView> childrenToRemoveOut,
704                        RecentsConfiguration config) {
705        // Animate all of the existing views out of view (if they are not in the visible range in
706        // the new stack) or to their final positions in the new stack
707        int movement = 0;
708        int childCount = getChildCount();
709        for (int i = 0; i < childCount; i++) {
710            TaskView tv = (TaskView) getChildAt(i);
711            Task task = tv.getTask();
712            int taskIndex = tasks.indexOf(task);
713            TaskViewTransform toTransform;
714
715            // If the view is no longer visible, then we should just animate it out
716            boolean willBeInvisible = taskIndex < 0 || !taskTransforms.get(taskIndex).visible;
717            if (willBeInvisible) {
718                if (taskIndex < 0) {
719                    toTransform = curTaskTransforms.get(curTasks.indexOf(task));
720                } else {
721                    toTransform = new TaskViewTransform(taskTransforms.get(taskIndex));
722                }
723                tv.prepareTaskTransformForFilterTaskVisible(toTransform);
724                childrenToRemoveOut.add(tv);
725            } else {
726                toTransform = taskTransforms.get(taskIndex);
727                // Use the movement of the visible views to calculate the duration of the animation
728                movement = Math.max(movement, Math.abs(toTransform.translationY -
729                        (int) tv.getTranslationY()));
730            }
731            childViewTransformsOut.put(tv, new Pair(0, toTransform));
732        }
733        return Utilities.calculateTranslationAnimationDuration(movement,
734                config.filteringCurrentViewsMinAnimDuration);
735    }
736
737    /**
738     * Creates the animations for all the children views that need to be animated in when we are
739     * un/filtering a stack, and returns the duration for these animations.
740     */
741    int getEnterTransformsForFilterAnimation(ArrayList<Task> tasks,
742                         ArrayList<TaskViewTransform> taskTransforms,
743                         HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransformsOut,
744                         RecentsConfiguration config) {
745        int offset = 0;
746        int movement = 0;
747        int taskCount = tasks.size();
748        for (int i = taskCount - 1; i >= 0; i--) {
749            Task task = tasks.get(i);
750            TaskViewTransform toTransform = taskTransforms.get(i);
751            if (toTransform.visible) {
752                TaskView tv = getChildViewForTask(task);
753                if (tv == null) {
754                    // For views that are not already visible, animate them in
755                    tv = mViewPool.pickUpViewFromPool(task, task);
756
757                    // Compose a new transform to fade and slide the new task in
758                    TaskViewTransform fromTransform = new TaskViewTransform(toTransform);
759                    tv.prepareTaskTransformForFilterTaskHidden(fromTransform);
760                    tv.updateViewPropertiesToTaskTransform(null, fromTransform, 0);
761
762                    int startDelay = offset *
763                            Constants.Values.TaskStackView.FilterStartDelay;
764                    childViewTransformsOut.put(tv, new Pair(startDelay, toTransform));
765
766                    // Use the movement of the new views to calculate the duration of the animation
767                    movement = Math.max(movement,
768                            Math.abs(toTransform.translationY - fromTransform.translationY));
769                    offset++;
770                }
771            }
772        }
773        return Utilities.calculateTranslationAnimationDuration(movement,
774                config.filteringNewViewsMinAnimDuration);
775    }
776
777    /** Orchestrates the animations of the current child views and any new views. */
778    void doFilteringAnimation(ArrayList<Task> curTasks,
779                              ArrayList<TaskViewTransform> curTaskTransforms,
780                              final ArrayList<Task> tasks,
781                              final ArrayList<TaskViewTransform> taskTransforms) {
782        final RecentsConfiguration config = RecentsConfiguration.getInstance();
783
784        // Calculate the transforms to animate out all the existing views if they are not in the
785        // new visible range (or to their final positions in the stack if they are)
786        final ArrayList<TaskView> childrenToRemove = new ArrayList<TaskView>();
787        final HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransforms =
788                new HashMap<TaskView, Pair<Integer, TaskViewTransform>>();
789        int duration = getExitTransformsForFilterAnimation(curTasks, curTaskTransforms, tasks,
790                taskTransforms, childViewTransforms, childrenToRemove, config);
791
792        // If all the current views are in the visible range of the new stack, then don't wait for
793        // views to animate out and animate all the new views into their place
794        final boolean unifyNewViewAnimation = childrenToRemove.isEmpty();
795        if (unifyNewViewAnimation) {
796            int inDuration = getEnterTransformsForFilterAnimation(tasks, taskTransforms,
797                    childViewTransforms, config);
798            duration = Math.max(duration, inDuration);
799        }
800
801        // Animate all the views to their final transforms
802        for (final TaskView tv : childViewTransforms.keySet()) {
803            Pair<Integer, TaskViewTransform> t = childViewTransforms.get(tv);
804            tv.animate().cancel();
805            tv.animate()
806                    .setStartDelay(t.first)
807                    .withEndAction(new Runnable() {
808                        @Override
809                        public void run() {
810                            childViewTransforms.remove(tv);
811                            if (childViewTransforms.isEmpty()) {
812                                // Return all the removed children to the view pool
813                                for (TaskView tv : childrenToRemove) {
814                                    mViewPool.returnViewToPool(tv);
815                                }
816
817                                if (!unifyNewViewAnimation) {
818                                    // For views that are not already visible, animate them in
819                                    childViewTransforms.clear();
820                                    int duration = getEnterTransformsForFilterAnimation(tasks,
821                                            taskTransforms, childViewTransforms, config);
822                                    for (final TaskView tv : childViewTransforms.keySet()) {
823                                        Pair<Integer, TaskViewTransform> t = childViewTransforms.get(tv);
824                                        tv.animate().setStartDelay(t.first);
825                                        tv.updateViewPropertiesToTaskTransform(null, t.second, duration);
826                                    }
827                                }
828                            }
829                        }
830                    });
831            tv.updateViewPropertiesToTaskTransform(null, t.second, duration);
832        }
833    }
834
835    @Override
836    public void onStackFiltered(TaskStack newStack, final ArrayList<Task> curTasks,
837                                Task filteredTask) {
838        // Close any open info panes
839        closeOpenInfoPanes();
840
841        // Stash the scroll and filtered task for us to restore to when we unfilter
842        mStashedScroll = getStackScroll();
843
844        // Calculate the current task transforms
845        ArrayList<TaskViewTransform> curTaskTransforms =
846                getStackTransforms(curTasks, getStackScroll(), null, true);
847
848        // Scroll the item to the top of the stack (sans-peek) rect so that we can see it better
849        updateMinMaxScroll(false);
850        float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height();
851        setStackScrollRaw((int) (newStack.indexOfTask(filteredTask) * overlapHeight));
852        boundScrollRaw();
853
854        // Compute the transforms of the items in the new stack after setting the new scroll
855        final ArrayList<Task> tasks = mStack.getTasks();
856        final ArrayList<TaskViewTransform> taskTransforms =
857                getStackTransforms(mStack.getTasks(), getStackScroll(), null, true);
858
859        // Animate
860        doFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms);
861    }
862
863    @Override
864    public void onStackUnfiltered(TaskStack newStack, final ArrayList<Task> curTasks) {
865        // Close any open info panes
866        closeOpenInfoPanes();
867
868        // Calculate the current task transforms
869        final ArrayList<TaskViewTransform> curTaskTransforms =
870                getStackTransforms(curTasks, getStackScroll(), null, true);
871
872        // Restore the stashed scroll
873        updateMinMaxScroll(false);
874        setStackScrollRaw(mStashedScroll);
875        boundScrollRaw();
876
877        // Compute the transforms of the items in the new stack after restoring the stashed scroll
878        final ArrayList<Task> tasks = mStack.getTasks();
879        final ArrayList<TaskViewTransform> taskTransforms =
880                getStackTransforms(tasks, getStackScroll(), null, true);
881
882        // Animate
883        doFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms);
884
885        // Clear the saved vars
886        mStashedScroll = 0;
887    }
888
889    /**** ViewPoolConsumer Implementation ****/
890
891    @Override
892    public TaskView createView(Context context) {
893        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|createPoolView]");
894        return (TaskView) mInflater.inflate(R.layout.recents_task_view, this, false);
895    }
896
897    @Override
898    public void prepareViewToEnterPool(TaskView tv) {
899        Task task = tv.getTask();
900        tv.resetViewProperties();
901        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|returnToPool]",
902                tv.getTask() + " tv: " + tv);
903
904        // Report that this tasks's data is no longer being used
905        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
906        loader.unloadTaskData(task);
907
908        // Detach the view from the hierarchy
909        detachViewFromParent(tv);
910
911        // Disable hw layers on this view
912        tv.disableHwLayers();
913    }
914
915    @Override
916    public void prepareViewToLeavePool(TaskView tv, Task prepareData, boolean isNewView) {
917        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|leavePool]",
918                "isNewView: " + isNewView);
919
920        // Setup and attach the view to the window
921        Task task = prepareData;
922        // We try and rebind the task (this MUST be done before the task filled)
923        tv.onTaskBound(task);
924        // Request that this tasks's data be filled
925        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
926        loader.loadTaskData(task);
927
928        // Find the index where this task should be placed in the children
929        int insertIndex = -1;
930        int childCount = getChildCount();
931        for (int i = 0; i < childCount; i++) {
932            Task tvTask = ((TaskView) getChildAt(i)).getTask();
933            if (mStack.containsTask(task) && (mStack.indexOfTask(task) < mStack.indexOfTask(tvTask))) {
934                insertIndex = i;
935                break;
936            }
937        }
938
939        // Add/attach the view to the hierarchy
940        Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "  [TaskStackView|insertIndex]",
941                "" + insertIndex);
942        if (isNewView) {
943            addView(tv, insertIndex);
944
945            // Set the callbacks and listeners for this new view
946            tv.setOnClickListener(this);
947            if (Constants.DebugFlags.App.EnableInfoPane) {
948                tv.setOnLongClickListener(this);
949            }
950            tv.setCallbacks(this);
951        } else {
952            attachViewToParent(tv, insertIndex, tv.getLayoutParams());
953        }
954
955        // Enable hw layers on this view if hw layers are enabled on the stack
956        if (mHwLayersRefCount > 0) {
957            tv.enableHwLayers();
958        }
959    }
960
961    @Override
962    public boolean hasPreferredData(TaskView tv, Task preferredData) {
963        return (tv.getTask() == preferredData);
964    }
965
966    /**** TaskViewCallbacks Implementation ****/
967
968    @Override
969    public void onTaskIconClicked(TaskView tv) {
970        Console.log(Constants.DebugFlags.UI.ClickEvents, "[TaskStack|Clicked|Icon]",
971                tv.getTask() + " is currently filtered: " + mStack.hasFilteredTasks(),
972                Console.AnsiCyan);
973        if (Constants.DebugFlags.App.EnableTaskFiltering) {
974            if (mStack.hasFilteredTasks()) {
975                mStack.unfilterTasks();
976            } else {
977                mStack.filterTasks(tv.getTask());
978            }
979        } else {
980            Console.logError(getContext(), "Task Filtering TBD");
981        }
982    }
983
984    @Override
985    public void onTaskInfoPanelShown(TaskView tv) {
986        // Do nothing
987    }
988
989    @Override
990    public void onTaskInfoPanelHidden(TaskView tv) {
991        // Unset the saved scroll
992        mLastInfoPaneStackScroll = -1;
993    }
994
995    @Override
996    public void onTaskAppInfoClicked(TaskView tv) {
997        if (mCb != null) {
998            mCb.onTaskAppInfoLaunched(tv.getTask());
999        }
1000    }
1001
1002    /**** View.OnClickListener Implementation ****/
1003
1004    @Override
1005    public void onClick(View v) {
1006        TaskView tv = (TaskView) v;
1007        Task task = tv.getTask();
1008        Console.log(Constants.DebugFlags.UI.ClickEvents, "[TaskStack|Clicked|Thumbnail]",
1009                task + " cb: " + mCb);
1010
1011        // Close any open info panes if the user taps on another task
1012        if (closeOpenInfoPanes()) {
1013            return;
1014        }
1015
1016        if (mCb != null) {
1017            mCb.onTaskLaunched(this, tv, mStack, task);
1018        }
1019    }
1020
1021    @Override
1022    public boolean onLongClick(View v) {
1023        if (!Constants.DebugFlags.App.EnableInfoPane) return false;
1024
1025        TaskView tv = (TaskView) v;
1026
1027        // Close any other task info panels if we launch another info pane
1028        closeOpenInfoPanes();
1029
1030        // Scroll the task view so that it is maximally visible
1031        float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height();
1032        int taskIndex = mStack.indexOfTask(tv.getTask());
1033        int curScroll = getStackScroll();
1034        int newScroll = (int) Math.max(mMinScroll, Math.min(mMaxScroll, taskIndex * overlapHeight));
1035        TaskViewTransform transform = getStackTransform(taskIndex, curScroll);
1036        Rect nonOverlapRect = new Rect(transform.rect);
1037        if (taskIndex < (mStack.getTaskCount() - 1)) {
1038            nonOverlapRect.bottom = nonOverlapRect.top + (int) overlapHeight;
1039        }
1040
1041        // XXX: Use HW Layers
1042        if (transform.t < 0f) {
1043            animateScroll(curScroll, newScroll, null);
1044        } else if (nonOverlapRect.bottom > mStackRectSansPeek.bottom) {
1045            // Check if we are out of bounds, if so, just scroll it in such that the bottom of the
1046            // task view is visible
1047            newScroll = curScroll - (mStackRectSansPeek.bottom - nonOverlapRect.bottom);
1048            animateScroll(curScroll, newScroll, null);
1049        }
1050        mLastInfoPaneStackScroll = newScroll;
1051
1052        // Show the info pane for this task view
1053        tv.showInfoPane(new Rect(0, 0, 0, (int) overlapHeight));
1054        return true;
1055    }
1056}
1057
1058/* Handles touch events */
1059class TaskStackViewTouchHandler implements SwipeHelper.Callback {
1060    static int INACTIVE_POINTER_ID = -1;
1061
1062    TaskStackView mSv;
1063    VelocityTracker mVelocityTracker;
1064
1065    boolean mIsScrolling;
1066
1067    int mInitialMotionX, mInitialMotionY;
1068    int mLastMotionX, mLastMotionY;
1069    int mActivePointerId = INACTIVE_POINTER_ID;
1070    TaskView mActiveTaskView = null;
1071
1072    int mTotalScrollMotion;
1073    int mMinimumVelocity;
1074    int mMaximumVelocity;
1075    // The scroll touch slop is used to calculate when we start scrolling
1076    int mScrollTouchSlop;
1077    // The page touch slop is used to calculate when we start swiping
1078    float mPagingTouchSlop;
1079
1080    SwipeHelper mSwipeHelper;
1081    boolean mInterceptedBySwipeHelper;
1082
1083    public TaskStackViewTouchHandler(Context context, TaskStackView sv) {
1084        ViewConfiguration configuration = ViewConfiguration.get(context);
1085        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
1086        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
1087        mScrollTouchSlop = configuration.getScaledTouchSlop();
1088        mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
1089        mSv = sv;
1090
1091
1092        float densityScale = context.getResources().getDisplayMetrics().density;
1093        mSwipeHelper = new SwipeHelper(SwipeHelper.X, this, densityScale, mPagingTouchSlop);
1094        mSwipeHelper.setMinAlpha(1f);
1095    }
1096
1097    /** Velocity tracker helpers */
1098    void initOrResetVelocityTracker() {
1099        if (mVelocityTracker == null) {
1100            mVelocityTracker = VelocityTracker.obtain();
1101        } else {
1102            mVelocityTracker.clear();
1103        }
1104    }
1105    void initVelocityTrackerIfNotExists() {
1106        if (mVelocityTracker == null) {
1107            mVelocityTracker = VelocityTracker.obtain();
1108        }
1109    }
1110    void recycleVelocityTracker() {
1111        if (mVelocityTracker != null) {
1112            mVelocityTracker.recycle();
1113            mVelocityTracker = null;
1114        }
1115    }
1116
1117    /** Returns the view at the specified coordinates */
1118    TaskView findViewAtPoint(int x, int y) {
1119        int childCount = mSv.getChildCount();
1120        for (int i = childCount - 1; i >= 0; i--) {
1121            TaskView tv = (TaskView) mSv.getChildAt(i);
1122            if (tv.getVisibility() == View.VISIBLE) {
1123                if (mSv.isTransformedTouchPointInView(x, y, tv)) {
1124                    return tv;
1125                }
1126            }
1127        }
1128        return null;
1129    }
1130
1131    /** Touch preprocessing for handling below */
1132    public boolean onInterceptTouchEvent(MotionEvent ev) {
1133        Console.log(Constants.DebugFlags.UI.TouchEvents,
1134                "[TaskStackViewTouchHandler|interceptTouchEvent]",
1135                Console.motionEventActionToString(ev.getAction()), Console.AnsiBlue);
1136
1137        // Return early if we have no children
1138        boolean hasChildren = (mSv.getChildCount() > 0);
1139        if (!hasChildren) {
1140            return false;
1141        }
1142
1143        // Pass through to swipe helper if we are swiping
1144        mInterceptedBySwipeHelper = mSwipeHelper.onInterceptTouchEvent(ev);
1145        if (mInterceptedBySwipeHelper) {
1146            return true;
1147        }
1148
1149        boolean wasScrolling = !mSv.mScroller.isFinished() ||
1150                (mSv.mScrollAnimator != null && mSv.mScrollAnimator.isRunning());
1151        int action = ev.getAction();
1152        switch (action & MotionEvent.ACTION_MASK) {
1153            case MotionEvent.ACTION_DOWN: {
1154                // Save the touch down info
1155                mInitialMotionX = mLastMotionX = (int) ev.getX();
1156                mInitialMotionY = mLastMotionY = (int) ev.getY();
1157                mActivePointerId = ev.getPointerId(0);
1158                mActiveTaskView = findViewAtPoint(mLastMotionX, mLastMotionY);
1159                // Stop the current scroll if it is still flinging
1160                mSv.abortScroller();
1161                mSv.abortBoundScrollAnimation();
1162                // Initialize the velocity tracker
1163                initOrResetVelocityTracker();
1164                mVelocityTracker.addMovement(ev);
1165                // Check if the scroller is finished yet
1166                mIsScrolling = !mSv.mScroller.isFinished();
1167                break;
1168            }
1169            case MotionEvent.ACTION_MOVE: {
1170                if (mActivePointerId == INACTIVE_POINTER_ID) break;
1171
1172                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
1173                int y = (int) ev.getY(activePointerIndex);
1174                int x = (int) ev.getX(activePointerIndex);
1175                if (Math.abs(y - mInitialMotionY) > mScrollTouchSlop) {
1176                    // Save the touch move info
1177                    mIsScrolling = true;
1178                    // Initialize the velocity tracker if necessary
1179                    initVelocityTrackerIfNotExists();
1180                    mVelocityTracker.addMovement(ev);
1181                    // Disallow parents from intercepting touch events
1182                    final ViewParent parent = mSv.getParent();
1183                    if (parent != null) {
1184                        parent.requestDisallowInterceptTouchEvent(true);
1185                    }
1186                    // Enable HW layers
1187                    mSv.addHwLayersRefCount("stackScroll");
1188                }
1189
1190                mLastMotionX = x;
1191                mLastMotionY = y;
1192                break;
1193            }
1194            case MotionEvent.ACTION_CANCEL:
1195            case MotionEvent.ACTION_UP: {
1196                // Animate the scroll back if we've cancelled
1197                mSv.animateBoundScroll();
1198                // Disable HW layers
1199                if (mIsScrolling) {
1200                    mSv.decHwLayersRefCount("stackScroll");
1201                }
1202                // Reset the drag state and the velocity tracker
1203                mIsScrolling = false;
1204                mActivePointerId = INACTIVE_POINTER_ID;
1205                mActiveTaskView = null;
1206                mTotalScrollMotion = 0;
1207                recycleVelocityTracker();
1208                break;
1209            }
1210        }
1211
1212        return wasScrolling || mIsScrolling;
1213    }
1214
1215    /** Handles touch events once we have intercepted them */
1216    public boolean onTouchEvent(MotionEvent ev) {
1217        Console.log(Constants.DebugFlags.UI.TouchEvents,
1218                "[TaskStackViewTouchHandler|touchEvent]",
1219                Console.motionEventActionToString(ev.getAction()), Console.AnsiBlue);
1220
1221        // Short circuit if we have no children
1222        boolean hasChildren = (mSv.getChildCount() > 0);
1223        if (!hasChildren) {
1224            return false;
1225        }
1226
1227        // Pass through to swipe helper if we are swiping
1228        if (mInterceptedBySwipeHelper && mSwipeHelper.onTouchEvent(ev)) {
1229            return true;
1230        }
1231
1232        // Update the velocity tracker
1233        initVelocityTrackerIfNotExists();
1234        mVelocityTracker.addMovement(ev);
1235
1236        int action = ev.getAction();
1237        switch (action & MotionEvent.ACTION_MASK) {
1238            case MotionEvent.ACTION_DOWN: {
1239                // Save the touch down info
1240                mInitialMotionX = mLastMotionX = (int) ev.getX();
1241                mInitialMotionY = mLastMotionY = (int) ev.getY();
1242                mActivePointerId = ev.getPointerId(0);
1243                mActiveTaskView = findViewAtPoint(mLastMotionX, mLastMotionY);
1244                // Stop the current scroll if it is still flinging
1245                mSv.abortScroller();
1246                mSv.abortBoundScrollAnimation();
1247                // Initialize the velocity tracker
1248                initOrResetVelocityTracker();
1249                mVelocityTracker.addMovement(ev);
1250                // Disallow parents from intercepting touch events
1251                final ViewParent parent = mSv.getParent();
1252                if (parent != null) {
1253                    parent.requestDisallowInterceptTouchEvent(true);
1254                }
1255                break;
1256            }
1257            case MotionEvent.ACTION_POINTER_DOWN: {
1258                final int index = ev.getActionIndex();
1259                mActivePointerId = ev.getPointerId(index);
1260                mLastMotionX = (int) ev.getX(index);
1261                mLastMotionY = (int) ev.getY(index);
1262                break;
1263            }
1264            case MotionEvent.ACTION_MOVE: {
1265                if (mActivePointerId == INACTIVE_POINTER_ID) break;
1266
1267                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
1268                int x = (int) ev.getX(activePointerIndex);
1269                int y = (int) ev.getY(activePointerIndex);
1270                int yTotal = Math.abs(y - mInitialMotionY);
1271                int deltaY = mLastMotionY - y;
1272                if (!mIsScrolling) {
1273                    if (yTotal > mScrollTouchSlop) {
1274                        mIsScrolling = true;
1275                        // Initialize the velocity tracker
1276                        initOrResetVelocityTracker();
1277                        mVelocityTracker.addMovement(ev);
1278                        // Disallow parents from intercepting touch events
1279                        final ViewParent parent = mSv.getParent();
1280                        if (parent != null) {
1281                            parent.requestDisallowInterceptTouchEvent(true);
1282                        }
1283                        // Enable HW layers
1284                        mSv.addHwLayersRefCount("stackScroll");
1285                    }
1286                }
1287                if (mIsScrolling) {
1288                    int curStackScroll = mSv.getStackScroll();
1289                    if (mSv.isScrollOutOfBounds(curStackScroll + deltaY)) {
1290                        // Scale the touch if we are overscrolling
1291                        deltaY /= Constants.Values.TaskStackView.TouchOverscrollScaleFactor;
1292                    }
1293                    mSv.setStackScroll(curStackScroll + deltaY);
1294                    if (mSv.isScrollOutOfBounds()) {
1295                        mVelocityTracker.clear();
1296                    }
1297                }
1298                mLastMotionX = x;
1299                mLastMotionY = y;
1300                mTotalScrollMotion += Math.abs(deltaY);
1301                break;
1302            }
1303            case MotionEvent.ACTION_UP: {
1304                final VelocityTracker velocityTracker = mVelocityTracker;
1305                velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1306                int velocity = (int) velocityTracker.getYVelocity(mActivePointerId);
1307
1308                if (mIsScrolling && (Math.abs(velocity) > mMinimumVelocity)) {
1309                    // Enable HW layers on the stack
1310                    mSv.addHwLayersRefCount("flingScroll");
1311                    int overscrollRange = (int) (Math.min(1f,
1312                            Math.abs((float) velocity / mMaximumVelocity)) *
1313                            Constants.Values.TaskStackView.TaskStackOverscrollRange);
1314
1315                    Console.log(Constants.DebugFlags.UI.TouchEvents,
1316                            "[TaskStackViewTouchHandler|fling]",
1317                            "scroll: " + mSv.getStackScroll() + " velocity: " + velocity +
1318                                    " maxVelocity: " + mMaximumVelocity +
1319                                    " overscrollRange: " + overscrollRange,
1320                            Console.AnsiGreen);
1321
1322                    // Fling scroll
1323                    mSv.mScroller.fling(0, mSv.getStackScroll(),
1324                            0, -velocity,
1325                            0, 0,
1326                            mSv.mMinScroll, mSv.mMaxScroll,
1327                            0, overscrollRange);
1328                    // Invalidate to kick off computeScroll
1329                    mSv.invalidate();
1330                } else if (mSv.isScrollOutOfBounds()) {
1331                    // Animate the scroll back into bounds
1332                    // XXX: Make this animation a function of the velocity OR distance
1333                    mSv.animateBoundScroll();
1334                }
1335
1336                if (mIsScrolling) {
1337                    // Disable HW layers
1338                    mSv.decHwLayersRefCount("stackScroll");
1339                }
1340                mActivePointerId = INACTIVE_POINTER_ID;
1341                mIsScrolling = false;
1342                mTotalScrollMotion = 0;
1343                recycleVelocityTracker();
1344                break;
1345            }
1346            case MotionEvent.ACTION_POINTER_UP: {
1347                int pointerIndex = ev.getActionIndex();
1348                int pointerId = ev.getPointerId(pointerIndex);
1349                if (pointerId == mActivePointerId) {
1350                    // Select a new active pointer id and reset the motion state
1351                    final int newPointerIndex = (pointerIndex == 0) ? 1 : 0;
1352                    mActivePointerId = ev.getPointerId(newPointerIndex);
1353                    mLastMotionX = (int) ev.getX(newPointerIndex);
1354                    mLastMotionY = (int) ev.getY(newPointerIndex);
1355                    mVelocityTracker.clear();
1356                }
1357                break;
1358            }
1359            case MotionEvent.ACTION_CANCEL: {
1360                if (mIsScrolling) {
1361                    // Disable HW layers
1362                    mSv.decHwLayersRefCount("stackScroll");
1363                }
1364                if (mSv.isScrollOutOfBounds()) {
1365                    // Animate the scroll back into bounds
1366                    // XXX: Make this animation a function of the velocity OR distance
1367                    mSv.animateBoundScroll();
1368                }
1369                mActivePointerId = INACTIVE_POINTER_ID;
1370                mIsScrolling = false;
1371                mTotalScrollMotion = 0;
1372                recycleVelocityTracker();
1373                break;
1374            }
1375        }
1376        return true;
1377    }
1378
1379    /**** SwipeHelper Implementation ****/
1380
1381    @Override
1382    public View getChildAtPosition(MotionEvent ev) {
1383        return findViewAtPoint((int) ev.getX(), (int) ev.getY());
1384    }
1385
1386    @Override
1387    public boolean canChildBeDismissed(View v) {
1388        return true;
1389    }
1390
1391    @Override
1392    public void onBeginDrag(View v) {
1393        // Enable HW layers
1394        mSv.addHwLayersRefCount("swipeBegin");
1395        // Disallow parents from intercepting touch events
1396        final ViewParent parent = mSv.getParent();
1397        if (parent != null) {
1398            parent.requestDisallowInterceptTouchEvent(true);
1399        }
1400        // If the info panel is currently showing on this view, then we need to dismiss it
1401        if (Constants.DebugFlags.App.EnableInfoPane) {
1402            TaskView tv = (TaskView) v;
1403            if (tv.isInfoPaneVisible()) {
1404                tv.hideInfoPane();
1405            }
1406        }
1407    }
1408
1409    @Override
1410    public void onChildDismissed(View v) {
1411        TaskView tv = (TaskView) v;
1412        Task task = tv.getTask();
1413        Activity activity = (Activity) mSv.getContext();
1414
1415        // Remove the task from the view
1416        mSv.mStack.removeTask(task);
1417
1418        // Remove any stored data from the loader
1419        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
1420        loader.deleteTaskData(task);
1421
1422        // Remove the task from activity manager
1423        RecentsTaskLoader.getInstance().getSystemServicesProxy().removeTask(tv.getTask().key.id);
1424
1425        // If there are no remaining tasks, then either unfilter the current stack, or just close
1426        // the activity if there are no filtered stacks
1427        if (mSv.mStack.getTaskCount() == 0) {
1428            boolean shouldFinishActivity = true;
1429            if (mSv.mStack.hasFilteredTasks()) {
1430                mSv.mStack.unfilterTasks();
1431                shouldFinishActivity = (mSv.mStack.getTaskCount() == 0);
1432            }
1433            if (shouldFinishActivity) {
1434                activity.finish();
1435            }
1436        }
1437
1438        // Disable HW layers
1439        mSv.decHwLayersRefCount("swipeComplete");
1440    }
1441
1442    @Override
1443    public void onSnapBackCompleted(View v) {
1444        // Do Nothing
1445    }
1446
1447    @Override
1448    public void onDragCancelled(View v) {
1449        // Disable HW layers
1450        mSv.decHwLayersRefCount("swipeCancelled");
1451    }
1452}
1453