TaskStackView.java revision 04400672962d2e12132f9465928cbf7615c147c4
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.ValueAnimator;
20import android.content.ComponentName;
21import android.content.Context;
22import android.graphics.Matrix;
23import android.graphics.Rect;
24import android.view.LayoutInflater;
25import android.view.MotionEvent;
26import android.view.View;
27import android.view.accessibility.AccessibilityEvent;
28import android.widget.FrameLayout;
29import com.android.systemui.R;
30import com.android.systemui.recents.Constants;
31import com.android.systemui.recents.RecentsConfiguration;
32import com.android.systemui.recents.misc.DozeTrigger;
33import com.android.systemui.recents.misc.SystemServicesProxy;
34import com.android.systemui.recents.misc.Utilities;
35import com.android.systemui.recents.model.RecentsPackageMonitor;
36import com.android.systemui.recents.model.RecentsTaskLoader;
37import com.android.systemui.recents.model.Task;
38import com.android.systemui.recents.model.TaskStack;
39
40import java.util.ArrayList;
41import java.util.HashMap;
42import java.util.HashSet;
43
44
45/* The visual representation of a task stack view */
46public class TaskStackView extends FrameLayout implements TaskStack.TaskStackCallbacks,
47        TaskView.TaskViewCallbacks, TaskStackViewScroller.TaskStackViewScrollerCallbacks,
48        ViewPool.ViewPoolConsumer<TaskView, Task>, RecentsPackageMonitor.PackageCallbacks {
49
50    /** The TaskView callbacks */
51    interface TaskStackViewCallbacks {
52        public void onTaskViewClicked(TaskStackView stackView, TaskView tv, TaskStack stack, Task t,
53                                      boolean lockToTask);
54        public void onTaskViewAppInfoClicked(Task t);
55        public void onTaskViewDismissed(Task t);
56        public void onAllTaskViewsDismissed();
57        public void onTaskStackFilterTriggered();
58        public void onTaskStackUnfilterTriggered();
59    }
60
61    RecentsConfiguration mConfig;
62
63    TaskStack mStack;
64    TaskStackViewLayoutAlgorithm mLayoutAlgorithm;
65    TaskStackViewFilterAlgorithm mFilterAlgorithm;
66    TaskStackViewScroller mStackScroller;
67    TaskStackViewTouchHandler mTouchHandler;
68    TaskStackViewCallbacks mCb;
69    ViewPool<TaskView, Task> mViewPool;
70    ArrayList<TaskViewTransform> mCurrentTaskTransforms = new ArrayList<TaskViewTransform>();
71    DozeTrigger mUIDozeTrigger;
72    DebugOverlayView mDebugOverlay;
73    Rect mTaskStackBounds = new Rect();
74    int mFocusedTaskIndex = -1;
75    int mPrevAccessibilityFocusedIndex = -1;
76
77    // Optimizations
78    int mStackViewsAnimationDuration;
79    boolean mStackViewsDirty = true;
80    boolean mStackViewsClipDirty = true;
81    boolean mAwaitingFirstLayout = true;
82    boolean mStartEnterAnimationRequestedAfterLayout;
83    boolean mStartEnterAnimationCompleted;
84    ViewAnimation.TaskViewEnterContext mStartEnterAnimationContext;
85    int[] mTmpVisibleRange = new int[2];
86    float[] mTmpCoord = new float[2];
87    Matrix mTmpMatrix = new Matrix();
88    Rect mTmpRect = new Rect();
89    TaskViewTransform mTmpTransform = new TaskViewTransform();
90    HashMap<Task, TaskView> mTmpTaskViewMap = new HashMap<Task, TaskView>();
91    LayoutInflater mInflater;
92
93    // A convenience update listener to request updating clipping of tasks
94    ValueAnimator.AnimatorUpdateListener mRequestUpdateClippingListener =
95            new ValueAnimator.AnimatorUpdateListener() {
96        @Override
97        public void onAnimationUpdate(ValueAnimator animation) {
98            requestUpdateStackViewsClip();
99        }
100    };
101
102    // A convenience runnable to return all views to the pool
103    Runnable mReturnAllViewsToPoolRunnable = new Runnable() {
104        @Override
105        public void run() {
106            int childCount = getChildCount();
107            for (int i = childCount - 1; i >= 0; i--) {
108                TaskView tv = (TaskView) getChildAt(i);
109                mViewPool.returnViewToPool(tv);
110                // Also hide the view since we don't need it anymore
111                tv.setVisibility(View.INVISIBLE);
112            }
113        }
114    };
115
116    public TaskStackView(Context context, TaskStack stack) {
117        super(context);
118        mConfig = RecentsConfiguration.getInstance();
119        mStack = stack;
120        mStack.setCallbacks(this);
121        mViewPool = new ViewPool<TaskView, Task>(context, this);
122        mInflater = LayoutInflater.from(context);
123        mLayoutAlgorithm = new TaskStackViewLayoutAlgorithm(mConfig);
124        mFilterAlgorithm = new TaskStackViewFilterAlgorithm(mConfig, this, mViewPool);
125        mStackScroller = new TaskStackViewScroller(context, mConfig, mLayoutAlgorithm);
126        mStackScroller.setCallbacks(this);
127        mTouchHandler = new TaskStackViewTouchHandler(context, this, mConfig, mStackScroller);
128        mUIDozeTrigger = new DozeTrigger(mConfig.taskBarDismissDozeDelaySeconds, new Runnable() {
129            @Override
130            public void run() {
131                // Show the task bar dismiss buttons
132                int childCount = getChildCount();
133                for (int i = 0; i < childCount; i++) {
134                    TaskView tv = (TaskView) getChildAt(i);
135                    tv.startNoUserInteractionAnimation();
136                }
137            }
138        });
139    }
140
141    /** Sets the callbacks */
142    void setCallbacks(TaskStackViewCallbacks cb) {
143        mCb = cb;
144    }
145
146    /** Sets the debug overlay */
147    public void setDebugOverlay(DebugOverlayView overlay) {
148        mDebugOverlay = overlay;
149    }
150
151    /** Requests that the views be synchronized with the model */
152    void requestSynchronizeStackViewsWithModel() {
153        requestSynchronizeStackViewsWithModel(0);
154    }
155    void requestSynchronizeStackViewsWithModel(int duration) {
156        if (!mStackViewsDirty) {
157            invalidate();
158            mStackViewsDirty = true;
159        }
160        if (mAwaitingFirstLayout) {
161            // Skip the animation if we are awaiting first layout
162            mStackViewsAnimationDuration = 0;
163        } else {
164            mStackViewsAnimationDuration = Math.max(mStackViewsAnimationDuration, duration);
165        }
166    }
167
168    /** Requests that the views clipping be updated. */
169    void requestUpdateStackViewsClip() {
170        if (!mStackViewsClipDirty) {
171            invalidate();
172            mStackViewsClipDirty = true;
173        }
174    }
175
176    /** Finds the child view given a specific task. */
177    public TaskView getChildViewForTask(Task t) {
178        int childCount = getChildCount();
179        for (int i = 0; i < childCount; i++) {
180            TaskView tv = (TaskView) getChildAt(i);
181            if (tv.getTask() == t) {
182                return tv;
183            }
184        }
185        return null;
186    }
187
188    /** Returns the stack algorithm for this task stack. */
189    public TaskStackViewLayoutAlgorithm getStackAlgorithm() {
190        return mLayoutAlgorithm;
191    }
192
193    /**
194     * Gets the stack transforms of a list of tasks, and returns the visible range of tasks.
195     */
196    private boolean updateStackTransforms(ArrayList<TaskViewTransform> taskTransforms,
197                                       ArrayList<Task> tasks,
198                                       float stackScroll,
199                                       int[] visibleRangeOut,
200                                       boolean boundTranslationsToRect) {
201        // XXX: We should be intelligent about where to look for the visible stack range using the
202        //      current stack scroll.
203        // XXX: We should log extra cases like the ones below where we don't expect to hit very often
204        // XXX: Print out approximately how many indices we have to go through to find the first visible transform
205
206        int taskTransformCount = taskTransforms.size();
207        int taskCount = tasks.size();
208        int frontMostVisibleIndex = -1;
209        int backMostVisibleIndex = -1;
210
211        // We can reuse the task transforms where possible to reduce object allocation
212        if (taskTransformCount < taskCount) {
213            // If there are less transforms than tasks, then add as many transforms as necessary
214            for (int i = taskTransformCount; i < taskCount; i++) {
215                taskTransforms.add(new TaskViewTransform());
216            }
217        } else if (taskTransformCount > taskCount) {
218            // If there are more transforms than tasks, then just subset the transform list
219            taskTransforms.subList(0, taskCount);
220        }
221
222        // Update the stack transforms
223        TaskViewTransform prevTransform = null;
224        for (int i = taskCount - 1; i >= 0; i--) {
225            TaskViewTransform transform = mLayoutAlgorithm.getStackTransform(tasks.get(i),
226                    stackScroll, taskTransforms.get(i), prevTransform);
227            if (transform.visible) {
228                if (frontMostVisibleIndex < 0) {
229                    frontMostVisibleIndex = i;
230                }
231                backMostVisibleIndex = i;
232            } else {
233                if (backMostVisibleIndex != -1) {
234                    // We've reached the end of the visible range, so going down the rest of the
235                    // stack, we can just reset the transforms accordingly
236                    while (i >= 0) {
237                        taskTransforms.get(i).reset();
238                        i--;
239                    }
240                    break;
241                }
242            }
243
244            if (boundTranslationsToRect) {
245                transform.translationY = Math.min(transform.translationY,
246                        mLayoutAlgorithm.mViewRect.bottom);
247            }
248            prevTransform = transform;
249        }
250        if (visibleRangeOut != null) {
251            visibleRangeOut[0] = frontMostVisibleIndex;
252            visibleRangeOut[1] = backMostVisibleIndex;
253        }
254        return frontMostVisibleIndex != -1 && backMostVisibleIndex != -1;
255    }
256
257    /**
258     * Gets the stack transforms of a list of tasks, and returns the visible range of tasks. This
259     * call is less optimal than calling updateStackTransforms directly.
260     */
261    private ArrayList<TaskViewTransform> getStackTransforms(ArrayList<Task> tasks,
262                                                            float stackScroll,
263                                                            int[] visibleRangeOut,
264                                                            boolean boundTranslationsToRect) {
265        ArrayList<TaskViewTransform> taskTransforms = new ArrayList<TaskViewTransform>();
266        updateStackTransforms(taskTransforms, tasks, stackScroll, visibleRangeOut,
267                boundTranslationsToRect);
268        return taskTransforms;
269    }
270
271    /** Synchronizes the views with the model */
272    boolean synchronizeStackViewsWithModel() {
273        if (mStackViewsDirty) {
274            RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
275            SystemServicesProxy ssp = loader.getSystemServicesProxy();
276
277            // Get all the task transforms
278            ArrayList<Task> tasks = mStack.getTasks();
279            float stackScroll = mStackScroller.getStackScroll();
280            int[] visibleRange = mTmpVisibleRange;
281            boolean isValidVisibleRange = updateStackTransforms(mCurrentTaskTransforms, tasks,
282                    stackScroll, visibleRange, false);
283            if (mDebugOverlay != null) {
284                mDebugOverlay.setText("vis[" + visibleRange[1] + "-" + visibleRange[0] + "]");
285            }
286
287            // Return all the invisible children to the pool
288            mTmpTaskViewMap.clear();
289            int childCount = getChildCount();
290            for (int i = childCount - 1; i >= 0; i--) {
291                TaskView tv = (TaskView) getChildAt(i);
292                Task task = tv.getTask();
293                int taskIndex = mStack.indexOfTask(task);
294                if (visibleRange[1] <= taskIndex && taskIndex <= visibleRange[0]) {
295                    mTmpTaskViewMap.put(task, tv);
296                } else {
297                    mViewPool.returnViewToPool(tv);
298                }
299            }
300
301            // Pick up all the newly visible children and update all the existing children
302            for (int i = visibleRange[0]; isValidVisibleRange && i >= visibleRange[1]; i--) {
303                Task task = tasks.get(i);
304                TaskViewTransform transform = mCurrentTaskTransforms.get(i);
305                TaskView tv = mTmpTaskViewMap.get(task);
306                int taskIndex = mStack.indexOfTask(task);
307
308                if (tv == null) {
309                    tv = mViewPool.pickUpViewFromPool(task, task);
310
311                    if (mStackViewsAnimationDuration > 0) {
312                        // For items in the list, put them in start animating them from the
313                        // approriate ends of the list where they are expected to appear
314                        if (Float.compare(transform.p, 0f) <= 0) {
315                            mLayoutAlgorithm.getStackTransform(0f, 0f, mTmpTransform, null);
316                        } else {
317                            mLayoutAlgorithm.getStackTransform(1f, 0f, mTmpTransform, null);
318                        }
319                        tv.updateViewPropertiesToTaskTransform(mTmpTransform, 0);
320                    }
321                }
322
323                // Animate the task into place
324                tv.updateViewPropertiesToTaskTransform(mCurrentTaskTransforms.get(taskIndex),
325                        mStackViewsAnimationDuration, mRequestUpdateClippingListener);
326
327                // Request accessibility focus on the next view if we removed the task
328                // that previously held accessibility focus
329                childCount = getChildCount();
330                if (childCount > 0 && ssp.isTouchExplorationEnabled()) {
331                    TaskView atv = (TaskView) getChildAt(childCount - 1);
332                    int indexOfTask = mStack.indexOfTask(atv.getTask());
333                    if (mPrevAccessibilityFocusedIndex != indexOfTask) {
334                        tv.requestAccessibilityFocus();
335                        mPrevAccessibilityFocusedIndex = indexOfTask;
336                    }
337                }
338            }
339
340            // Reset the request-synchronize params
341            mStackViewsAnimationDuration = 0;
342            mStackViewsDirty = false;
343            mStackViewsClipDirty = true;
344            return true;
345        }
346        return false;
347    }
348
349    /** Updates the clip for each of the task views. */
350    void clipTaskViews() {
351        // Update the clip on each task child
352        if (Constants.DebugFlags.App.EnableTaskStackClipping) {
353            int childCount = getChildCount();
354            for (int i = 0; i < childCount - 1; i++) {
355                TaskView tv = (TaskView) getChildAt(i);
356                TaskView nextTv = null;
357                TaskView tmpTv = null;
358                int clipBottom = 0;
359                if (tv.shouldClipViewInStack()) {
360                    // Find the next view to clip against
361                    int nextIndex = i;
362                    while (nextIndex < getChildCount()) {
363                        tmpTv = (TaskView) getChildAt(++nextIndex);
364                        if (tmpTv != null && tmpTv.shouldClipViewInStack()) {
365                            nextTv = tmpTv;
366                            break;
367                        }
368                    }
369
370                    // Clip against the next view, this is just an approximation since we are
371                    // stacked and we can make assumptions about the visibility of the this
372                    // task relative to the ones in front of it.
373                    if (nextTv != null) {
374                        // Map the top edge of next task view into the local space of the current
375                        // task view to find the clip amount in local space
376                        mTmpCoord[0] = mTmpCoord[1] = 0;
377                        Utilities.mapCoordInDescendentToSelf(nextTv, this, mTmpCoord, false);
378                        Utilities.mapCoordInSelfToDescendent(tv, this, mTmpCoord, mTmpMatrix);
379                        clipBottom = (int) Math.floor(tv.getMeasuredHeight() - mTmpCoord[1]
380                                - nextTv.getPaddingTop() - 1);
381                    }
382                }
383                tv.getViewBounds().setClipBottom(clipBottom);
384            }
385            if (getChildCount() > 0) {
386                // The front most task should never be clipped
387                TaskView tv = (TaskView) getChildAt(getChildCount() - 1);
388                tv.getViewBounds().setClipBottom(0);
389            }
390        }
391        mStackViewsClipDirty = false;
392    }
393
394    /** The stack insets to apply to the stack contents */
395    public void setStackInsetRect(Rect r) {
396        mTaskStackBounds.set(r);
397    }
398
399    /** Updates the min and max virtual scroll bounds */
400    void updateMinMaxScroll(boolean boundScrollToNewMinMax, boolean launchedWithAltTab,
401            boolean launchedFromHome) {
402        // Compute the min and max scroll values
403        mLayoutAlgorithm.computeMinMaxScroll(mStack.getTasks(), launchedWithAltTab, launchedFromHome);
404
405        // Debug logging
406        if (boundScrollToNewMinMax) {
407            mStackScroller.boundScroll();
408        }
409    }
410
411    /** Returns the scroller. */
412    public TaskStackViewScroller getScroller() {
413        return mStackScroller;
414    }
415
416    /** Focuses the task at the specified index in the stack */
417    void focusTask(int taskIndex, boolean scrollToNewPosition, final boolean animateFocusedState) {
418        // Return early if the task is already focused
419        if (taskIndex == mFocusedTaskIndex) return;
420
421        if (0 <= taskIndex && taskIndex < mStack.getTaskCount()) {
422            mFocusedTaskIndex = taskIndex;
423
424            // Focus the view if possible, otherwise, focus the view after we scroll into position
425            Task t = mStack.getTasks().get(taskIndex);
426            TaskView tv = getChildViewForTask(t);
427            Runnable postScrollRunnable = null;
428            if (tv != null) {
429                tv.setFocusedTask(animateFocusedState);
430            } else {
431                postScrollRunnable = new Runnable() {
432                    @Override
433                    public void run() {
434                        Task t = mStack.getTasks().get(mFocusedTaskIndex);
435                        TaskView tv = getChildViewForTask(t);
436                        if (tv != null) {
437                            tv.setFocusedTask(animateFocusedState);
438                        }
439                    }
440                };
441            }
442
443            // Scroll the view into position (just center it in the curve)
444            if (scrollToNewPosition) {
445                float newScroll = mLayoutAlgorithm.getStackScrollForTask(t) - 0.5f;
446                newScroll = mStackScroller.getBoundedStackScroll(newScroll);
447                mStackScroller.animateScroll(mStackScroller.getStackScroll(), newScroll, postScrollRunnable);
448            } else {
449                if (postScrollRunnable != null) {
450                    postScrollRunnable.run();
451                }
452            }
453
454        }
455    }
456
457    /**
458     * Ensures that there is a task focused, if nothign is focused, then we will use the task
459     * at the center of the visible stack.
460     */
461    public boolean ensureFocusedTask() {
462        if (mFocusedTaskIndex < 0) {
463            // If there is no task focused, then find the task that is closes to the center
464            // of the screen and use that as the currently focused task
465            int x = mLayoutAlgorithm.mStackVisibleRect.centerX();
466            int y = mLayoutAlgorithm.mStackVisibleRect.centerY();
467            int childCount = getChildCount();
468            for (int i = childCount - 1; i >= 0; i--) {
469                TaskView tv = (TaskView) getChildAt(i);
470                tv.getHitRect(mTmpRect);
471                if (mTmpRect.contains(x, y)) {
472                    mFocusedTaskIndex = mStack.indexOfTask(tv.getTask());
473                    break;
474                }
475            }
476            // If we can't find the center task, then use the front most index
477            if (mFocusedTaskIndex < 0 && childCount > 0) {
478                mFocusedTaskIndex = childCount - 1;
479            }
480        }
481        return mFocusedTaskIndex >= 0;
482    }
483
484    /**
485     * Focuses the next task in the stack.
486     * @param animateFocusedState determines whether to actually draw the highlight along with
487     *                            the change in focus, as well as whether to scroll to fit the
488     *                            task into view.
489     */
490    public void focusNextTask(boolean forward, boolean animateFocusedState) {
491        // Find the next index to focus
492        int numTasks = mStack.getTaskCount();
493        if (numTasks == 0) return;
494
495        int direction = (forward ? -1 : 1);
496        int newIndex = mFocusedTaskIndex + direction;
497        if (newIndex >= 0 && newIndex <= (numTasks - 1)) {
498            newIndex = Math.max(0, Math.min(numTasks - 1, newIndex));
499            focusTask(newIndex, true, animateFocusedState);
500        }
501    }
502
503    /** Dismisses the focused task. */
504    public void dismissFocusedTask() {
505        // Return early if there is no focused task index
506        if (mFocusedTaskIndex < 0) return;
507
508        Task t = mStack.getTasks().get(mFocusedTaskIndex);
509        TaskView tv = getChildViewForTask(t);
510        tv.dismissTask();
511    }
512
513    @Override
514    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
515        super.onInitializeAccessibilityEvent(event);
516        int childCount = getChildCount();
517        if (childCount > 0) {
518            TaskView backMostTask = (TaskView) getChildAt(0);
519            TaskView frontMostTask = (TaskView) getChildAt(childCount - 1);
520            event.setFromIndex(mStack.indexOfTask(backMostTask.getTask()));
521            event.setToIndex(mStack.indexOfTask(frontMostTask.getTask()));
522            event.setContentDescription(frontMostTask.getTask().activityLabel);
523        }
524        event.setItemCount(mStack.getTaskCount());
525        event.setScrollY(mStackScroller.mScroller.getCurrY());
526        event.setMaxScrollY(mStackScroller.progressToScrollRange(mLayoutAlgorithm.mMaxScrollP));
527    }
528
529    @Override
530    public boolean onInterceptTouchEvent(MotionEvent ev) {
531        return mTouchHandler.onInterceptTouchEvent(ev);
532    }
533
534    @Override
535    public boolean onTouchEvent(MotionEvent ev) {
536        return mTouchHandler.onTouchEvent(ev);
537    }
538
539    @Override
540    public boolean onGenericMotionEvent(MotionEvent ev) {
541        return mTouchHandler.onGenericMotionEvent(ev);
542    }
543
544    @Override
545    public void computeScroll() {
546        mStackScroller.computeScroll();
547        // Synchronize the views
548        synchronizeStackViewsWithModel();
549        clipTaskViews();
550        // Notify accessibility
551        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
552    }
553
554    /** Computes the stack and task rects */
555    public void computeRects(int windowWidth, int windowHeight, Rect taskStackBounds,
556            boolean launchedWithAltTab, boolean launchedFromHome) {
557        // Compute the rects in the stack algorithm
558        mLayoutAlgorithm.computeRects(windowWidth, windowHeight, taskStackBounds);
559
560        // Update the scroll bounds
561        updateMinMaxScroll(false, launchedWithAltTab, launchedFromHome);
562    }
563
564    /**
565     * This is ONLY used from AlternateRecentsComponent to update the dummy stack view for purposes
566     * of getting the task rect to animate to.
567     */
568    public void updateMinMaxScrollForStack(TaskStack stack, boolean launchedWithAltTab,
569            boolean launchedFromHome) {
570        mStack = stack;
571        updateMinMaxScroll(false, launchedWithAltTab, launchedFromHome);
572    }
573
574    /**
575     * This is called with the full window width and height to allow stack view children to
576     * perform the full screen transition down.
577     */
578    @Override
579    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
580        int width = MeasureSpec.getSize(widthMeasureSpec);
581        int height = MeasureSpec.getSize(heightMeasureSpec);
582
583        // Compute our stack/task rects
584        Rect taskStackBounds = new Rect(mTaskStackBounds);
585        taskStackBounds.bottom -= mConfig.systemInsets.bottom;
586        computeRects(width, height, taskStackBounds, mConfig.launchedWithAltTab,
587                mConfig.launchedFromHome);
588
589        // If this is the first layout, then scroll to the front of the stack and synchronize the
590        // stack views immediately to load all the views
591        if (mAwaitingFirstLayout) {
592            mStackScroller.setStackScrollToInitialState();
593            requestSynchronizeStackViewsWithModel();
594            synchronizeStackViewsWithModel();
595        }
596
597        // Measure each of the TaskViews
598        int childCount = getChildCount();
599        for (int i = 0; i < childCount; i++) {
600            TaskView tv = (TaskView) getChildAt(i);
601            if (tv.getBackground() != null) {
602                tv.getBackground().getPadding(mTmpRect);
603            } else {
604                mTmpRect.setEmpty();
605            }
606            tv.measure(
607                MeasureSpec.makeMeasureSpec(
608                        mLayoutAlgorithm.mTaskRect.width() + mTmpRect.left + mTmpRect.right,
609                        MeasureSpec.EXACTLY),
610                MeasureSpec.makeMeasureSpec(
611                        mLayoutAlgorithm.mTaskRect.height() + mTmpRect.top + mTmpRect.bottom,
612                        MeasureSpec.EXACTLY));
613        }
614
615        setMeasuredDimension(width, height);
616    }
617
618    /**
619     * This is called with the size of the space not including the top or right insets, or the
620     * search bar height in portrait (but including the search bar width in landscape, since we want
621     * to draw under it.
622     */
623    @Override
624    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
625        // Layout each of the children
626        int childCount = getChildCount();
627        for (int i = 0; i < childCount; i++) {
628            TaskView tv = (TaskView) getChildAt(i);
629            if (tv.getBackground() != null) {
630                tv.getBackground().getPadding(mTmpRect);
631            } else {
632                mTmpRect.setEmpty();
633            }
634            tv.layout(mLayoutAlgorithm.mTaskRect.left - mTmpRect.left,
635                    mLayoutAlgorithm.mTaskRect.top - mTmpRect.top,
636                    mLayoutAlgorithm.mTaskRect.right + mTmpRect.right,
637                    mLayoutAlgorithm.mTaskRect.bottom + mTmpRect.bottom);
638        }
639
640        if (mAwaitingFirstLayout) {
641            mAwaitingFirstLayout = false;
642            onFirstLayout();
643        }
644    }
645
646    /** Handler for the first layout. */
647    void onFirstLayout() {
648        int offscreenY = mLayoutAlgorithm.mViewRect.bottom -
649                (mLayoutAlgorithm.mTaskRect.top - mLayoutAlgorithm.mViewRect.top);
650
651        // Find the launch target task
652        Task launchTargetTask = null;
653        int childCount = getChildCount();
654        for (int i = childCount - 1; i >= 0; i--) {
655            TaskView tv = (TaskView) getChildAt(i);
656            Task task = tv.getTask();
657            if (task.isLaunchTarget) {
658                launchTargetTask = task;
659                break;
660            }
661        }
662
663        // Prepare the first view for its enter animation
664        for (int i = childCount - 1; i >= 0; i--) {
665            TaskView tv = (TaskView) getChildAt(i);
666            Task task = tv.getTask();
667            boolean occludesLaunchTarget = (launchTargetTask != null) &&
668                    launchTargetTask.group.isTaskAboveTask(task, launchTargetTask);
669            tv.prepareEnterRecentsAnimation(task.isLaunchTarget, occludesLaunchTarget, offscreenY);
670        }
671
672        // If the enter animation started already and we haven't completed a layout yet, do the
673        // enter animation now
674        if (mStartEnterAnimationRequestedAfterLayout) {
675            startEnterRecentsAnimation(mStartEnterAnimationContext);
676            mStartEnterAnimationRequestedAfterLayout = false;
677            mStartEnterAnimationContext = null;
678        }
679
680        // When Alt-Tabbing, we scroll to and focus the previous task
681        if (mConfig.launchedWithAltTab) {
682            if (mConfig.launchedFromHome) {
683                focusTask(Math.max(0, mStack.getTaskCount() - 1), false, true);
684            } else {
685                focusTask(Math.max(0, mStack.getTaskCount() - 2), false, true);
686            }
687        }
688    }
689
690    /** Requests this task stacks to start it's enter-recents animation */
691    public void startEnterRecentsAnimation(ViewAnimation.TaskViewEnterContext ctx) {
692        // If we are still waiting to layout, then just defer until then
693        if (mAwaitingFirstLayout) {
694            mStartEnterAnimationRequestedAfterLayout = true;
695            mStartEnterAnimationContext = ctx;
696            return;
697        }
698
699        if (mStack.getTaskCount() > 0) {
700            // Find the launch target task
701            Task launchTargetTask = null;
702            int childCount = getChildCount();
703            for (int i = childCount - 1; i >= 0; i--) {
704                TaskView tv = (TaskView) getChildAt(i);
705                Task task = tv.getTask();
706                if (task.isLaunchTarget) {
707                    launchTargetTask = task;
708                    break;
709                }
710            }
711
712            // Animate all the task views into view
713            for (int i = childCount - 1; i >= 0; i--) {
714                TaskView tv = (TaskView) getChildAt(i);
715                Task task = tv.getTask();
716                ctx.currentTaskTransform = new TaskViewTransform();
717                ctx.currentStackViewIndex = i;
718                ctx.currentStackViewCount = childCount;
719                ctx.currentTaskRect = mLayoutAlgorithm.mTaskRect;
720                ctx.currentTaskOccludesLaunchTarget = (launchTargetTask != null) &&
721                        launchTargetTask.group.isTaskAboveTask(task, launchTargetTask);
722                ctx.updateListener = mRequestUpdateClippingListener;
723                mLayoutAlgorithm.getStackTransform(task, mStackScroller.getStackScroll(), ctx.currentTaskTransform, null);
724                tv.startEnterRecentsAnimation(ctx);
725            }
726
727            // Add a runnable to the post animation ref counter to clear all the views
728            ctx.postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
729                @Override
730                public void run() {
731                    mStartEnterAnimationCompleted = true;
732                    // Start dozing
733                    mUIDozeTrigger.startDozing();
734                    // Focus the first view if accessibility is enabled
735                    RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
736                    SystemServicesProxy ssp = loader.getSystemServicesProxy();
737                    int childCount = getChildCount();
738                    if (childCount > 0 && ssp.isTouchExplorationEnabled()) {
739                        TaskView tv = ((TaskView) getChildAt(childCount - 1));
740                        tv.requestAccessibilityFocus();
741                        mPrevAccessibilityFocusedIndex = mStack.indexOfTask(tv.getTask());
742                    }
743                }
744            });
745        }
746    }
747
748    /** Requests this task stacks to start it's exit-recents animation. */
749    public void startExitToHomeAnimation(ViewAnimation.TaskViewExitContext ctx) {
750        // Stop any scrolling
751        mStackScroller.stopScroller();
752        mStackScroller.stopBoundScrollAnimation();
753        // Animate all the task views out of view
754        ctx.offscreenTranslationY = mLayoutAlgorithm.mViewRect.bottom -
755                (mLayoutAlgorithm.mTaskRect.top - mLayoutAlgorithm.mViewRect.top);
756        int childCount = getChildCount();
757        for (int i = 0; i < childCount; i++) {
758            TaskView tv = (TaskView) getChildAt(i);
759            tv.startExitToHomeAnimation(ctx);
760        }
761
762        // Add a runnable to the post animation ref counter to clear all the views
763        ctx.postAnimationTrigger.addLastDecrementRunnable(mReturnAllViewsToPoolRunnable);
764    }
765
766    /** Animates a task view in this stack as it launches. */
767    public void startLaunchTaskAnimation(TaskView tv, Runnable r, boolean lockToTask) {
768        Task launchTargetTask = tv.getTask();
769        int childCount = getChildCount();
770        for (int i = 0; i < childCount; i++) {
771            TaskView t = (TaskView) getChildAt(i);
772            if (t == tv) {
773                t.setClipViewInStack(false);
774                t.startLaunchTaskAnimation(r, true, true, lockToTask);
775            } else {
776                boolean occludesLaunchTarget = launchTargetTask.group.isTaskAboveTask(t.getTask(),
777                        launchTargetTask);
778                t.startLaunchTaskAnimation(null, false, occludesLaunchTarget, lockToTask);
779            }
780        }
781    }
782
783    public boolean isTransformedTouchPointInView(float x, float y, View child) {
784        return isTransformedTouchPointInView(x, y, child, null);
785    }
786
787    /** Pokes the dozer on user interaction. */
788    void onUserInteraction() {
789        // Poke the doze trigger if it is dozing
790        mUIDozeTrigger.poke();
791    }
792
793    /**** TaskStackCallbacks Implementation ****/
794
795    @Override
796    public void onStackTaskAdded(TaskStack stack, Task t) {
797        requestSynchronizeStackViewsWithModel();
798    }
799
800    @Override
801    public void onStackTaskRemoved(TaskStack stack, Task removedTask, Task newFrontMostTask) {
802        // Remove the view associated with this task, we can't rely on updateTransforms
803        // to work here because the task is no longer in the list
804        TaskView tv = getChildViewForTask(removedTask);
805        if (tv != null) {
806            mViewPool.returnViewToPool(tv);
807        }
808
809        // Notify the callback that we've removed the task and it can clean up after it
810        mCb.onTaskViewDismissed(removedTask);
811
812        // Get the stack scroll of the task to anchor to (since we are removing something, the front
813        // most task will be our anchor task)
814        Task anchorTask = null;
815        float prevAnchorTaskScroll = 0;
816        boolean pullStackForward = stack.getTaskCount() > 0;
817        if (pullStackForward) {
818            anchorTask = mStack.getFrontMostTask();
819            prevAnchorTaskScroll = mLayoutAlgorithm.getStackScrollForTask(anchorTask);
820        }
821
822        // Update the min/max scroll and animate other task views into their new positions
823        updateMinMaxScroll(true, mConfig.launchedWithAltTab, mConfig.launchedFromHome);
824
825        // Offset the stack by as much as the anchor task would otherwise move back
826        if (pullStackForward) {
827            float anchorTaskScroll = mLayoutAlgorithm.getStackScrollForTask(anchorTask);
828            mStackScroller.setStackScroll(mStackScroller.getStackScroll() + (anchorTaskScroll
829                    - prevAnchorTaskScroll));
830            mStackScroller.boundScroll();
831        }
832
833        // Animate all the tasks into place
834        requestSynchronizeStackViewsWithModel(200);
835
836        // Update the new front most task
837        if (newFrontMostTask != null) {
838            TaskView frontTv = getChildViewForTask(newFrontMostTask);
839            if (frontTv != null) {
840                frontTv.onTaskBound(newFrontMostTask);
841                frontTv.fadeInActionButton(false);
842            }
843        }
844
845        // If there are no remaining tasks, then either unfilter the current stack, or just close
846        // the activity if there are no filtered stacks
847        if (mStack.getTaskCount() == 0) {
848            boolean shouldFinishActivity = true;
849            if (mStack.hasFilteredTasks()) {
850                mStack.unfilterTasks();
851                shouldFinishActivity = (mStack.getTaskCount() == 0);
852            }
853            if (shouldFinishActivity) {
854                mCb.onAllTaskViewsDismissed();
855            }
856        }
857    }
858
859    @Override
860    public void onStackFiltered(TaskStack newStack, final ArrayList<Task> curTasks,
861                                Task filteredTask) {
862        /*
863        // Stash the scroll and filtered task for us to restore to when we unfilter
864        mStashedScroll = getStackScroll();
865
866        // Calculate the current task transforms
867        ArrayList<TaskViewTransform> curTaskTransforms =
868                getStackTransforms(curTasks, getStackScroll(), null, true);
869
870        // Update the task offsets
871        mLayoutAlgorithm.updateTaskOffsets(mStack.getTasks());
872
873        // Scroll the item to the top of the stack (sans-peek) rect so that we can see it better
874        updateMinMaxScroll(false);
875        float overlapHeight = mLayoutAlgorithm.getTaskOverlapHeight();
876        setStackScrollRaw((int) (newStack.indexOfTask(filteredTask) * overlapHeight));
877        boundScrollRaw();
878
879        // Compute the transforms of the items in the new stack after setting the new scroll
880        final ArrayList<Task> tasks = mStack.getTasks();
881        final ArrayList<TaskViewTransform> taskTransforms =
882                getStackTransforms(mStack.getTasks(), getStackScroll(), null, true);
883
884        // Animate
885        mFilterAlgorithm.startFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms);
886
887        // Notify any callbacks
888        mCb.onTaskStackFilterTriggered();
889        */
890    }
891
892    @Override
893    public void onStackUnfiltered(TaskStack newStack, final ArrayList<Task> curTasks) {
894        /*
895        // Calculate the current task transforms
896        final ArrayList<TaskViewTransform> curTaskTransforms =
897                getStackTransforms(curTasks, getStackScroll(), null, true);
898
899        // Update the task offsets
900        mLayoutAlgorithm.updateTaskOffsets(mStack.getTasks());
901
902        // Restore the stashed scroll
903        updateMinMaxScroll(false);
904        setStackScrollRaw(mStashedScroll);
905        boundScrollRaw();
906
907        // Compute the transforms of the items in the new stack after restoring the stashed scroll
908        final ArrayList<Task> tasks = mStack.getTasks();
909        final ArrayList<TaskViewTransform> taskTransforms =
910                getStackTransforms(tasks, getStackScroll(), null, true);
911
912        // Animate
913        mFilterAlgorithm.startFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms);
914
915        // Clear the saved vars
916        mStashedScroll = 0;
917
918        // Notify any callbacks
919        mCb.onTaskStackUnfilterTriggered();
920        */
921    }
922
923    /**** ViewPoolConsumer Implementation ****/
924
925    @Override
926    public TaskView createView(Context context) {
927        return (TaskView) mInflater.inflate(R.layout.recents_task_view, this, false);
928    }
929
930    @Override
931    public void prepareViewToEnterPool(TaskView tv) {
932        Task task = tv.getTask();
933
934        // Clear the accessibility focus for that view
935        if (tv.isAccessibilityFocused()) {
936            tv.clearAccessibilityFocus();
937        }
938
939        // Report that this tasks's data is no longer being used
940        RecentsTaskLoader.getInstance().unloadTaskData(task);
941
942        // Detach the view from the hierarchy
943        detachViewFromParent(tv);
944
945        // Reset the view properties
946        tv.resetViewProperties();
947    }
948
949    @Override
950    public void prepareViewToLeavePool(TaskView tv, Task task, boolean isNewView) {
951        // Rebind the task and request that this task's data be filled into the TaskView
952        tv.onTaskBound(task);
953
954        // Load the task data
955        RecentsTaskLoader.getInstance().loadTaskData(task);
956
957        // Sanity check, the task view should always be clipping against the stack at this point,
958        // but just in case, re-enable it here
959        tv.setClipViewInStack(true);
960
961        // If the doze trigger has already fired, then update the state for this task view
962        if (mUIDozeTrigger.hasTriggered()) {
963            tv.setNoUserInteractionState();
964        }
965
966        // If we've finished the start animation, then ensure we always enable the focus animations
967        if (mStartEnterAnimationCompleted) {
968            tv.enableFocusAnimations();
969        }
970
971        // Find the index where this task should be placed in the stack
972        int insertIndex = -1;
973        int taskIndex = mStack.indexOfTask(task);
974        if (taskIndex != -1) {
975            int childCount = getChildCount();
976            for (int i = 0; i < childCount; i++) {
977                Task tvTask = ((TaskView) getChildAt(i)).getTask();
978                if (taskIndex < mStack.indexOfTask(tvTask)) {
979                    insertIndex = i;
980                    break;
981                }
982            }
983        }
984
985        // Add/attach the view to the hierarchy
986        if (isNewView) {
987            addView(tv, insertIndex);
988
989            // Set the callbacks and listeners for this new view
990            tv.setTouchEnabled(true);
991            tv.setCallbacks(this);
992        } else {
993            attachViewToParent(tv, insertIndex, tv.getLayoutParams());
994        }
995    }
996
997    @Override
998    public boolean hasPreferredData(TaskView tv, Task preferredData) {
999        return (tv.getTask() == preferredData);
1000    }
1001
1002    /**** TaskViewCallbacks Implementation ****/
1003
1004    @Override
1005    public void onTaskViewAppIconClicked(TaskView tv) {
1006        if (Constants.DebugFlags.App.EnableTaskFiltering) {
1007            if (mStack.hasFilteredTasks()) {
1008                mStack.unfilterTasks();
1009            } else {
1010                mStack.filterTasks(tv.getTask());
1011            }
1012        }
1013    }
1014
1015    @Override
1016    public void onTaskViewAppInfoClicked(TaskView tv) {
1017        if (mCb != null) {
1018            mCb.onTaskViewAppInfoClicked(tv.getTask());
1019        }
1020    }
1021
1022    @Override
1023    public void onTaskViewClicked(TaskView tv, Task task, boolean lockToTask) {
1024        // Cancel any doze triggers
1025        mUIDozeTrigger.stopDozing();
1026
1027        if (mCb != null) {
1028            mCb.onTaskViewClicked(this, tv, mStack, task, lockToTask);
1029        }
1030    }
1031
1032    @Override
1033    public void onTaskViewDismissed(TaskView tv) {
1034        Task task = tv.getTask();
1035        int taskIndex = mStack.indexOfTask(task);
1036        boolean taskWasFocused = tv.isFocusedTask();
1037        // Announce for accessibility
1038        tv.announceForAccessibility(getContext().getString(R.string.accessibility_recents_item_dismissed,
1039                tv.getTask().activityLabel));
1040        // Remove the task from the view
1041        mStack.removeTask(task);
1042        // If the dismissed task was focused, then we should focus the new task in the same index
1043        if (taskWasFocused) {
1044            ArrayList<Task> tasks = mStack.getTasks();
1045            int nextTaskIndex = Math.min(tasks.size() - 1, taskIndex - 1);
1046            if (nextTaskIndex >= 0) {
1047                Task nextTask = tasks.get(nextTaskIndex);
1048                TaskView nextTv = getChildViewForTask(nextTask);
1049                if (nextTv != null) {
1050                    // Focus the next task, and only animate the visible state if we are launched
1051                    // from Alt-Tab
1052                    nextTv.setFocusedTask(mConfig.launchedWithAltTab);
1053                }
1054            }
1055        }
1056    }
1057
1058    @Override
1059    public void onTaskViewClipStateChanged(TaskView tv) {
1060        if (!mStackViewsDirty) {
1061            invalidate();
1062        }
1063    }
1064
1065    @Override
1066    public void onTaskViewFocusChanged(TaskView tv, boolean focused) {
1067        if (focused) {
1068            mFocusedTaskIndex = mStack.indexOfTask(tv.getTask());
1069        }
1070    }
1071
1072    /**** TaskStackViewScroller.TaskStackViewScrollerCallbacks ****/
1073
1074    @Override
1075    public void onScrollChanged(float p) {
1076        mUIDozeTrigger.poke();
1077        requestSynchronizeStackViewsWithModel();
1078        postInvalidateOnAnimation();
1079    }
1080
1081    /**** RecentsPackageMonitor.PackageCallbacks Implementation ****/
1082
1083    @Override
1084    public void onPackagesChanged(RecentsPackageMonitor monitor, String packageName, int userId) {
1085        // Compute which components need to be removed
1086        HashSet<ComponentName> removedComponents = monitor.computeComponentsRemoved(
1087                mStack.getTaskKeys(), packageName, userId);
1088
1089        // For other tasks, just remove them directly if they no longer exist
1090        ArrayList<Task> tasks = mStack.getTasks();
1091        for (int i = tasks.size() - 1; i >= 0; i--) {
1092            final Task t = tasks.get(i);
1093            if (removedComponents.contains(t.key.baseIntent.getComponent())) {
1094                TaskView tv = getChildViewForTask(t);
1095                if (tv != null) {
1096                    // For visible children, defer removing the task until after the animation
1097                    tv.startDeleteTaskAnimation(new Runnable() {
1098                        @Override
1099                        public void run() {
1100                            mStack.removeTask(t);
1101                        }
1102                    });
1103                } else {
1104                    // Otherwise, remove the task from the stack immediately
1105                    mStack.removeTask(t);
1106                }
1107            }
1108        }
1109    }
1110}
1111