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