RecentsView.java revision f21c3dace89b168f5e5e4e96532d977b8b0a1cf5
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 static android.app.ActivityManager.StackId.INVALID_STACK_ID;
20
21import android.animation.Animator;
22import android.animation.ObjectAnimator;
23import android.app.ActivityOptions.OnAnimationStartedListener;
24import android.content.Context;
25import android.graphics.Canvas;
26import android.graphics.Color;
27import android.graphics.Outline;
28import android.graphics.Rect;
29import android.graphics.drawable.ColorDrawable;
30import android.graphics.drawable.Drawable;
31import android.util.ArraySet;
32import android.util.AttributeSet;
33import android.view.AppTransitionAnimationSpec;
34import android.view.IAppTransitionAnimationSpecsFuture;
35import android.view.LayoutInflater;
36import android.view.MotionEvent;
37import android.view.View;
38import android.view.ViewDebug;
39import android.view.ViewOutlineProvider;
40import android.view.ViewPropertyAnimator;
41import android.view.WindowInsets;
42import android.widget.FrameLayout;
43import android.widget.TextView;
44
45import com.android.internal.logging.MetricsLogger;
46import com.android.internal.logging.MetricsProto.MetricsEvent;
47import com.android.systemui.Interpolators;
48import com.android.systemui.R;
49import com.android.systemui.recents.Recents;
50import com.android.systemui.recents.RecentsActivity;
51import com.android.systemui.recents.RecentsActivityLaunchState;
52import com.android.systemui.recents.RecentsConfiguration;
53import com.android.systemui.recents.RecentsDebugFlags;
54import com.android.systemui.recents.events.EventBus;
55import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
56import com.android.systemui.recents.events.activity.DockedFirstAnimationFrameEvent;
57import com.android.systemui.recents.events.activity.EnterRecentsWindowAnimationCompletedEvent;
58import com.android.systemui.recents.events.activity.HideStackActionButtonEvent;
59import com.android.systemui.recents.events.activity.LaunchTaskEvent;
60import com.android.systemui.recents.events.activity.ShowStackActionButtonEvent;
61import com.android.systemui.recents.events.ui.AllTaskViewsDismissedEvent;
62import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
63import com.android.systemui.recents.events.ui.DraggingInRecentsEndedEvent;
64import com.android.systemui.recents.events.ui.DraggingInRecentsEvent;
65import com.android.systemui.recents.events.ui.dragndrop.DragDropTargetChangedEvent;
66import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
67import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
68import com.android.systemui.recents.misc.ReferenceCountedTrigger;
69import com.android.systemui.recents.misc.SystemServicesProxy;
70import com.android.systemui.recents.misc.Utilities;
71import com.android.systemui.recents.model.Task;
72import com.android.systemui.recents.model.TaskStack;
73import com.android.systemui.recents.views.RecentsTransitionHelper.AnimationSpecComposer;
74import com.android.systemui.stackdivider.WindowManagerProxy;
75import com.android.systemui.statusbar.FlingAnimationUtils;
76
77import java.io.FileDescriptor;
78import java.io.PrintWriter;
79import java.util.ArrayList;
80import java.util.List;
81
82/**
83 * This view is the the top level layout that contains TaskStacks (which are laid out according
84 * to their SpaceNode bounds.
85 */
86public class RecentsView extends FrameLayout {
87
88    private static final String TAG = "RecentsView";
89
90    private static final int DOCK_AREA_OVERLAY_TRANSITION_DURATION = 135;
91    private static final int DEFAULT_UPDATE_SCRIM_DURATION = 200;
92    private static final float DEFAULT_SCRIM_ALPHA = 0.33f;
93
94    private static final int SHOW_STACK_ACTION_BUTTON_DURATION = 150;
95    private static final int HIDE_STACK_ACTION_BUTTON_DURATION = 100;
96
97    private TaskStack mStack;
98    private TaskStackView mTaskStackView;
99    private TextView mStackActionButton;
100    private TextView mEmptyView;
101
102    private boolean mAwaitingFirstLayout = true;
103    private boolean mLastTaskLaunchedWasFreeform;
104
105    @ViewDebug.ExportedProperty(category="recents")
106    private Rect mSystemInsets = new Rect();
107    private int mDividerSize;
108
109    private Drawable mBackgroundScrim = new ColorDrawable(
110            Color.argb((int) (DEFAULT_SCRIM_ALPHA * 255), 0, 0, 0)).mutate();
111    private Animator mBackgroundScrimAnimator;
112
113    private RecentsTransitionHelper mTransitionHelper;
114    @ViewDebug.ExportedProperty(deepExport=true, prefix="touch_")
115    private RecentsViewTouchHandler mTouchHandler;
116    private final FlingAnimationUtils mFlingAnimationUtils;
117
118    public RecentsView(Context context) {
119        this(context, null);
120    }
121
122    public RecentsView(Context context, AttributeSet attrs) {
123        this(context, attrs, 0);
124    }
125
126    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr) {
127        this(context, attrs, defStyleAttr, 0);
128    }
129
130    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
131        super(context, attrs, defStyleAttr, defStyleRes);
132        setWillNotDraw(false);
133
134        SystemServicesProxy ssp = Recents.getSystemServices();
135        mTransitionHelper = new RecentsTransitionHelper(getContext());
136        mDividerSize = ssp.getDockedDividerSize(context);
137        mTouchHandler = new RecentsViewTouchHandler(this);
138        mFlingAnimationUtils = new FlingAnimationUtils(context, 0.3f);
139
140        LayoutInflater inflater = LayoutInflater.from(context);
141        if (RecentsDebugFlags.Static.EnableStackActionButton) {
142            float cornerRadius = context.getResources().getDimensionPixelSize(
143                    R.dimen.recents_task_view_rounded_corners_radius);
144            mStackActionButton = (TextView) inflater.inflate(R.layout.recents_stack_action_button,
145                    this, false);
146            mStackActionButton.forceHasOverlappingRendering(false);
147            mStackActionButton.setOnClickListener(new View.OnClickListener() {
148                @Override
149                public void onClick(View v) {
150                    EventBus.getDefault().send(new DismissAllTaskViewsEvent());
151                }
152            });
153            addView(mStackActionButton);
154            mStackActionButton.setClipToOutline(true);
155            mStackActionButton.setOutlineProvider(new ViewOutlineProvider() {
156                @Override
157                public void getOutline(View view, Outline outline) {
158                    outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), cornerRadius);
159                }
160            });
161        }
162        mEmptyView = (TextView) inflater.inflate(R.layout.recents_empty, this, false);
163        addView(mEmptyView);
164    }
165
166    /**
167     * Called from RecentsActivity when it is relaunched.
168     */
169    public void onReload(boolean isResumingFromVisible, boolean isTaskStackEmpty) {
170        RecentsConfiguration config = Recents.getConfiguration();
171        RecentsActivityLaunchState launchState = config.getLaunchState();
172
173        if (mTaskStackView == null) {
174            isResumingFromVisible = false;
175            mTaskStackView = new TaskStackView(getContext());
176            mTaskStackView.setSystemInsets(mSystemInsets);
177            addView(mTaskStackView);
178        }
179
180        // Reset the state
181        mAwaitingFirstLayout = !isResumingFromVisible;
182        mLastTaskLaunchedWasFreeform = false;
183
184        // Update the stack
185        mTaskStackView.onReload(isResumingFromVisible);
186
187        if (isResumingFromVisible) {
188            // If we are already visible, then restore the background scrim
189            animateBackgroundScrim(1f, DEFAULT_UPDATE_SCRIM_DURATION);
190        } else {
191            // If we are already occluded by the app, then set the final background scrim alpha now.
192            // Otherwise, defer until the enter animation completes to animate the scrim alpha with
193            // the tasks for the home animation.
194            if (launchState.launchedViaDockGesture || launchState.launchedFromApp
195                    || isTaskStackEmpty) {
196                mBackgroundScrim.setAlpha(255);
197            } else {
198                mBackgroundScrim.setAlpha(0);
199            }
200        }
201    }
202
203    /**
204     * Called from RecentsActivity when the task stack is updated.
205     */
206    public void updateStack(TaskStack stack) {
207        mStack = stack;
208        mTaskStackView.setTasks(stack, true /* allowNotifyStackChanges */);
209
210        // Update the top level view's visibilities
211        if (stack.getTaskCount() > 0) {
212            hideEmptyView();
213        } else {
214            showEmptyView(R.string.recents_empty_message);
215        }
216    }
217
218    /**
219     * Returns the current TaskStack.
220     */
221    public TaskStack getStack() {
222        return mStack;
223    }
224
225    /*
226     * Returns the window background scrim.
227     */
228    public Drawable getBackgroundScrim() {
229        return mBackgroundScrim;
230    }
231
232    /**
233     * Returns whether the last task launched was in the freeform stack or not.
234     */
235    public boolean isLastTaskLaunchedFreeform() {
236        return mLastTaskLaunchedWasFreeform;
237    }
238
239    /** Launches the focused task from the first stack if possible */
240    public boolean launchFocusedTask(int logEvent) {
241        if (mTaskStackView != null) {
242            Task task = mTaskStackView.getFocusedTask();
243            if (task != null) {
244                TaskView taskView = mTaskStackView.getChildViewForTask(task);
245                EventBus.getDefault().send(new LaunchTaskEvent(taskView, task, null,
246                        INVALID_STACK_ID, false));
247
248                if (logEvent != 0) {
249                    MetricsLogger.action(getContext(), logEvent,
250                            task.key.getComponent().toString());
251                }
252                return true;
253            }
254        }
255        return false;
256    }
257
258    /** Launches the task that recents was launched from if possible */
259    public boolean launchPreviousTask() {
260        if (mTaskStackView != null) {
261            TaskStack stack = mTaskStackView.getStack();
262            Task task = stack.getLaunchTarget();
263            if (task != null) {
264                TaskView taskView = mTaskStackView.getChildViewForTask(task);
265                EventBus.getDefault().send(new LaunchTaskEvent(taskView, task, null,
266                        INVALID_STACK_ID, false));
267                return true;
268            }
269        }
270        return false;
271    }
272
273    /** Launches a given task. */
274    public boolean launchTask(Task task, Rect taskBounds, int destinationStack) {
275        if (mTaskStackView != null) {
276            // Iterate the stack views and try and find the given task.
277            List<TaskView> taskViews = mTaskStackView.getTaskViews();
278            int taskViewCount = taskViews.size();
279            for (int j = 0; j < taskViewCount; j++) {
280                TaskView tv = taskViews.get(j);
281                if (tv.getTask() == task) {
282                    EventBus.getDefault().send(new LaunchTaskEvent(tv, task, taskBounds,
283                            destinationStack, false));
284                    return true;
285                }
286            }
287        }
288        return false;
289    }
290
291    /**
292     * Hides the task stack and shows the empty view.
293     */
294    public void showEmptyView(int msgResId) {
295        mTaskStackView.setVisibility(View.INVISIBLE);
296        mEmptyView.setText(msgResId);
297        mEmptyView.setVisibility(View.VISIBLE);
298        mEmptyView.bringToFront();
299        if (RecentsDebugFlags.Static.EnableStackActionButton) {
300            mStackActionButton.bringToFront();
301        }
302    }
303
304    /**
305     * Shows the task stack and hides the empty view.
306     */
307    public void hideEmptyView() {
308        mEmptyView.setVisibility(View.INVISIBLE);
309        mTaskStackView.setVisibility(View.VISIBLE);
310        mTaskStackView.bringToFront();
311        if (RecentsDebugFlags.Static.EnableStackActionButton) {
312            mStackActionButton.bringToFront();
313        }
314    }
315
316    @Override
317    protected void onAttachedToWindow() {
318        EventBus.getDefault().register(this, RecentsActivity.EVENT_BUS_PRIORITY + 1);
319        EventBus.getDefault().register(mTouchHandler, RecentsActivity.EVENT_BUS_PRIORITY + 2);
320        super.onAttachedToWindow();
321    }
322
323    @Override
324    protected void onDetachedFromWindow() {
325        super.onDetachedFromWindow();
326        EventBus.getDefault().unregister(this);
327        EventBus.getDefault().unregister(mTouchHandler);
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 onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
335        int width = MeasureSpec.getSize(widthMeasureSpec);
336        int height = MeasureSpec.getSize(heightMeasureSpec);
337
338        if (mTaskStackView.getVisibility() != GONE) {
339            mTaskStackView.measure(widthMeasureSpec, heightMeasureSpec);
340        }
341
342        // Measure the empty view to the full size of the screen
343        if (mEmptyView.getVisibility() != GONE) {
344            measureChild(mEmptyView, MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
345                    MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
346        }
347
348        if (RecentsDebugFlags.Static.EnableStackActionButton) {
349            // Measure the stack action button within the constraints of the space above the stack
350            Rect buttonBounds = mTaskStackView.mLayoutAlgorithm.mStackActionButtonRect;
351            measureChild(mStackActionButton,
352                    MeasureSpec.makeMeasureSpec(buttonBounds.width(), MeasureSpec.AT_MOST),
353                    MeasureSpec.makeMeasureSpec(buttonBounds.height(), MeasureSpec.AT_MOST));
354        }
355
356        setMeasuredDimension(width, height);
357    }
358
359    /**
360     * This is called with the full size of the window since we are handling our own insets.
361     */
362    @Override
363    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
364        if (mTaskStackView.getVisibility() != GONE) {
365            mTaskStackView.layout(left, top, left + getMeasuredWidth(), top + getMeasuredHeight());
366        }
367
368        // Layout the empty view
369        if (mEmptyView.getVisibility() != GONE) {
370            int leftRightInsets = mSystemInsets.left + mSystemInsets.right;
371            int topBottomInsets = mSystemInsets.top + mSystemInsets.bottom;
372            int childWidth = mEmptyView.getMeasuredWidth();
373            int childHeight = mEmptyView.getMeasuredHeight();
374            int childLeft = left + mSystemInsets.left +
375                    Math.max(0, (right - left - leftRightInsets - childWidth)) / 2;
376            int childTop = top + mSystemInsets.top +
377                    Math.max(0, (bottom - top - topBottomInsets - childHeight)) / 2;
378            mEmptyView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
379        }
380
381        if (RecentsDebugFlags.Static.EnableStackActionButton) {
382            // Layout the stack action button such that its drawable is start-aligned with the
383            // stack, vertically centered in the available space above the stack
384            Rect buttonBounds = getStackActionButtonBoundsFromStackLayout();
385            mStackActionButton.layout(buttonBounds.left, buttonBounds.top, buttonBounds.right,
386                    buttonBounds.bottom);
387        }
388
389        if (mAwaitingFirstLayout) {
390            mAwaitingFirstLayout = false;
391
392            // If launched via dragging from the nav bar, then we should translate the whole view
393            // down offscreen
394            RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
395            if (launchState.launchedViaDragGesture) {
396                setTranslationY(getMeasuredHeight());
397            } else {
398                setTranslationY(0f);
399            }
400        }
401    }
402
403    @Override
404    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
405        mSystemInsets.set(insets.getSystemWindowInsets());
406        mTaskStackView.setSystemInsets(mSystemInsets);
407        requestLayout();
408        return insets;
409    }
410
411    @Override
412    public boolean onInterceptTouchEvent(MotionEvent ev) {
413        return mTouchHandler.onInterceptTouchEvent(ev);
414    }
415
416    @Override
417    public boolean onTouchEvent(MotionEvent ev) {
418        return mTouchHandler.onTouchEvent(ev);
419    }
420
421    @Override
422    public void onDrawForeground(Canvas canvas) {
423        super.onDrawForeground(canvas);
424
425        ArrayList<TaskStack.DockState> visDockStates = mTouchHandler.getVisibleDockStates();
426        for (int i = visDockStates.size() - 1; i >= 0; i--) {
427            Drawable d = visDockStates.get(i).viewState.dockAreaOverlay;
428            if (d.getAlpha() > 0) {
429                d.draw(canvas);
430            }
431        }
432    }
433
434    @Override
435    protected boolean verifyDrawable(Drawable who) {
436        ArrayList<TaskStack.DockState> visDockStates = mTouchHandler.getVisibleDockStates();
437        for (int i = visDockStates.size() - 1; i >= 0; i--) {
438            Drawable d = visDockStates.get(i).viewState.dockAreaOverlay;
439            if (d == who) {
440                return true;
441            }
442        }
443        return super.verifyDrawable(who);
444    }
445
446    /**** EventBus Events ****/
447
448    public final void onBusEvent(LaunchTaskEvent event) {
449        mLastTaskLaunchedWasFreeform = event.task.isFreeformTask();
450        mTransitionHelper.launchTaskFromRecents(mStack, event.task, mTaskStackView, event.taskView,
451                event.screenPinningRequested, event.targetTaskBounds, event.targetTaskStack);
452    }
453
454    public final void onBusEvent(DismissRecentsToHomeAnimationStarted event) {
455        int taskViewExitToHomeDuration = TaskStackAnimationHelper.EXIT_TO_HOME_TRANSLATION_DURATION;
456        if (RecentsDebugFlags.Static.EnableStackActionButton) {
457            // Hide the stack action button
458            hideStackActionButton(taskViewExitToHomeDuration, false /* translate */);
459        }
460        animateBackgroundScrim(0f, taskViewExitToHomeDuration);
461    }
462
463    public final void onBusEvent(DragStartEvent event) {
464        updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
465                true /* isDefaultDockState */, TaskStack.DockState.NONE.viewState.dockAreaAlpha,
466                true /* animateAlpha */, false /* animateBounds */);
467    }
468
469    public final void onBusEvent(DragDropTargetChangedEvent event) {
470        if (event.dropTarget == null || !(event.dropTarget instanceof TaskStack.DockState)) {
471            updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
472                    true /* isDefaultDockState */, TaskStack.DockState.NONE.viewState.dockAreaAlpha,
473                    true /* animateAlpha */, true /* animateBounds */);
474        } else {
475            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
476            updateVisibleDockRegions(new TaskStack.DockState[] {dockState},
477                    false /* isDefaultDockState */, -1, true /* animateAlpha */,
478                    true /* animateBounds */);
479        }
480        if (mStackActionButton != null) {
481            event.addPostAnimationCallback(new Runnable() {
482                @Override
483                public void run() {
484                    // Move the clear all button to its new position
485                    Rect buttonBounds = getStackActionButtonBoundsFromStackLayout();
486                    mStackActionButton.setLeftTopRightBottom(buttonBounds.left, buttonBounds.top,
487                            buttonBounds.right, buttonBounds.bottom);
488                }
489            });
490        }
491    }
492
493    public final void onBusEvent(final DragEndEvent event) {
494        // Handle the case where we drop onto a dock region
495        if (event.dropTarget instanceof TaskStack.DockState) {
496            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
497
498            // Hide the dock region
499            updateVisibleDockRegions(null, false /* isDefaultDockState */, -1,
500                    false /* animateAlpha */, false /* animateBounds */);
501
502            TaskStackLayoutAlgorithm stackLayout = mTaskStackView.getStackAlgorithm();
503            TaskStackViewScroller stackScroller = mTaskStackView.getScroller();
504            TaskViewTransform tmpTransform = new TaskViewTransform();
505
506            // We translated the view but we need to animate it back from the current layout-space
507            // rect to its final layout-space rect
508            int x = (int) event.taskView.getTranslationX();
509            int y = (int) event.taskView.getTranslationY();
510            Rect taskViewRect = new Rect(event.taskView.getLeft(), event.taskView.getTop(),
511                    event.taskView.getRight(), event.taskView.getBottom());
512            taskViewRect.offset(x, y);
513            event.taskView.setTranslationX(0);
514            event.taskView.setTranslationY(0);
515            event.taskView.setLeftTopRightBottom(taskViewRect.left, taskViewRect.top,
516                    taskViewRect.right, taskViewRect.bottom);
517
518            final OnAnimationStartedListener startedListener = new OnAnimationStartedListener() {
519                @Override
520                public void onAnimationStarted() {
521                    EventBus.getDefault().send(new DockedFirstAnimationFrameEvent());
522                    mTaskStackView.getStack().removeTask(event.task, AnimationProps.IMMEDIATE,
523                            true /* fromDockGesture */);
524                }
525            };
526
527            // Dock the task and launch it
528            SystemServicesProxy ssp = Recents.getSystemServices();
529            ssp.startTaskInDockedMode(event.task.key.id, dockState.createMode);
530            final Rect taskRect = getTaskRect(event.taskView);
531            IAppTransitionAnimationSpecsFuture future = mTransitionHelper.getAppTransitionFuture(
532                    new AnimationSpecComposer() {
533                        @Override
534                        public List<AppTransitionAnimationSpec> composeSpecs() {
535                            return mTransitionHelper.composeDockAnimationSpec(
536                                    event.taskView, taskRect);
537                        }
538                    });
539            ssp.overridePendingAppTransitionMultiThumbFuture(future,
540                    mTransitionHelper.wrapStartedListener(startedListener),
541                    true /* scaleUp */);
542
543            MetricsLogger.action(mContext, MetricsEvent.ACTION_WINDOW_DOCK_DRAG_DROP,
544                    event.task.getTopComponent().flattenToShortString());
545        } else {
546            // Animate the overlay alpha back to 0
547            updateVisibleDockRegions(null, true /* isDefaultDockState */, -1,
548                    true /* animateAlpha */, false /* animateBounds */);
549        }
550    }
551
552    private Rect getTaskRect(TaskView taskView) {
553        int[] location = taskView.getLocationOnScreen();
554        int viewX = location[0];
555        int viewY = location[1];
556        return new Rect(viewX, viewY,
557                (int) (viewX + taskView.getWidth() * taskView.getScaleX()),
558                (int) (viewY + taskView.getHeight() * taskView.getScaleY()));
559    }
560
561    public final void onBusEvent(DraggingInRecentsEvent event) {
562        if (mTaskStackView.getTaskViews().size() > 0) {
563            setTranslationY(event.distanceFromTop - mTaskStackView.getTaskViews().get(0).getY());
564        }
565    }
566
567    public final void onBusEvent(DraggingInRecentsEndedEvent event) {
568        ViewPropertyAnimator animator = animate();
569        if (event.velocity > mFlingAnimationUtils.getMinVelocityPxPerSecond()) {
570            animator.translationY(getHeight());
571            animator.withEndAction(new Runnable() {
572                @Override
573                public void run() {
574                    WindowManagerProxy.getInstance().maximizeDockedStack();
575                }
576            });
577            mFlingAnimationUtils.apply(animator, getTranslationY(), getHeight(), event.velocity);
578        } else {
579            animator.translationY(0f);
580            animator.setListener(null);
581            mFlingAnimationUtils.apply(animator, getTranslationY(), 0, event.velocity);
582        }
583        animator.start();
584    }
585
586    public final void onBusEvent(EnterRecentsWindowAnimationCompletedEvent event) {
587        RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
588        if (!launchState.launchedViaDockGesture && !launchState.launchedFromApp
589                && mStack.getTaskCount() > 0) {
590            animateBackgroundScrim(1f,
591                    TaskStackAnimationHelper.ENTER_FROM_HOME_TRANSLATION_DURATION);
592        }
593    }
594
595    public final void onBusEvent(AllTaskViewsDismissedEvent event) {
596        hideStackActionButton(HIDE_STACK_ACTION_BUTTON_DURATION, true /* translate */);
597    }
598
599    public final void onBusEvent(DismissAllTaskViewsEvent event) {
600        SystemServicesProxy ssp = Recents.getSystemServices();
601        if (!ssp.hasDockedTask()) {
602            // Animate the background away only if we are dismissing Recents to home
603            animateBackgroundScrim(0f, DEFAULT_UPDATE_SCRIM_DURATION);
604        }
605    }
606
607    public final void onBusEvent(ShowStackActionButtonEvent event) {
608        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
609            return;
610        }
611
612        showStackActionButton(SHOW_STACK_ACTION_BUTTON_DURATION, event.translate);
613    }
614
615    public final void onBusEvent(HideStackActionButtonEvent event) {
616        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
617            return;
618        }
619
620        hideStackActionButton(HIDE_STACK_ACTION_BUTTON_DURATION, true /* translate */);
621    }
622
623    /**
624     * Shows the stack action button.
625     */
626    private void showStackActionButton(final int duration, final boolean translate) {
627        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
628            return;
629        }
630
631        final ReferenceCountedTrigger postAnimationTrigger = new ReferenceCountedTrigger();
632        if (mStackActionButton.getVisibility() == View.INVISIBLE) {
633            mStackActionButton.setVisibility(View.VISIBLE);
634            mStackActionButton.setAlpha(0f);
635            if (translate) {
636                mStackActionButton.setTranslationY(-mStackActionButton.getMeasuredHeight() * 0.25f);
637            } else {
638                mStackActionButton.setTranslationY(0f);
639            }
640            postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
641                @Override
642                public void run() {
643                    if (translate) {
644                        mStackActionButton.animate()
645                            .translationY(0f);
646                    }
647                    mStackActionButton.animate()
648                            .alpha(1f)
649                            .setDuration(duration)
650                            .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
651                            .start();
652                }
653            });
654        }
655        postAnimationTrigger.flushLastDecrementRunnables();
656    }
657
658    /**
659     * Hides the stack action button.
660     */
661    private void hideStackActionButton(int duration, boolean translate) {
662        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
663            return;
664        }
665
666        final ReferenceCountedTrigger postAnimationTrigger = new ReferenceCountedTrigger();
667        hideStackActionButton(duration, translate, postAnimationTrigger);
668        postAnimationTrigger.flushLastDecrementRunnables();
669    }
670
671    /**
672     * Hides the stack action button.
673     */
674    private void hideStackActionButton(int duration, boolean translate,
675                                       final ReferenceCountedTrigger postAnimationTrigger) {
676        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
677            return;
678        }
679
680        if (mStackActionButton.getVisibility() == View.VISIBLE) {
681            if (translate) {
682                mStackActionButton.animate()
683                    .translationY(-mStackActionButton.getMeasuredHeight() * 0.25f);
684            }
685            mStackActionButton.animate()
686                    .alpha(0f)
687                    .setDuration(duration)
688                    .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
689                    .withEndAction(new Runnable() {
690                        @Override
691                        public void run() {
692                            mStackActionButton.setVisibility(View.INVISIBLE);
693                            postAnimationTrigger.decrement();
694                        }
695                    })
696                    .start();
697            postAnimationTrigger.increment();
698        }
699    }
700
701    /**
702     * Updates the dock region to match the specified dock state.
703     */
704    private void updateVisibleDockRegions(TaskStack.DockState[] newDockStates,
705            boolean isDefaultDockState, int overrideAlpha, boolean animateAlpha,
706            boolean animateBounds) {
707        ArraySet<TaskStack.DockState> newDockStatesSet = Utilities.arrayToSet(newDockStates,
708                new ArraySet<TaskStack.DockState>());
709        ArrayList<TaskStack.DockState> visDockStates = mTouchHandler.getVisibleDockStates();
710        for (int i = visDockStates.size() - 1; i >= 0; i--) {
711            TaskStack.DockState dockState = visDockStates.get(i);
712            TaskStack.DockState.ViewState viewState = dockState.viewState;
713            if (newDockStates == null || !newDockStatesSet.contains(dockState)) {
714                // This is no longer visible, so hide it
715                viewState.startAnimation(null, 0, DOCK_AREA_OVERLAY_TRANSITION_DURATION,
716                        Interpolators.ALPHA_OUT, animateAlpha, animateBounds);
717            } else {
718                // This state is now visible, update the bounds and show it
719                int alpha = (overrideAlpha != -1 ? overrideAlpha : viewState.dockAreaAlpha);
720                Rect bounds = isDefaultDockState
721                        ? dockState.getPreDockedBounds(getMeasuredWidth(), getMeasuredHeight())
722                        : dockState.getDockedBounds(getMeasuredWidth(), getMeasuredHeight(),
723                        mDividerSize, mSystemInsets, getResources());
724                if (viewState.dockAreaOverlay.getCallback() != this) {
725                    viewState.dockAreaOverlay.setCallback(this);
726                    viewState.dockAreaOverlay.setBounds(bounds);
727                }
728                viewState.startAnimation(bounds, alpha, DOCK_AREA_OVERLAY_TRANSITION_DURATION,
729                        Interpolators.ALPHA_IN, animateAlpha, animateBounds);
730            }
731        }
732    }
733
734    /**
735     * Animates the background scrim to the given {@param alpha}.
736     */
737    private void animateBackgroundScrim(float alpha, int duration) {
738        Utilities.cancelAnimationWithoutCallbacks(mBackgroundScrimAnimator);
739        // Calculate the absolute alpha to animate from
740        int fromAlpha = (int) ((mBackgroundScrim.getAlpha() / (DEFAULT_SCRIM_ALPHA * 255)) * 255);
741        int toAlpha = (int) (alpha * 255);
742        mBackgroundScrimAnimator = ObjectAnimator.ofInt(mBackgroundScrim, Utilities.DRAWABLE_ALPHA,
743                fromAlpha, toAlpha);
744        mBackgroundScrimAnimator.setDuration(duration);
745        mBackgroundScrimAnimator.setInterpolator(toAlpha > fromAlpha
746                ? Interpolators.ALPHA_IN
747                : Interpolators.ALPHA_OUT);
748        mBackgroundScrimAnimator.start();
749    }
750
751    /**
752     * @return the bounds of the stack action button.
753     */
754    private Rect getStackActionButtonBoundsFromStackLayout() {
755        Rect actionButtonRect = new Rect(mTaskStackView.mLayoutAlgorithm.mStackActionButtonRect);
756        int left = isLayoutRtl()
757                ? actionButtonRect.left - mStackActionButton.getPaddingLeft()
758                : actionButtonRect.right + mStackActionButton.getPaddingRight()
759                        - mStackActionButton.getMeasuredWidth();
760        int top = actionButtonRect.top +
761                (actionButtonRect.height() - mStackActionButton.getMeasuredHeight()) / 2;
762        actionButtonRect.set(left, top, left + mStackActionButton.getMeasuredWidth(),
763                top + mStackActionButton.getMeasuredHeight());
764        return actionButtonRect;
765    }
766
767    public void dump(String prefix, PrintWriter writer) {
768        String innerPrefix = prefix + "  ";
769        String id = Integer.toHexString(System.identityHashCode(this));
770
771        writer.print(prefix); writer.print(TAG);
772        writer.print(" awaitingFirstLayout="); writer.print(mAwaitingFirstLayout ? "Y" : "N");
773        writer.print(" insets="); writer.print(Utilities.dumpRect(mSystemInsets));
774        writer.print(" [0x"); writer.print(id); writer.print("]");
775        writer.println();
776
777        if (mStack != null) {
778            mStack.dump(innerPrefix, writer);
779        }
780        if (mTaskStackView != null) {
781            mTaskStackView.dump(innerPrefix, writer);
782        }
783    }
784}
785