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