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