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