RecentsView.java revision c54c748ede08ee79dee2397d2e0820a4067ab3aa
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.DragEndCancelledEvent;
68import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
69import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
70import com.android.systemui.recents.misc.ReferenceCountedTrigger;
71import com.android.systemui.recents.misc.SystemServicesProxy;
72import com.android.systemui.recents.misc.Utilities;
73import com.android.systemui.recents.model.Task;
74import com.android.systemui.recents.model.TaskStack;
75import com.android.systemui.recents.views.RecentsTransitionHelper.AnimationSpecComposer;
76import com.android.systemui.stackdivider.WindowManagerProxy;
77import com.android.systemui.statusbar.FlingAnimationUtils;
78
79import java.io.FileDescriptor;
80import java.io.PrintWriter;
81import java.util.ArrayList;
82import java.util.List;
83
84/**
85 * This view is the the top level layout that contains TaskStacks (which are laid out according
86 * to their SpaceNode bounds.
87 */
88public class RecentsView extends FrameLayout {
89
90    private static final String TAG = "RecentsView";
91
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 = 134;
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            mStackActionButton = (TextView) inflater.inflate(R.layout.recents_stack_action_button,
144                    this, false);
145            mStackActionButton.setOnClickListener(new View.OnClickListener() {
146                @Override
147                public void onClick(View v) {
148                    EventBus.getDefault().send(new DismissAllTaskViewsEvent());
149                }
150            });
151            addView(mStackActionButton);
152        }
153        mEmptyView = (TextView) inflater.inflate(R.layout.recents_empty, this, false);
154        addView(mEmptyView);
155    }
156
157    /**
158     * Called from RecentsActivity when it is relaunched.
159     */
160    public void onReload(boolean isResumingFromVisible, boolean isTaskStackEmpty) {
161        RecentsConfiguration config = Recents.getConfiguration();
162        RecentsActivityLaunchState launchState = config.getLaunchState();
163
164        if (mTaskStackView == null) {
165            isResumingFromVisible = false;
166            mTaskStackView = new TaskStackView(getContext());
167            mTaskStackView.setSystemInsets(mSystemInsets);
168            addView(mTaskStackView);
169        }
170
171        // Reset the state
172        mAwaitingFirstLayout = !isResumingFromVisible;
173        mLastTaskLaunchedWasFreeform = false;
174
175        // Update the stack
176        mTaskStackView.onReload(isResumingFromVisible);
177
178        if (isResumingFromVisible) {
179            // If we are already visible, then restore the background scrim
180            animateBackgroundScrim(1f, DEFAULT_UPDATE_SCRIM_DURATION);
181        } else {
182            // If we are already occluded by the app, then set the final background scrim alpha now.
183            // Otherwise, defer until the enter animation completes to animate the scrim alpha with
184            // the tasks for the home animation.
185            if (launchState.launchedViaDockGesture || launchState.launchedFromApp
186                    || isTaskStackEmpty) {
187                mBackgroundScrim.setAlpha(255);
188            } else {
189                mBackgroundScrim.setAlpha(0);
190            }
191        }
192    }
193
194    /**
195     * Called from RecentsActivity when the task stack is updated.
196     */
197    public void updateStack(TaskStack stack, boolean setStackViewTasks) {
198        mStack = stack;
199        if (setStackViewTasks) {
200            mTaskStackView.setTasks(stack, true /* allowNotifyStackChanges */);
201        }
202
203        // Update the top level view's visibilities
204        if (stack.getTaskCount() > 0) {
205            hideEmptyView();
206        } else {
207            showEmptyView(R.string.recents_empty_message);
208        }
209    }
210
211    /**
212     * Returns the current TaskStack.
213     */
214    public TaskStack getStack() {
215        return mStack;
216    }
217
218    /*
219     * Returns the window background scrim.
220     */
221    public Drawable getBackgroundScrim() {
222        return mBackgroundScrim;
223    }
224
225    /**
226     * Returns whether the nav bar is on the right.
227     */
228    public boolean isNavBarOnRight() {
229        return mSystemInsets.right > 0;
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            visDockStates.get(i).viewState.draw(canvas);
428        }
429    }
430
431    @Override
432    protected boolean verifyDrawable(Drawable who) {
433        ArrayList<TaskStack.DockState> visDockStates = mTouchHandler.getVisibleDockStates();
434        for (int i = visDockStates.size() - 1; i >= 0; i--) {
435            Drawable d = visDockStates.get(i).viewState.dockAreaOverlay;
436            if (d == who) {
437                return true;
438            }
439        }
440        return super.verifyDrawable(who);
441    }
442
443    /**** EventBus Events ****/
444
445    public final void onBusEvent(LaunchTaskEvent event) {
446        mLastTaskLaunchedWasFreeform = event.task.isFreeformTask();
447        mTransitionHelper.launchTaskFromRecents(mStack, event.task, mTaskStackView, event.taskView,
448                event.screenPinningRequested, event.targetTaskBounds, event.targetTaskStack);
449    }
450
451    public final void onBusEvent(DismissRecentsToHomeAnimationStarted event) {
452        int taskViewExitToHomeDuration = TaskStackAnimationHelper.EXIT_TO_HOME_TRANSLATION_DURATION;
453        if (RecentsDebugFlags.Static.EnableStackActionButton) {
454            // Hide the stack action button
455            hideStackActionButton(taskViewExitToHomeDuration, false /* translate */);
456        }
457        animateBackgroundScrim(0f, taskViewExitToHomeDuration);
458    }
459
460    public final void onBusEvent(DragStartEvent event) {
461        updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
462                true /* isDefaultDockState */, TaskStack.DockState.NONE.viewState.dockAreaAlpha,
463                TaskStack.DockState.NONE.viewState.hintTextAlpha,
464                true /* animateAlpha */, false /* animateBounds */);
465
466        // Temporarily hide the stack action button without changing visibility
467        if (mStackActionButton != null) {
468            mStackActionButton.animate()
469                    .alpha(0f)
470                    .setDuration(HIDE_STACK_ACTION_BUTTON_DURATION)
471                    .setInterpolator(Interpolators.ALPHA_OUT)
472                    .start();
473        }
474    }
475
476    public final void onBusEvent(DragDropTargetChangedEvent event) {
477        if (event.dropTarget == null || !(event.dropTarget instanceof TaskStack.DockState)) {
478            updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
479                    true /* isDefaultDockState */, TaskStack.DockState.NONE.viewState.dockAreaAlpha,
480                    TaskStack.DockState.NONE.viewState.hintTextAlpha,
481                    true /* animateAlpha */, true /* animateBounds */);
482        } else {
483            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
484            updateVisibleDockRegions(new TaskStack.DockState[] {dockState},
485                    false /* isDefaultDockState */, -1, -1, true /* animateAlpha */,
486                    true /* animateBounds */);
487        }
488        if (mStackActionButton != null) {
489            event.addPostAnimationCallback(new Runnable() {
490                @Override
491                public void run() {
492                    // Move the clear all button to its new position
493                    Rect buttonBounds = getStackActionButtonBoundsFromStackLayout();
494                    mStackActionButton.setLeftTopRightBottom(buttonBounds.left, buttonBounds.top,
495                            buttonBounds.right, buttonBounds.bottom);
496                }
497            });
498        }
499    }
500
501    public final void onBusEvent(final DragEndEvent event) {
502        // Handle the case where we drop onto a dock region
503        if (event.dropTarget instanceof TaskStack.DockState) {
504            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
505
506            // Hide the dock region
507            updateVisibleDockRegions(null, false /* isDefaultDockState */, -1, -1,
508                    false /* animateAlpha */, false /* animateBounds */);
509
510            // We translated the view but we need to animate it back from the current layout-space
511            // rect to its final layout-space rect
512            Utilities.setViewFrameFromTranslation(event.taskView);
513
514            // Dock the task and launch it
515            SystemServicesProxy ssp = Recents.getSystemServices();
516            if (ssp.startTaskInDockedMode(event.task.key.id, dockState.createMode)) {
517                final OnAnimationStartedListener startedListener =
518                        new OnAnimationStartedListener() {
519                    @Override
520                    public void onAnimationStarted() {
521                        EventBus.getDefault().send(new DockedFirstAnimationFrameEvent());
522                        // Remove the task and don't bother relaying out, as all the tasks will be
523                        // relaid out when the stack changes on the multiwindow change event
524                        mTaskStackView.getStack().removeTask(event.task, null,
525                                true /* fromDockGesture */);
526                    }
527                };
528
529                final Rect taskRect = getTaskRect(event.taskView);
530                IAppTransitionAnimationSpecsFuture future =
531                        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                EventBus.getDefault().send(new DragEndCancelledEvent(mStack, event.task,
547                        event.taskView));
548            }
549        } else {
550            // Animate the overlay alpha back to 0
551            updateVisibleDockRegions(null, true /* isDefaultDockState */, -1, -1,
552                    true /* animateAlpha */, false /* animateBounds */);
553        }
554
555        // Show the stack action button again without changing visibility
556        if (mStackActionButton != null) {
557            mStackActionButton.animate()
558                    .alpha(1f)
559                    .setDuration(SHOW_STACK_ACTION_BUTTON_DURATION)
560                    .setInterpolator(Interpolators.ALPHA_IN)
561                    .start();
562        }
563    }
564
565    public final void onBusEvent(final DragEndCancelledEvent event) {
566        // Animate the overlay alpha back to 0
567        updateVisibleDockRegions(null, true /* isDefaultDockState */, -1, -1,
568                true /* animateAlpha */, false /* animateBounds */);
569    }
570
571    private Rect getTaskRect(TaskView taskView) {
572        int[] location = taskView.getLocationOnScreen();
573        int viewX = location[0];
574        int viewY = location[1];
575        return new Rect(viewX, viewY,
576                (int) (viewX + taskView.getWidth() * taskView.getScaleX()),
577                (int) (viewY + taskView.getHeight() * taskView.getScaleY()));
578    }
579
580    public final void onBusEvent(DraggingInRecentsEvent event) {
581        if (mTaskStackView.getTaskViews().size() > 0) {
582            setTranslationY(event.distanceFromTop - mTaskStackView.getTaskViews().get(0).getY());
583        }
584    }
585
586    public final void onBusEvent(DraggingInRecentsEndedEvent event) {
587        ViewPropertyAnimator animator = animate();
588        if (event.velocity > mFlingAnimationUtils.getMinVelocityPxPerSecond()) {
589            animator.translationY(getHeight());
590            animator.withEndAction(new Runnable() {
591                @Override
592                public void run() {
593                    WindowManagerProxy.getInstance().maximizeDockedStack();
594                }
595            });
596            mFlingAnimationUtils.apply(animator, getTranslationY(), getHeight(), event.velocity);
597        } else {
598            animator.translationY(0f);
599            animator.setListener(null);
600            mFlingAnimationUtils.apply(animator, getTranslationY(), 0, event.velocity);
601        }
602        animator.start();
603    }
604
605    public final void onBusEvent(EnterRecentsWindowAnimationCompletedEvent event) {
606        RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
607        if (!launchState.launchedViaDockGesture && !launchState.launchedFromApp
608                && mStack.getTaskCount() > 0) {
609            animateBackgroundScrim(1f,
610                    TaskStackAnimationHelper.ENTER_FROM_HOME_TRANSLATION_DURATION);
611        }
612    }
613
614    public final void onBusEvent(AllTaskViewsDismissedEvent event) {
615        hideStackActionButton(HIDE_STACK_ACTION_BUTTON_DURATION, true /* translate */);
616    }
617
618    public final void onBusEvent(DismissAllTaskViewsEvent event) {
619        SystemServicesProxy ssp = Recents.getSystemServices();
620        if (!ssp.hasDockedTask()) {
621            // Animate the background away only if we are dismissing Recents to home
622            animateBackgroundScrim(0f, DEFAULT_UPDATE_SCRIM_DURATION);
623        }
624    }
625
626    public final void onBusEvent(ShowStackActionButtonEvent event) {
627        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
628            return;
629        }
630
631        showStackActionButton(SHOW_STACK_ACTION_BUTTON_DURATION, event.translate);
632    }
633
634    public final void onBusEvent(HideStackActionButtonEvent event) {
635        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
636            return;
637        }
638
639        hideStackActionButton(HIDE_STACK_ACTION_BUTTON_DURATION, true /* translate */);
640    }
641
642    public final void onBusEvent(MultiWindowStateChangedEvent event) {
643        updateStack(event.stack, false /* setStackViewTasks */);
644    }
645
646    /**
647     * Shows the stack action button.
648     */
649    private void showStackActionButton(final int duration, final boolean translate) {
650        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
651            return;
652        }
653
654        final ReferenceCountedTrigger postAnimationTrigger = new ReferenceCountedTrigger();
655        if (mStackActionButton.getVisibility() == View.INVISIBLE) {
656            mStackActionButton.setVisibility(View.VISIBLE);
657            mStackActionButton.setAlpha(0f);
658            if (translate) {
659                mStackActionButton.setTranslationY(-mStackActionButton.getMeasuredHeight() * 0.25f);
660            } else {
661                mStackActionButton.setTranslationY(0f);
662            }
663            postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
664                @Override
665                public void run() {
666                    if (translate) {
667                        mStackActionButton.animate()
668                            .translationY(0f);
669                    }
670                    mStackActionButton.animate()
671                            .alpha(1f)
672                            .setDuration(duration)
673                            .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
674                            .start();
675                }
676            });
677        }
678        postAnimationTrigger.flushLastDecrementRunnables();
679    }
680
681    /**
682     * Hides the stack action button.
683     */
684    private void hideStackActionButton(int duration, boolean translate) {
685        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
686            return;
687        }
688
689        final ReferenceCountedTrigger postAnimationTrigger = new ReferenceCountedTrigger();
690        hideStackActionButton(duration, translate, postAnimationTrigger);
691        postAnimationTrigger.flushLastDecrementRunnables();
692    }
693
694    /**
695     * Hides the stack action button.
696     */
697    private void hideStackActionButton(int duration, boolean translate,
698                                       final ReferenceCountedTrigger postAnimationTrigger) {
699        if (!RecentsDebugFlags.Static.EnableStackActionButton) {
700            return;
701        }
702
703        if (mStackActionButton.getVisibility() == View.VISIBLE) {
704            if (translate) {
705                mStackActionButton.animate()
706                    .translationY(-mStackActionButton.getMeasuredHeight() * 0.25f);
707            }
708            mStackActionButton.animate()
709                    .alpha(0f)
710                    .setDuration(duration)
711                    .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
712                    .withEndAction(new Runnable() {
713                        @Override
714                        public void run() {
715                            mStackActionButton.setVisibility(View.INVISIBLE);
716                            postAnimationTrigger.decrement();
717                        }
718                    })
719                    .start();
720            postAnimationTrigger.increment();
721        }
722    }
723
724    /**
725     * Updates the dock region to match the specified dock state.
726     */
727    private void updateVisibleDockRegions(TaskStack.DockState[] newDockStates,
728            boolean isDefaultDockState, int overrideAreaAlpha, int overrideHintAlpha,
729            boolean animateAlpha, boolean animateBounds) {
730        ArraySet<TaskStack.DockState> newDockStatesSet = Utilities.arrayToSet(newDockStates,
731                new ArraySet<TaskStack.DockState>());
732        ArrayList<TaskStack.DockState> visDockStates = mTouchHandler.getVisibleDockStates();
733        for (int i = visDockStates.size() - 1; i >= 0; i--) {
734            TaskStack.DockState dockState = visDockStates.get(i);
735            TaskStack.DockState.ViewState viewState = dockState.viewState;
736            if (newDockStates == null || !newDockStatesSet.contains(dockState)) {
737                // This is no longer visible, so hide it
738                viewState.startAnimation(null, 0, 0, TaskStackView.SLOW_SYNC_STACK_DURATION,
739                        Interpolators.FAST_OUT_SLOW_IN, animateAlpha, animateBounds);
740            } else {
741                // This state is now visible, update the bounds and show it
742                int areaAlpha = overrideAreaAlpha != -1
743                        ? overrideAreaAlpha
744                        : viewState.dockAreaAlpha;
745                int hintAlpha = overrideHintAlpha != -1
746                        ? overrideHintAlpha
747                        : viewState.hintTextAlpha;
748                Rect bounds = isDefaultDockState
749                        ? dockState.getPreDockedBounds(getMeasuredWidth(), getMeasuredHeight())
750                        : dockState.getDockedBounds(getMeasuredWidth(), getMeasuredHeight(),
751                        mDividerSize, mSystemInsets, getResources());
752                if (viewState.dockAreaOverlay.getCallback() != this) {
753                    viewState.dockAreaOverlay.setCallback(this);
754                    viewState.dockAreaOverlay.setBounds(bounds);
755                }
756                viewState.startAnimation(bounds, areaAlpha, hintAlpha,
757                        TaskStackView.SLOW_SYNC_STACK_DURATION, Interpolators.FAST_OUT_SLOW_IN,
758                        animateAlpha, animateBounds);
759            }
760        }
761    }
762
763    /**
764     * Animates the background scrim to the given {@param alpha}.
765     */
766    private void animateBackgroundScrim(float alpha, int duration) {
767        Utilities.cancelAnimationWithoutCallbacks(mBackgroundScrimAnimator);
768        // Calculate the absolute alpha to animate from
769        int fromAlpha = (int) ((mBackgroundScrim.getAlpha() / (DEFAULT_SCRIM_ALPHA * 255)) * 255);
770        int toAlpha = (int) (alpha * 255);
771        mBackgroundScrimAnimator = ObjectAnimator.ofInt(mBackgroundScrim, Utilities.DRAWABLE_ALPHA,
772                fromAlpha, toAlpha);
773        mBackgroundScrimAnimator.setDuration(duration);
774        mBackgroundScrimAnimator.setInterpolator(toAlpha > fromAlpha
775                ? Interpolators.ALPHA_IN
776                : Interpolators.ALPHA_OUT);
777        mBackgroundScrimAnimator.start();
778    }
779
780    /**
781     * @return the bounds of the stack action button.
782     */
783    private Rect getStackActionButtonBoundsFromStackLayout() {
784        Rect actionButtonRect = new Rect(mTaskStackView.mLayoutAlgorithm.mStackActionButtonRect);
785        int left = isLayoutRtl()
786                ? actionButtonRect.left - mStackActionButton.getPaddingLeft()
787                : actionButtonRect.right + mStackActionButton.getPaddingRight()
788                        - mStackActionButton.getMeasuredWidth();
789        int top = actionButtonRect.top +
790                (actionButtonRect.height() - mStackActionButton.getMeasuredHeight()) / 2;
791        actionButtonRect.set(left, top, left + mStackActionButton.getMeasuredWidth(),
792                top + mStackActionButton.getMeasuredHeight());
793        return actionButtonRect;
794    }
795
796    public void dump(String prefix, PrintWriter writer) {
797        String innerPrefix = prefix + "  ";
798        String id = Integer.toHexString(System.identityHashCode(this));
799
800        writer.print(prefix); writer.print(TAG);
801        writer.print(" awaitingFirstLayout="); writer.print(mAwaitingFirstLayout ? "Y" : "N");
802        writer.print(" insets="); writer.print(Utilities.dumpRect(mSystemInsets));
803        writer.print(" [0x"); writer.print(id); writer.print("]");
804        writer.println();
805
806        if (mStack != null) {
807            mStack.dump(innerPrefix, writer);
808        }
809        if (mTaskStackView != null) {
810            mTaskStackView.dump(innerPrefix, writer);
811        }
812    }
813}
814