RecentsView.java revision 5da4347b41b105dc6c6c01bf2810af3ce3013229
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.app.ActivityManager;
20import android.app.ActivityOptions;
21import android.content.Context;
22import android.graphics.Bitmap;
23import android.graphics.Canvas;
24import android.graphics.Rect;
25import android.graphics.drawable.Drawable;
26import android.os.Bundle;
27import android.os.IRemoteCallback;
28import android.os.RemoteException;
29import android.util.ArraySet;
30import android.util.AttributeSet;
31import android.util.Log;
32import android.util.SparseArray;
33import android.view.AppTransitionAnimationSpec;
34import android.view.LayoutInflater;
35import android.view.MotionEvent;
36import android.view.View;
37import android.view.WindowInsets;
38import android.view.WindowManagerGlobal;
39import android.view.animation.AnimationUtils;
40import android.view.animation.Interpolator;
41import android.widget.FrameLayout;
42import com.android.internal.logging.MetricsLogger;
43import com.android.systemui.R;
44import com.android.systemui.recents.Constants;
45import com.android.systemui.recents.Recents;
46import com.android.systemui.recents.RecentsActivity;
47import com.android.systemui.recents.RecentsActivityLaunchState;
48import com.android.systemui.recents.RecentsAppWidgetHostView;
49import com.android.systemui.recents.RecentsConfiguration;
50import com.android.systemui.recents.events.EventBus;
51import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
52import com.android.systemui.recents.events.component.ScreenPinningRequestEvent;
53import com.android.systemui.recents.events.ui.DismissTaskViewEvent;
54import com.android.systemui.recents.events.ui.dragndrop.DragDockStateChangedEvent;
55import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
56import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
57import com.android.systemui.recents.misc.SystemServicesProxy;
58import com.android.systemui.recents.model.Task;
59import com.android.systemui.recents.model.TaskStack;
60
61import java.util.ArrayList;
62import java.util.List;
63
64import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
65import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
66import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
67
68/**
69 * This view is the the top level layout that contains TaskStacks (which are laid out according
70 * to their SpaceNode bounds.
71 */
72public class RecentsView extends FrameLayout implements TaskStackView.TaskStackViewCallbacks {
73
74    private static final String TAG = "RecentsView";
75    private static final boolean DEBUG = false;
76
77    private static final boolean ADD_HEADER_BITMAP = true;
78    private int mStackViewVisibility = View.VISIBLE;
79
80    /** The RecentsView callbacks */
81    public interface RecentsViewCallbacks {
82        public void onTaskViewClicked();
83        public void onTaskLaunchFailed();
84        public void onAllTaskViewsDismissed();
85        public void runAfterPause(Runnable r);
86    }
87
88    LayoutInflater mInflater;
89
90    ArrayList<TaskStack> mStacks;
91    TaskStackView mTaskStackView;
92    RecentsAppWidgetHostView mSearchBar;
93    RecentsViewCallbacks mCb;
94
95    RecentsViewTouchHandler mTouchHandler;
96    DragView mDragView;
97    TaskStack.DockState[] mVisibleDockStates = {
98            TaskStack.DockState.LEFT,
99            TaskStack.DockState.TOP,
100            TaskStack.DockState.RIGHT,
101            TaskStack.DockState.BOTTOM,
102    };
103
104    Interpolator mFastOutSlowInInterpolator;
105
106    Rect mSystemInsets = new Rect();
107
108    public RecentsView(Context context) {
109        super(context);
110    }
111
112    public RecentsView(Context context, AttributeSet attrs) {
113        this(context, attrs, 0);
114    }
115
116    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr) {
117        this(context, attrs, defStyleAttr, 0);
118    }
119
120    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
121        super(context, attrs, defStyleAttr, defStyleRes);
122        setWillNotDraw(false);
123        mInflater = LayoutInflater.from(context);
124        mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context,
125                com.android.internal.R.interpolator.fast_out_slow_in);
126        mTouchHandler = new RecentsViewTouchHandler(this);
127    }
128
129    /** Sets the callbacks */
130    public void setCallbacks(RecentsViewCallbacks cb) {
131        mCb = cb;
132    }
133
134    /** Set/get the bsp root node */
135    public void setTaskStack(TaskStack stack) {
136        RecentsConfiguration config = Recents.getConfiguration();
137        if (config.getLaunchState().launchedReuseTaskStackViews) {
138            if (mTaskStackView != null) {
139                // If onRecentsHidden is not triggered, we need to the stack view again here
140                mTaskStackView.reset();
141                mTaskStackView.setStack(stack);
142            } else {
143                mTaskStackView = new TaskStackView(getContext(), stack);
144                mTaskStackView.setCallbacks(this);
145                addView(mTaskStackView);
146            }
147        } else {
148            if (mTaskStackView != null) {
149                removeView(mTaskStackView);
150            }
151            mTaskStackView = new TaskStackView(getContext(), stack);
152            mTaskStackView.setCallbacks(this);
153            addView(mTaskStackView);
154        }
155        mTaskStackView.setVisibility(mStackViewVisibility);
156
157        // Trigger a new layout
158        requestLayout();
159    }
160
161    /** Gets the next task in the stack - or if the last - the top task */
162    public Task getNextTaskOrTopTask(Task taskToSearch) {
163        Task returnTask = null;
164        boolean found = false;
165        if (mTaskStackView != null) {
166            TaskStack stack = mTaskStackView.getStack();
167            ArrayList<Task> taskList = stack.getTasks();
168            // Iterate the stack views and try and find the focused task
169            for (int j = taskList.size() - 1; j >= 0; --j) {
170                Task task = taskList.get(j);
171                // Return the next task in the line.
172                if (found)
173                    return task;
174                // Remember the first possible task as the top task.
175                if (returnTask == null)
176                    returnTask = task;
177                if (task == taskToSearch)
178                    found = true;
179            }
180        }
181        return returnTask;
182    }
183
184    /** Launches the focused task from the first stack if possible */
185    public boolean launchFocusedTask() {
186        if (mTaskStackView != null) {
187            TaskStack stack = mTaskStackView.getStack();
188            // Iterate the stack views and try and find the focused task
189            List<TaskView> taskViews = mTaskStackView.getTaskViews();
190            int taskViewCount = taskViews.size();
191            for (int j = 0; j < taskViewCount; j++) {
192                TaskView tv = taskViews.get(j);
193                Task task = tv.getTask();
194                if (tv.isFocusedTask()) {
195                    onTaskViewClicked(mTaskStackView, tv, stack, task, false, false, null,
196                            INVALID_STACK_ID);
197                    return true;
198                }
199            }
200        }
201        return false;
202    }
203
204    /** Launches a given task. */
205    public boolean launchTask(Task task, Rect taskBounds, int destinationStack) {
206        if (mTaskStackView != null) {
207            TaskStack stack = mTaskStackView.getStack();
208            // Iterate the stack views and try and find the given task.
209            List<TaskView> taskViews = mTaskStackView.getTaskViews();
210            int taskViewCount = taskViews.size();
211            for (int j = 0; j < taskViewCount; j++) {
212                TaskView tv = taskViews.get(j);
213                if (tv.getTask() == task) {
214                    onTaskViewClicked(mTaskStackView, tv, stack, task, false, taskBounds != null,
215                            taskBounds, destinationStack);
216                    return true;
217                }
218            }
219        }
220        return false;
221    }
222
223    /** Requests all task stacks to start their enter-recents animation */
224    public void startEnterRecentsAnimation(ViewAnimation.TaskViewEnterContext ctx) {
225        // We have to increment/decrement the post animation trigger in case there are no children
226        // to ensure that it runs
227        ctx.postAnimationTrigger.increment();
228        if (mTaskStackView != null) {
229            mTaskStackView.startEnterRecentsAnimation(ctx);
230        }
231        ctx.postAnimationTrigger.decrement();
232    }
233
234    /** Requests all task stacks to start their exit-recents animation */
235    public void startExitToHomeAnimation(ViewAnimation.TaskViewExitContext ctx) {
236        // We have to increment/decrement the post animation trigger in case there are no children
237        // to ensure that it runs
238        ctx.postAnimationTrigger.increment();
239        if (mTaskStackView != null) {
240            mTaskStackView.startExitToHomeAnimation(ctx);
241        }
242        ctx.postAnimationTrigger.decrement();
243
244        // Notify of the exit animation
245        EventBus.getDefault().send(new DismissRecentsToHomeAnimationStarted());
246    }
247
248    /** Adds the search bar */
249    public void setSearchBar(RecentsAppWidgetHostView searchBar) {
250        // Remove the previous search bar if one exists
251        if (mSearchBar != null && indexOfChild(mSearchBar) > -1) {
252            removeView(mSearchBar);
253        }
254        // Add the new search bar
255        if (searchBar != null) {
256            mSearchBar = searchBar;
257            addView(mSearchBar);
258        }
259    }
260
261    /** Returns whether there is currently a search bar */
262    public boolean hasValidSearchBar() {
263        return mSearchBar != null && !mSearchBar.isReinflateRequired();
264    }
265
266    /** Sets the visibility of the search bar */
267    public void setSearchBarVisibility(int visibility) {
268        if (mSearchBar != null) {
269            mSearchBar.setVisibility(visibility);
270            // Always bring the search bar to the top
271            mSearchBar.bringToFront();
272        }
273    }
274
275    @Override
276    protected void onAttachedToWindow() {
277        EventBus.getDefault().register(this, RecentsActivity.EVENT_BUS_PRIORITY + 1);
278        EventBus.getDefault().register(mTouchHandler, RecentsActivity.EVENT_BUS_PRIORITY + 1);
279        super.onAttachedToWindow();
280    }
281
282    @Override
283    protected void onDetachedFromWindow() {
284        super.onDetachedFromWindow();
285        EventBus.getDefault().unregister(this);
286        EventBus.getDefault().unregister(mTouchHandler);
287    }
288
289    /**
290     * This is called with the full size of the window since we are handling our own insets.
291     */
292    @Override
293    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
294        RecentsConfiguration config = Recents.getConfiguration();
295        int width = MeasureSpec.getSize(widthMeasureSpec);
296        int height = MeasureSpec.getSize(heightMeasureSpec);
297
298        // Get the search bar bounds and measure the search bar layout
299        Rect searchBarSpaceBounds = new Rect();
300        if (mSearchBar != null) {
301            config.getSearchBarBounds(new Rect(0, 0, width, height), mSystemInsets.top,
302                    searchBarSpaceBounds);
303            mSearchBar.measure(
304                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.width(), MeasureSpec.EXACTLY),
305                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.height(), MeasureSpec.EXACTLY));
306        }
307
308        Rect taskStackBounds = new Rect();
309        config.getTaskStackBounds(new Rect(0, 0, width, height), mSystemInsets.top,
310                mSystemInsets.right, searchBarSpaceBounds, taskStackBounds);
311        if (mTaskStackView != null && mTaskStackView.getVisibility() != GONE) {
312            mTaskStackView.setTaskStackBounds(taskStackBounds, mSystemInsets);
313            mTaskStackView.measure(widthMeasureSpec, heightMeasureSpec);
314        }
315
316        if (mDragView != null) {
317            mDragView.measure(
318                    MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
319                    MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
320        }
321
322        setMeasuredDimension(width, height);
323    }
324
325    /**
326     * This is called with the full size of the window since we are handling our own insets.
327     */
328    @Override
329    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
330        RecentsConfiguration config = Recents.getConfiguration();
331
332        // Get the search bar bounds so that we lay it out
333        Rect measuredRect = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight());
334        Rect searchBarSpaceBounds = new Rect();
335        if (mSearchBar != null) {
336            config.getSearchBarBounds(measuredRect,
337                    mSystemInsets.top, searchBarSpaceBounds);
338            mSearchBar.layout(searchBarSpaceBounds.left, searchBarSpaceBounds.top,
339                    searchBarSpaceBounds.right, searchBarSpaceBounds.bottom);
340        }
341
342        if (mTaskStackView != null && mTaskStackView.getVisibility() != GONE) {
343            mTaskStackView.layout(left, top, left + getMeasuredWidth(), top + getMeasuredHeight());
344        }
345
346        if (mDragView != null) {
347            mDragView.layout(left, top, left + mDragView.getMeasuredWidth(),
348                    top + mDragView.getMeasuredHeight());
349        }
350    }
351
352    @Override
353    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
354        mSystemInsets.set(insets.getSystemWindowInsets());
355        requestLayout();
356        return insets.consumeSystemWindowInsets();
357    }
358
359    @Override
360    public boolean onInterceptTouchEvent(MotionEvent ev) {
361        return mTouchHandler.onInterceptTouchEvent(ev);
362    }
363
364    @Override
365    public boolean onTouchEvent(MotionEvent ev) {
366        return mTouchHandler.onTouchEvent(ev);
367    }
368
369    @Override
370    protected void dispatchDraw(Canvas canvas) {
371        super.dispatchDraw(canvas);
372        for (int i = mVisibleDockStates.length - 1; i >= 0; i--) {
373            Drawable d = mVisibleDockStates[i].viewState.dockAreaOverlay;
374            if (d.getAlpha() > 0) {
375                d.draw(canvas);
376            }
377        }
378    }
379
380    @Override
381    protected boolean verifyDrawable(Drawable who) {
382        for (int i = mVisibleDockStates.length - 1; i >= 0; i--) {
383            Drawable d = mVisibleDockStates[i].viewState.dockAreaOverlay;
384            if (d == who) {
385                return true;
386            }
387        }
388        return super.verifyDrawable(who);
389    }
390
391    /** Unfilters any filtered stacks */
392    public boolean unfilterFilteredStacks() {
393        if (mStacks != null) {
394            // Check if there are any filtered stacks and unfilter them before we back out of Recents
395            boolean stacksUnfiltered = false;
396            int numStacks = mStacks.size();
397            for (int i = 0; i < numStacks; i++) {
398                TaskStack stack = mStacks.get(i);
399                if (stack.hasFilteredTasks()) {
400                    stack.unfilterTasks();
401                    stacksUnfiltered = true;
402                }
403            }
404            return stacksUnfiltered;
405        }
406        return false;
407    }
408
409    public void disableLayersForOneFrame() {
410        if (mTaskStackView != null) {
411            mTaskStackView.disableLayersForOneFrame();
412        }
413    }
414
415    private void postDrawHeaderThumbnailTransitionRunnable(final TaskStackView view,
416            final TaskView clickedView, final int offsetX, final int offsetY,
417            final float stackScroll,
418            final ActivityOptions.OnAnimationStartedListener animStartedListener,
419            final int destinationStack) {
420        Runnable r = new Runnable() {
421            @Override
422            public void run() {
423                overrideDrawHeaderThumbnailTransition(view, clickedView, offsetX, offsetY,
424                        stackScroll, animStartedListener, destinationStack);
425
426            }
427        };
428
429        mCb.runAfterPause(r);
430    }
431
432    private void overrideDrawHeaderThumbnailTransition(TaskStackView stackView,
433            TaskView clickedTask, int offsetX, int offsetY, float stackScroll,
434            final ActivityOptions.OnAnimationStartedListener animStartedListener,
435            int destinationStack) {
436        List<AppTransitionAnimationSpec> specs = getAppTransitionAnimationSpecs(stackView,
437                clickedTask, offsetX, offsetY, stackScroll, destinationStack);
438        if (specs == null) {
439            return;
440        }
441
442        IRemoteCallback.Stub callback = new IRemoteCallback.Stub() {
443            @Override
444            public void sendResult(Bundle data) throws RemoteException {
445                post(new Runnable() {
446                    @Override
447                    public void run() {
448                        if (animStartedListener != null) {
449                            animStartedListener.onAnimationStarted();
450                        }
451                    }
452                });
453            }
454        };
455
456        AppTransitionAnimationSpec[] specsArray =
457                new AppTransitionAnimationSpec[specs.size()];
458        try {
459            WindowManagerGlobal.getWindowManagerService().overridePendingAppTransitionMultiThumb(
460                    specs.toArray(specsArray), callback, null, true /* scaleUp */);
461
462        } catch (RemoteException e) {
463            Log.w(TAG, "Error overriding app transition", e);
464        }
465    }
466
467    private List<AppTransitionAnimationSpec> getAppTransitionAnimationSpecs(TaskStackView stackView,
468            TaskView clickedTask, int offsetX, int offsetY, float stackScroll,
469            int destinationStack) {
470        final int targetStackId = destinationStack != INVALID_STACK_ID ?
471                destinationStack : clickedTask.getTask().key.stackId;
472        if (targetStackId != FREEFORM_WORKSPACE_STACK_ID
473                && targetStackId != FULLSCREEN_WORKSPACE_STACK_ID) {
474            return null;
475        }
476        // If this is a full screen stack, the transition will be towards the single, full screen
477        // task. We only need the transition spec for this task.
478        List<AppTransitionAnimationSpec> specs = new ArrayList<>();
479        if (targetStackId == FULLSCREEN_WORKSPACE_STACK_ID) {
480            specs.add(createThumbnailHeaderAnimationSpec(
481                    stackView, offsetX, offsetY, stackScroll, clickedTask,
482                    clickedTask.getTask().key.id, ADD_HEADER_BITMAP));
483            return specs;
484        }
485        // This is a free form stack or full screen stack, so there will be multiple windows
486        // animating from thumbnails. We need transition animation specs for all of them.
487
488        // We will use top and bottom task views as a base for tasks, that aren't visible on the
489        // screen. This is necessary for cascade recents list, where some of the tasks might be
490        // hidden.
491        List<TaskView> taskViews = stackView.getTaskViews();
492        int childCount = taskViews.size();
493        TaskView topChild = taskViews.get(0);
494        TaskView bottomChild = taskViews.get(childCount - 1);
495        SparseArray<TaskView> taskViewsByTaskId = new SparseArray<>();
496        for (int i = 0; i < childCount; i++) {
497            TaskView taskView = taskViews.get(i);
498            taskViewsByTaskId.put(taskView.getTask().key.id, taskView);
499        }
500
501        TaskStack stack = stackView.getStack();
502        // We go through all tasks now and for each generate transition animation spec. If there is
503        // a view associated with a task, we use that view as a base for the animation. If there
504        // isn't, we use bottom or top view, depending on which one would be closer to the task
505        // view if it existed.
506        ArrayList<Task> tasks = stack.getTasks();
507        boolean passedClickedTask = false;
508        for (int i = 0, n = tasks.size(); i < n; i++) {
509            Task task = tasks.get(i);
510            TaskView taskView = taskViewsByTaskId.get(task.key.id);
511            if (taskView != null) {
512                specs.add(createThumbnailHeaderAnimationSpec(stackView, offsetX, offsetY,
513                        stackScroll, taskView, taskView.getTask().key.id, ADD_HEADER_BITMAP));
514                if (taskView == clickedTask) {
515                    passedClickedTask = true;
516                }
517            } else {
518                taskView = passedClickedTask ? bottomChild : topChild;
519                specs.add(createThumbnailHeaderAnimationSpec(stackView, offsetX, offsetY,
520                        stackScroll, taskView, task.key.id, !ADD_HEADER_BITMAP));
521            }
522        }
523
524        return specs;
525    }
526
527    private AppTransitionAnimationSpec createThumbnailHeaderAnimationSpec(TaskStackView stackView,
528            int offsetX, int offsetY, float stackScroll, TaskView tv, int taskId,
529            boolean addHeaderBitmap) {
530        // Disable any focused state before we draw the header
531        // Upfront the processing of the thumbnail
532        if (tv.isFocusedTask()) {
533            tv.setFocusedState(false, false /* animated */, false /* requestViewFocus */);
534        }
535        TaskViewTransform transform = new TaskViewTransform();
536        transform = stackView.getStackAlgorithm().getStackTransform(tv.mTask, stackScroll,
537                transform, null);
538
539        float scale = tv.getScaleX();
540        int fromHeaderWidth = (int) (tv.mHeaderView.getMeasuredWidth() * scale);
541        int fromHeaderHeight = (int) (tv.mHeaderView.getMeasuredHeight() * scale);
542
543        Bitmap b = null;
544        if (addHeaderBitmap) {
545            b = Bitmap.createBitmap(fromHeaderWidth, fromHeaderHeight,
546                    Bitmap.Config.ARGB_8888);
547
548            if (Constants.DebugFlags.App.EnableTransitionThumbnailDebugMode) {
549                b.eraseColor(0xFFff0000);
550            } else {
551                Canvas c = new Canvas(b);
552                c.scale(tv.getScaleX(), tv.getScaleY());
553                tv.mHeaderView.draw(c);
554                c.setBitmap(null);
555
556            }
557            b = b.createAshmemBitmap();
558        }
559
560        int[] pts = new int[2];
561        tv.getLocationOnScreen(pts);
562
563        final int left = pts[0] + offsetX;
564        final int top = pts[1] + offsetY;
565        final Rect rect = new Rect(left, top, left + (int) transform.rect.width(),
566                top + (int) transform.rect.height());
567
568        return new AppTransitionAnimationSpec(taskId, b, rect);
569    }
570
571    /**
572     * Cancels any running window transitions for the launched task (the task animating into
573     * Recents).
574     */
575    private void cancelLaunchedTaskWindowTransition(final Task task) {
576        SystemServicesProxy ssp = Recents.getSystemServices();
577        RecentsConfiguration config = Recents.getConfiguration();
578        RecentsActivityLaunchState launchState = config.getLaunchState();
579        if (launchState.launchedToTaskId != -1 &&
580                launchState.launchedToTaskId != task.key.id) {
581            ssp.cancelWindowTransition(launchState.launchedToTaskId);
582        }
583    }
584
585    /**** TaskStackView.TaskStackCallbacks Implementation ****/
586
587    @Override
588    public void onTaskViewClicked(final TaskStackView stackView, final TaskView tv,
589            final TaskStack stack, final Task task, final boolean lockToTask,
590            final boolean boundsValid, final Rect bounds, int destinationStack) {
591        // Notify any callbacks of the launching of a new task
592        if (mCb != null) {
593            mCb.onTaskViewClicked();
594        }
595
596        // Upfront the processing of the thumbnail
597        TaskViewTransform transform = new TaskViewTransform();
598        View sourceView;
599        int offsetX = 0;
600        int offsetY = 0;
601        float stackScroll = stackView.getScroller().getStackScroll();
602        if (tv == null) {
603            // If there is no actual task view, then use the stack view as the source view
604            // and then offset to the expected transform rect, but bound this to just
605            // outside the display rect (to ensure we don't animate from too far away)
606            sourceView = stackView;
607            offsetX = (int) transform.rect.left;
608            offsetY = getMeasuredHeight();
609        } else {
610            sourceView = tv.mThumbnailView;
611        }
612
613        // Compute the thumbnail to scale up from
614        final SystemServicesProxy ssp = Recents.getSystemServices();
615        boolean screenPinningRequested = false;
616        ActivityOptions opts = null;
617        ActivityOptions.OnAnimationStartedListener animStartedListener = null;
618        if (task.thumbnail != null && task.thumbnail.getWidth() > 0 &&
619                task.thumbnail.getHeight() > 0) {
620            animStartedListener = new ActivityOptions.OnAnimationStartedListener() {
621                @Override
622                public void onAnimationStarted() {
623                    // If we are launching into another task, cancel the previous task's
624                    // window transition
625                    cancelLaunchedTaskWindowTransition(task);
626
627                    if (lockToTask) {
628                        // Request screen pinning after the animation runs
629                        postDelayed(new Runnable() {
630                            @Override
631                            public void run() {
632                                EventBus.getDefault().send(new ScreenPinningRequestEvent(
633                                        getContext(), ssp));
634                            }
635                        }, 350);
636                    }
637                }
638            };
639            postDrawHeaderThumbnailTransitionRunnable(stackView, tv, offsetX, offsetY, stackScroll,
640                    animStartedListener, destinationStack);
641            opts = ActivityOptions.makeThumbnailAspectScaleUpAnimation(sourceView,
642                    Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8).createAshmemBitmap(),
643                    offsetX, offsetY, (int) transform.rect.width(), (int) transform.rect.height(),
644                    sourceView.getHandler(), animStartedListener);
645            screenPinningRequested = true;
646        } else {
647            opts = ActivityOptions.makeBasic();
648        }
649        if (boundsValid) {
650            opts.setBounds(bounds.isEmpty() ? null : bounds);
651        }
652        final ActivityOptions launchOpts = opts;
653        final boolean finalScreenPinningRequested = screenPinningRequested;
654        final Runnable launchRunnable = new Runnable() {
655            @Override
656            public void run() {
657                if (task.isActive) {
658                    // Bring an active task to the foreground
659                    ssp.moveTaskToFront(task.key.id, launchOpts);
660                } else {
661                    if (ssp.startActivityFromRecents(getContext(), task.key.id, task.activityLabel,
662                            launchOpts)) {
663                        if (!finalScreenPinningRequested) {
664                            // If we have not requested this already to be run after the window
665                            // transition, then just run it now
666                            EventBus.getDefault().send(new ScreenPinningRequestEvent(
667                                    getContext(), ssp));
668                        }
669                    } else {
670                        // Dismiss the task and return the user to home if we fail to
671                        // launch the task
672                        EventBus.getDefault().send(new DismissTaskViewEvent(task, tv));
673                        if (mCb != null) {
674                            mCb.onTaskLaunchFailed();
675                        }
676
677                        // Keep track of failed launches
678                        MetricsLogger.count(getContext(), "overview_task_launch_failed", 1);
679                    }
680                }
681            }
682        };
683
684        // Keep track of the index of the task launch
685        int taskIndexFromFront = 0;
686        int taskIndex = stack.indexOfTask(task);
687        if (taskIndex > -1) {
688            taskIndexFromFront = stack.getTaskCount() - taskIndex - 1;
689        }
690        MetricsLogger.histogram(getContext(), "overview_task_launch_index", taskIndexFromFront);
691
692        // Launch the app right away if there is no task view, otherwise, animate the icon out first
693        if (tv == null) {
694            launchRunnable.run();
695        } else {
696            if (task.group != null && !task.group.isFrontMostTask(task)) {
697                // For affiliated tasks that are behind other tasks, we must animate the front cards
698                // out of view before starting the task transition
699                stackView.startLaunchTaskAnimation(tv, launchRunnable, lockToTask);
700            } else {
701                // Otherwise, we can start the task transition immediately
702                stackView.startLaunchTaskAnimation(tv, null, lockToTask);
703                launchRunnable.run();
704            }
705        }
706    }
707
708    @Override
709    public void onAllTaskViewsDismissed(ArrayList<Task> removedTasks) {
710        /* TODO: Not currently enabled
711        if (removedTasks != null) {
712            int taskCount = removedTasks.size();
713            for (int i = 0; i < taskCount; i++) {
714                onTaskViewDismissed(removedTasks.get(i));
715            }
716        }
717        */
718
719        mCb.onAllTaskViewsDismissed();
720
721        // Keep track of all-deletions
722        MetricsLogger.count(getContext(), "overview_task_all_dismissed", 1);
723    }
724
725    @Override
726    public void onTaskStackFilterTriggered() {
727        // Hide the search bar
728        if (mSearchBar != null) {
729            int filterDuration = getResources().getInteger(
730                    R.integer.recents_filter_animate_current_views_duration);
731            mSearchBar.animate()
732                    .alpha(0f)
733                    .setStartDelay(0)
734                    .setInterpolator(mFastOutSlowInInterpolator)
735                    .setDuration(filterDuration)
736                    .withLayer()
737                    .start();
738        }
739    }
740
741    @Override
742    public void onTaskStackUnfilterTriggered() {
743        // Show the search bar
744        if (mSearchBar != null) {
745            int filterDuration = getResources().getInteger(
746                    R.integer.recents_filter_animate_new_views_duration);
747            mSearchBar.animate()
748                    .alpha(1f)
749                    .setStartDelay(0)
750                    .setInterpolator(mFastOutSlowInInterpolator)
751                    .setDuration(filterDuration)
752                    .withLayer()
753                    .start();
754        }
755    }
756
757    /**** EventBus Events ****/
758
759    public final void onBusEvent(DragStartEvent event) {
760        // Add the drag view
761        mDragView = event.dragView;
762        addView(mDragView);
763
764        updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
765                TaskStack.DockState.NONE.viewState.dockAreaAlpha);
766    }
767
768    public final void onBusEvent(DragDockStateChangedEvent event) {
769        if (event.dockState == TaskStack.DockState.NONE) {
770            updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
771                    TaskStack.DockState.NONE.viewState.dockAreaAlpha);
772        } else {
773            updateVisibleDockRegions(new TaskStack.DockState[] {event.dockState}, -1);
774        }
775    }
776
777    public final void onBusEvent(final DragEndEvent event) {
778        event.postAnimationTrigger.increment();
779        event.postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
780            @Override
781            public void run() {
782                // Remove the drag view
783                removeView(mDragView);
784                mDragView = null;
785                updateVisibleDockRegions(null, -1);
786
787                // Dock the new task if we are hovering over a valid dock state
788                if (event.dockState != TaskStack.DockState.NONE) {
789                    SystemServicesProxy ssp = Recents.getSystemServices();
790                    ssp.startTaskInDockedMode(event.task.key.id, event.dockState.createMode);
791                    launchTask(event.task, null, INVALID_STACK_ID);
792                }
793            }
794        });
795        if (event.dockState == TaskStack.DockState.NONE) {
796            // Animate the alpha back to what it was before
797            Rect taskBounds = mTaskStackView.getStackAlgorithm().getUntransformedTaskViewBounds();
798            int left = taskBounds.left + (int) ((1f - event.taskView.getScaleX()) * taskBounds.width()) / 2;
799            int top = taskBounds.top + (int) ((1f - event.taskView.getScaleY()) * taskBounds.height()) / 2;
800            event.dragView.animate()
801                    .scaleX(1f)
802                    .scaleY(1f)
803                    .translationX(left + event.taskView.getTranslationX())
804                    .translationY(top + event.taskView.getTranslationY())
805                    .setDuration(175)
806                    .setInterpolator(mFastOutSlowInInterpolator)
807                    .withEndAction(event.postAnimationTrigger.decrementAsRunnable())
808                    .start();
809
810            // Animate the overlay alpha back to 0
811            updateVisibleDockRegions(null, -1);
812        } else {
813            event.postAnimationTrigger.decrement();
814        }
815    }
816
817    /**
818     * Updates the dock region to match the specified dock state.
819     */
820    private void updateVisibleDockRegions(TaskStack.DockState[] newDockStates, int overrideAlpha) {
821        ArraySet<TaskStack.DockState> newDockStatesSet = new ArraySet<>();
822        if (newDockStates != null) {
823            for (TaskStack.DockState dockState : newDockStates) {
824                newDockStatesSet.add(dockState);
825            }
826        }
827        for (TaskStack.DockState dockState : mVisibleDockStates) {
828            TaskStack.DockState.ViewState viewState = dockState.viewState;
829            if (newDockStates == null || !newDockStatesSet.contains(dockState)) {
830                // This is no longer visible, so hide it
831                viewState.startAlphaAnimation(0, 150);
832            } else {
833                // This state is now visible, update the bounds and show it
834                int alpha = (overrideAlpha != -1 ? overrideAlpha : viewState.dockAreaAlpha);
835                viewState.dockAreaOverlay.setBounds(
836                        dockState.getDockedBounds(getMeasuredWidth(), getMeasuredHeight()));
837                viewState.dockAreaOverlay.setCallback(this);
838                viewState.startAlphaAnimation(alpha, 150);
839            }
840        }
841    }
842
843    public void setStackViewVisibility(int stackViewVisibility) {
844        mStackViewVisibility = stackViewVisibility;
845        if (mTaskStackView != null) {
846            mTaskStackView.setVisibility(stackViewVisibility);
847            invalidate();
848        }
849    }
850}
851