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