RecentsView.java revision 479f7446cf489fb99c91b3fc2bf96b1dc184f5ba
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.systemui.recents.views;
18
19import android.content.Context;
20import android.content.res.Resources;
21import android.graphics.Canvas;
22import android.graphics.Rect;
23import android.graphics.drawable.Drawable;
24import android.os.Handler;
25import android.util.ArraySet;
26import android.util.AttributeSet;
27import android.view.LayoutInflater;
28import android.view.MotionEvent;
29import android.view.View;
30import android.view.WindowInsets;
31import android.view.animation.AnimationUtils;
32import android.view.animation.Interpolator;
33import android.widget.FrameLayout;
34import com.android.systemui.R;
35import com.android.systemui.recents.Recents;
36import com.android.systemui.recents.RecentsActivity;
37import com.android.systemui.recents.RecentsActivityLaunchState;
38import com.android.systemui.recents.RecentsAppWidgetHostView;
39import com.android.systemui.recents.RecentsConfiguration;
40import com.android.systemui.recents.RecentsDebugFlags;
41import com.android.systemui.recents.events.EventBus;
42import com.android.systemui.recents.events.activity.CancelEnterRecentsWindowAnimationEvent;
43import com.android.systemui.recents.events.activity.DebugFlagsChangedEvent;
44import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
45import com.android.systemui.recents.events.activity.HideHistoryButtonEvent;
46import com.android.systemui.recents.events.activity.HideHistoryEvent;
47import com.android.systemui.recents.events.activity.ShowHistoryButtonEvent;
48import com.android.systemui.recents.events.activity.ShowHistoryEvent;
49import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent;
50import com.android.systemui.recents.events.ui.DraggingInRecentsEndedEvent;
51import com.android.systemui.recents.events.ui.DraggingInRecentsEvent;
52import com.android.systemui.recents.events.ui.dragndrop.DragDropTargetChangedEvent;
53import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
54import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
55import com.android.systemui.recents.misc.SystemServicesProxy;
56import com.android.systemui.recents.model.Task;
57import com.android.systemui.recents.model.TaskStack;
58
59import java.util.ArrayList;
60import java.util.List;
61
62import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
63
64/**
65 * This view is the the top level layout that contains TaskStacks (which are laid out according
66 * to their SpaceNode bounds.
67 */
68public class RecentsView extends FrameLayout implements TaskStackView.TaskStackViewCallbacks {
69
70    private static final String TAG = "RecentsView";
71    private static final boolean DEBUG = false;
72
73    Handler mHandler;
74
75    TaskStack mStack;
76    TaskStackView mTaskStackView;
77    RecentsAppWidgetHostView mSearchBar;
78    View mHistoryButton;
79    boolean mAwaitingFirstLayout = true;
80    boolean mLastTaskLaunchedWasFreeform;
81
82    RecentsTransitionHelper mTransitionHelper;
83    RecentsViewTouchHandler mTouchHandler;
84    TaskStack.DockState[] mVisibleDockStates = {
85            TaskStack.DockState.LEFT,
86            TaskStack.DockState.TOP,
87            TaskStack.DockState.RIGHT,
88            TaskStack.DockState.BOTTOM,
89    };
90
91    private Interpolator mFastOutSlowInInterpolator;
92    private Interpolator mFastOutLinearInInterpolator;
93    private int mHistoryTransitionDuration;
94
95    Rect mSystemInsets = new Rect();
96
97    public RecentsView(Context context) {
98        super(context);
99    }
100
101    public RecentsView(Context context, AttributeSet attrs) {
102        this(context, attrs, 0);
103    }
104
105    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr) {
106        this(context, attrs, defStyleAttr, 0);
107    }
108
109    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
110        super(context, attrs, defStyleAttr, defStyleRes);
111        Resources res = context.getResources();
112        setWillNotDraw(false);
113        mHandler = new Handler();
114        mTransitionHelper = new RecentsTransitionHelper(getContext(), mHandler);
115        mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context,
116                com.android.internal.R.interpolator.fast_out_slow_in);
117        mFastOutLinearInInterpolator = AnimationUtils.loadInterpolator(context,
118                com.android.internal.R.interpolator.fast_out_linear_in);
119        mHistoryTransitionDuration = res.getInteger(R.integer.recents_history_transition_duration);
120        mTouchHandler = new RecentsViewTouchHandler(this);
121
122        LayoutInflater inflater = LayoutInflater.from(context);
123        mHistoryButton = inflater.inflate(R.layout.recents_history_button, this, false);
124        mHistoryButton.setOnClickListener(new View.OnClickListener() {
125            @Override
126            public void onClick(View v) {
127                EventBus.getDefault().send(new ShowHistoryEvent());
128            }
129        });
130    }
131
132    /** Set/get the bsp root node */
133    public void setTaskStack(TaskStack stack) {
134        RecentsConfiguration config = Recents.getConfiguration();
135        mStack = stack;
136        if (config.getLaunchState().launchedReuseTaskStackViews) {
137            if (mTaskStackView != null) {
138                // If onRecentsHidden is not triggered, we need to the stack view again here
139                mTaskStackView.reset();
140                mTaskStackView.setStack(stack);
141            } else {
142                mTaskStackView = new TaskStackView(getContext(), stack);
143                mTaskStackView.setCallbacks(this);
144                addView(mTaskStackView);
145            }
146        } else {
147            if (mTaskStackView != null) {
148                removeView(mTaskStackView);
149            }
150            mTaskStackView = new TaskStackView(getContext(), stack);
151            mTaskStackView.setCallbacks(this);
152            addView(mTaskStackView);
153        }
154        if (indexOfChild(mHistoryButton) == -1) {
155            addView(mHistoryButton);
156        } else {
157            mHistoryButton.bringToFront();
158        }
159
160        // Trigger a new layout
161        requestLayout();
162    }
163
164    /**
165     * Returns whether the last task launched was in the freeform stack or not.
166     */
167    public boolean isLastTaskLaunchedFreeform() {
168        return mLastTaskLaunchedWasFreeform;
169    }
170
171    /**
172     * Returns the currently set task stack.
173     */
174    public TaskStack getTaskStack() {
175        return mStack;
176    }
177
178    /** Gets the next task in the stack - or if the last - the top task */
179    public Task getNextTaskOrTopTask(Task taskToSearch) {
180        Task returnTask = null;
181        boolean found = false;
182        if (mTaskStackView != null) {
183            TaskStack stack = mTaskStackView.getStack();
184            ArrayList<Task> taskList = stack.getStackTasks();
185            // Iterate the stack views and try and find the focused task
186            for (int j = taskList.size() - 1; j >= 0; --j) {
187                Task task = taskList.get(j);
188                // Return the next task in the line.
189                if (found)
190                    return task;
191                // Remember the first possible task as the top task.
192                if (returnTask == null)
193                    returnTask = task;
194                if (task == taskToSearch)
195                    found = true;
196            }
197        }
198        return returnTask;
199    }
200
201    /** Launches the focused task from the first stack if possible */
202    public boolean launchFocusedTask() {
203        if (mTaskStackView != null) {
204            TaskStack stack = mTaskStackView.getStack();
205            Task task = mTaskStackView.getFocusedTask();
206            if (task != null) {
207                TaskView taskView = mTaskStackView.getChildViewForTask(task);
208                onTaskViewClicked(mTaskStackView, taskView, stack, task, false, null,
209                        INVALID_STACK_ID);
210                return true;
211            }
212        }
213        return false;
214    }
215
216    /** Launches a given task. */
217    public boolean launchTask(Task task, Rect taskBounds, int destinationStack) {
218        if (mTaskStackView != null) {
219            TaskStack stack = mTaskStackView.getStack();
220            // Iterate the stack views and try and find the given task.
221            List<TaskView> taskViews = mTaskStackView.getTaskViews();
222            int taskViewCount = taskViews.size();
223            for (int j = 0; j < taskViewCount; j++) {
224                TaskView tv = taskViews.get(j);
225                if (tv.getTask() == task) {
226                    onTaskViewClicked(mTaskStackView, tv, stack, task, false,
227                            taskBounds, destinationStack);
228                    return true;
229                }
230            }
231        }
232        return false;
233    }
234
235    /** Requests all task stacks to start their enter-recents animation */
236    public void startEnterRecentsAnimation(ViewAnimation.TaskViewEnterContext ctx) {
237        // We have to increment/decrement the post animation trigger in case there are no children
238        // to ensure that it runs
239        ctx.postAnimationTrigger.increment();
240        if (mTaskStackView != null) {
241            mTaskStackView.startEnterRecentsAnimation(ctx);
242        }
243        ctx.postAnimationTrigger.decrement();
244    }
245
246    /** Requests all task stacks to start their exit-recents animation */
247    public void startExitToHomeAnimation(ViewAnimation.TaskViewExitContext ctx) {
248        // We have to increment/decrement the post animation trigger in case there are no children
249        // to ensure that it runs
250        ctx.postAnimationTrigger.increment();
251        if (mTaskStackView != null) {
252            mTaskStackView.startExitToHomeAnimation(ctx);
253        }
254        ctx.postAnimationTrigger.decrement();
255
256        // Hide the history button
257        int taskViewExitToHomeDuration = getResources().getInteger(
258                R.integer.recents_task_exit_to_home_duration);
259        hideHistoryButton(taskViewExitToHomeDuration);
260
261        // If we are going home, cancel the previous task's window transition
262        EventBus.getDefault().send(new CancelEnterRecentsWindowAnimationEvent(null));
263
264        // Notify sof the exit animation
265        EventBus.getDefault().send(new DismissRecentsToHomeAnimationStarted());
266    }
267
268    /** Adds the search bar */
269    public void setSearchBar(RecentsAppWidgetHostView searchBar) {
270        // Remove the previous search bar if one exists
271        if (mSearchBar != null && indexOfChild(mSearchBar) > -1) {
272            removeView(mSearchBar);
273        }
274        // Add the new search bar
275        if (searchBar != null) {
276            mSearchBar = searchBar;
277            addView(mSearchBar);
278        }
279    }
280
281    /** Returns whether there is currently a search bar */
282    public boolean hasValidSearchBar() {
283        return mSearchBar != null && !mSearchBar.isReinflateRequired();
284    }
285
286    /** Sets the visibility of the search bar */
287    public void setSearchBarVisibility(int visibility) {
288        if (mSearchBar != null) {
289            mSearchBar.setVisibility(visibility);
290            // Always bring the search bar to the top
291            mSearchBar.bringToFront();
292        }
293    }
294
295    /**
296     * Returns the last known system insets.
297     */
298    public Rect getSystemInsets() {
299        return mSystemInsets;
300    }
301
302    @Override
303    protected void onAttachedToWindow() {
304        EventBus.getDefault().register(this, RecentsActivity.EVENT_BUS_PRIORITY + 1);
305        EventBus.getDefault().register(mTouchHandler, RecentsActivity.EVENT_BUS_PRIORITY + 1);
306        super.onAttachedToWindow();
307    }
308
309    @Override
310    protected void onDetachedFromWindow() {
311        super.onDetachedFromWindow();
312        EventBus.getDefault().unregister(this);
313        EventBus.getDefault().unregister(mTouchHandler);
314    }
315
316    /**
317     * This is called with the full size of the window since we are handling our own insets.
318     */
319    @Override
320    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
321        RecentsConfiguration config = Recents.getConfiguration();
322        int width = MeasureSpec.getSize(widthMeasureSpec);
323        int height = MeasureSpec.getSize(heightMeasureSpec);
324
325        // Get the search bar bounds and measure the search bar layout
326        Rect searchBarSpaceBounds = new Rect();
327        if (mSearchBar != null) {
328            config.getSearchBarBounds(new Rect(0, 0, width, height), mSystemInsets.top,
329                    searchBarSpaceBounds);
330            mSearchBar.measure(
331                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.width(), MeasureSpec.EXACTLY),
332                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.height(), MeasureSpec.EXACTLY));
333        }
334
335        Rect taskStackBounds = new Rect();
336        config.getTaskStackBounds(new Rect(0, 0, width, height), mSystemInsets.top,
337                mSystemInsets.right, searchBarSpaceBounds, taskStackBounds);
338        if (mTaskStackView != null && mTaskStackView.getVisibility() != GONE) {
339            mTaskStackView.setTaskStackBounds(taskStackBounds, mSystemInsets);
340            mTaskStackView.measure(widthMeasureSpec, heightMeasureSpec);
341        }
342
343        // Measure the history button with the full space above the stack, but width-constrained
344        // to the stack
345        Rect historyButtonRect = mTaskStackView.mLayoutAlgorithm.mHistoryButtonRect;
346        measureChild(mHistoryButton,
347                MeasureSpec.makeMeasureSpec(historyButtonRect.width(), MeasureSpec.EXACTLY),
348                MeasureSpec.makeMeasureSpec(historyButtonRect.height(),
349                        MeasureSpec.EXACTLY));
350        setMeasuredDimension(width, height);
351    }
352
353    /**
354     * This is called with the full size of the window since we are handling our own insets.
355     */
356    @Override
357    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
358        RecentsConfiguration config = Recents.getConfiguration();
359
360        // Get the search bar bounds so that we lay it out
361        Rect measuredRect = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight());
362        Rect searchBarSpaceBounds = new Rect();
363        if (mSearchBar != null) {
364            config.getSearchBarBounds(measuredRect,
365                    mSystemInsets.top, searchBarSpaceBounds);
366            mSearchBar.layout(searchBarSpaceBounds.left, searchBarSpaceBounds.top,
367                    searchBarSpaceBounds.right, searchBarSpaceBounds.bottom);
368        }
369
370        if (mTaskStackView != null && mTaskStackView.getVisibility() != GONE) {
371            mTaskStackView.layout(left, top, left + getMeasuredWidth(), top + getMeasuredHeight());
372        }
373
374        // Layout the history button left-aligned with the stack, but offset from the top of the
375        // view
376        Rect historyButtonRect = mTaskStackView.mLayoutAlgorithm.mHistoryButtonRect;
377        mHistoryButton.layout(historyButtonRect.left, historyButtonRect.top,
378                historyButtonRect.right, historyButtonRect.bottom);
379
380        if (mAwaitingFirstLayout) {
381            mAwaitingFirstLayout = false;
382
383            // If launched via dragging from the nav bar, then we should translate the whole view
384            // down offscreen
385            RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
386            if (launchState.launchedViaDragGesture) {
387                setTranslationY(getMeasuredHeight());
388            }
389        }
390    }
391
392    @Override
393    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
394        mSystemInsets.set(insets.getSystemWindowInsets());
395        requestLayout();
396        return insets;
397    }
398
399    @Override
400    public boolean onInterceptTouchEvent(MotionEvent ev) {
401        return mTouchHandler.onInterceptTouchEvent(ev);
402    }
403
404    @Override
405    public boolean onTouchEvent(MotionEvent ev) {
406        return mTouchHandler.onTouchEvent(ev);
407    }
408
409    @Override
410    protected void dispatchDraw(Canvas canvas) {
411        super.dispatchDraw(canvas);
412        for (int i = mVisibleDockStates.length - 1; i >= 0; i--) {
413            Drawable d = mVisibleDockStates[i].viewState.dockAreaOverlay;
414            if (d.getAlpha() > 0) {
415                d.draw(canvas);
416            }
417        }
418    }
419
420    @Override
421    protected boolean verifyDrawable(Drawable who) {
422        for (int i = mVisibleDockStates.length - 1; i >= 0; i--) {
423            Drawable d = mVisibleDockStates[i].viewState.dockAreaOverlay;
424            if (d == who) {
425                return true;
426            }
427        }
428        return super.verifyDrawable(who);
429    }
430
431    public void disableLayersForOneFrame() {
432        if (mTaskStackView != null) {
433            mTaskStackView.disableLayersForOneFrame();
434        }
435    }
436
437    /**** TaskStackView.TaskStackCallbacks Implementation ****/
438
439    @Override
440    public void onTaskViewClicked(final TaskStackView stackView, final TaskView tv,
441            final TaskStack stack, final Task task, final boolean lockToTask,
442            final Rect bounds, int destinationStack) {
443        mLastTaskLaunchedWasFreeform = task.isFreeformTask();
444        mTransitionHelper.launchTaskFromRecents(stack, task, stackView, tv, lockToTask, bounds,
445                destinationStack);
446    }
447
448    /**** EventBus Events ****/
449
450    public final void onBusEvent(DragStartEvent event) {
451        updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
452                TaskStack.DockState.NONE.viewState.dockAreaAlpha);
453    }
454
455    public final void onBusEvent(DragDropTargetChangedEvent event) {
456        if (event.dropTarget == null || !(event.dropTarget instanceof TaskStack.DockState)) {
457            updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
458                    TaskStack.DockState.NONE.viewState.dockAreaAlpha);
459        } else {
460            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
461            updateVisibleDockRegions(new TaskStack.DockState[] {dockState}, -1);
462        }
463    }
464
465    public final void onBusEvent(final DragEndEvent event) {
466        // Animate the overlay alpha back to 0
467        updateVisibleDockRegions(null, -1);
468
469        // Handle the case where we drop onto a dock region
470        if (event.dropTarget instanceof TaskStack.DockState) {
471            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
472
473            // Dock the task and launch it
474            SystemServicesProxy ssp = Recents.getSystemServices();
475            ssp.startTaskInDockedMode(event.task.key.id, dockState.createMode);
476            launchTask(event.task, null, INVALID_STACK_ID);
477        }
478    }
479
480    public final void onBusEvent(DraggingInRecentsEvent event) {
481        if (mTaskStackView.getTaskViews().size() > 0) {
482            setTranslationY(event.distanceFromTop - mTaskStackView.getTaskViews().get(0).getY());
483        }
484    }
485
486    public final void onBusEvent(DraggingInRecentsEndedEvent event) {
487        animate().translationY(0f);
488    }
489
490    public final void onBusEvent(ShowHistoryEvent event) {
491        // Hide the history button when the history view is shown
492        hideHistoryButton(mHistoryTransitionDuration);
493    }
494
495    public final void onBusEvent(HideHistoryEvent event) {
496        // Show the history button when the history view is hidden
497        showHistoryButton(mHistoryTransitionDuration);
498    }
499
500    public final void onBusEvent(ShowHistoryButtonEvent event) {
501        showHistoryButton(150);
502    }
503
504    public final void onBusEvent(HideHistoryButtonEvent event) {
505        hideHistoryButton(100);
506    }
507
508    public final void onBusEvent(DebugFlagsChangedEvent event) {
509        RecentsDebugFlags debugFlags = Recents.getDebugFlags();
510        if (!debugFlags.isHistoryEnabled()) {
511            hideHistoryButton(100);
512        }
513    }
514
515    /**
516     * Shows the history button.
517     */
518    private void showHistoryButton(int duration) {
519        RecentsDebugFlags debugFlags = Recents.getDebugFlags();
520        if (!debugFlags.isHistoryEnabled()) {
521            return;
522        }
523
524        mHistoryButton.setVisibility(View.VISIBLE);
525        mHistoryButton.animate()
526                .alpha(1f)
527                .setDuration(duration)
528                .setInterpolator(mFastOutSlowInInterpolator)
529                .withLayer()
530                .start();
531    }
532
533    /**
534     * Hides the history button.
535     */
536    private void hideHistoryButton(int duration) {
537        mHistoryButton.animate()
538                .alpha(0f)
539                .setDuration(duration)
540                .setInterpolator(mFastOutLinearInInterpolator)
541                .withEndAction(new Runnable() {
542                    @Override
543                    public void run() {
544                        mHistoryButton.setVisibility(View.INVISIBLE);
545                    }
546                })
547                .withLayer()
548                .start();
549    }
550
551    /**
552     * Updates the dock region to match the specified dock state.
553     */
554    private void updateVisibleDockRegions(TaskStack.DockState[] newDockStates, int overrideAlpha) {
555        ArraySet<TaskStack.DockState> newDockStatesSet = new ArraySet<>();
556        if (newDockStates != null) {
557            for (TaskStack.DockState dockState : newDockStates) {
558                newDockStatesSet.add(dockState);
559            }
560        }
561        for (TaskStack.DockState dockState : mVisibleDockStates) {
562            TaskStack.DockState.ViewState viewState = dockState.viewState;
563            if (newDockStates == null || !newDockStatesSet.contains(dockState)) {
564                // This is no longer visible, so hide it
565                viewState.startAlphaAnimation(0, 150);
566            } else {
567                // This state is now visible, update the bounds and show it
568                int alpha = (overrideAlpha != -1 ? overrideAlpha : viewState.dockAreaAlpha);
569                viewState.dockAreaOverlay.setBounds(
570                        dockState.getDockedBounds(getMeasuredWidth(), getMeasuredHeight()));
571                viewState.dockAreaOverlay.setCallback(this);
572                viewState.startAlphaAnimation(alpha, 150);
573            }
574        }
575    }
576
577    public final void onBusEvent(RecentsVisibilityChangedEvent event) {
578        if (!event.visible) {
579            // Reset the view state
580            mAwaitingFirstLayout = true;
581            mLastTaskLaunchedWasFreeform = false;
582        }
583    }
584}
585