RecentsView.java revision 805578d8483a53c50896a808b0aec1bf152e5216
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.graphics.Canvas;
21import android.graphics.Rect;
22import android.graphics.drawable.Drawable;
23import android.os.Handler;
24import android.util.ArraySet;
25import android.util.AttributeSet;
26import android.view.LayoutInflater;
27import android.view.MotionEvent;
28import android.view.WindowInsets;
29import android.view.animation.AnimationUtils;
30import android.view.animation.Interpolator;
31import android.widget.FrameLayout;
32import com.android.internal.logging.MetricsLogger;
33import com.android.systemui.R;
34import com.android.systemui.recents.Recents;
35import com.android.systemui.recents.RecentsActivity;
36import com.android.systemui.recents.RecentsActivityLaunchState;
37import com.android.systemui.recents.RecentsAppWidgetHostView;
38import com.android.systemui.recents.RecentsConfiguration;
39import com.android.systemui.recents.events.EventBus;
40import com.android.systemui.recents.events.activity.CancelEnterRecentsWindowAnimationEvent;
41import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
42import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent;
43import com.android.systemui.recents.events.ui.DraggingInRecentsEndedEvent;
44import com.android.systemui.recents.events.ui.DraggingInRecentsEvent;
45import com.android.systemui.recents.events.ui.dragndrop.DragDropTargetChangedEvent;
46import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
47import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
48import com.android.systemui.recents.misc.SystemServicesProxy;
49import com.android.systemui.recents.model.Task;
50import com.android.systemui.recents.model.TaskStack;
51
52import java.util.ArrayList;
53import java.util.List;
54
55import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
56
57/**
58 * This view is the the top level layout that contains TaskStacks (which are laid out according
59 * to their SpaceNode bounds.
60 */
61public class RecentsView extends FrameLayout implements TaskStackView.TaskStackViewCallbacks {
62
63    private static final String TAG = "RecentsView";
64    private static final boolean DEBUG = false;
65
66    LayoutInflater mInflater;
67    Handler mHandler;
68
69    TaskStackView mTaskStackView;
70    RecentsAppWidgetHostView mSearchBar;
71    boolean mAwaitingFirstLayout = true;
72    boolean mLastTaskLaunchedWasFreeform;
73
74    RecentsTransitionHelper mTransitionHelper;
75    RecentsViewTouchHandler mTouchHandler;
76    DragView mDragView;
77    TaskStack.DockState[] mVisibleDockStates = {
78            TaskStack.DockState.LEFT,
79            TaskStack.DockState.TOP,
80            TaskStack.DockState.RIGHT,
81            TaskStack.DockState.BOTTOM,
82    };
83
84    Interpolator mFastOutSlowInInterpolator;
85
86    Rect mSystemInsets = new Rect();
87
88    public RecentsView(Context context) {
89        super(context);
90    }
91
92    public RecentsView(Context context, AttributeSet attrs) {
93        this(context, attrs, 0);
94    }
95
96    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr) {
97        this(context, attrs, defStyleAttr, 0);
98    }
99
100    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
101        super(context, attrs, defStyleAttr, defStyleRes);
102        setWillNotDraw(false);
103        mInflater = LayoutInflater.from(context);
104        mHandler = new Handler();
105        mTransitionHelper = new RecentsTransitionHelper(getContext(), mHandler);
106        mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context,
107                com.android.internal.R.interpolator.fast_out_slow_in);
108        mTouchHandler = new RecentsViewTouchHandler(this);
109    }
110
111    /** Set/get the bsp root node */
112    public void setTaskStack(TaskStack stack) {
113        RecentsConfiguration config = Recents.getConfiguration();
114        if (config.getLaunchState().launchedReuseTaskStackViews) {
115            if (mTaskStackView != null) {
116                // If onRecentsHidden is not triggered, we need to the stack view again here
117                mTaskStackView.reset();
118                mTaskStackView.setStack(stack);
119            } else {
120                mTaskStackView = new TaskStackView(getContext(), stack);
121                mTaskStackView.setCallbacks(this);
122                addView(mTaskStackView);
123            }
124        } else {
125            if (mTaskStackView != null) {
126                removeView(mTaskStackView);
127            }
128            mTaskStackView = new TaskStackView(getContext(), stack);
129            mTaskStackView.setCallbacks(this);
130            addView(mTaskStackView);
131        }
132
133        // Trigger a new layout
134        requestLayout();
135    }
136
137    /**
138     * Returns whether the last task launched was in the freeform stack or not.
139     */
140    public boolean isLastTaskLaunchedFreeform() {
141        return mLastTaskLaunchedWasFreeform;
142    }
143
144    /** Gets the next task in the stack - or if the last - the top task */
145    public Task getNextTaskOrTopTask(Task taskToSearch) {
146        Task returnTask = null;
147        boolean found = false;
148        if (mTaskStackView != null) {
149            TaskStack stack = mTaskStackView.getStack();
150            ArrayList<Task> taskList = stack.getTasks();
151            // Iterate the stack views and try and find the focused task
152            for (int j = taskList.size() - 1; j >= 0; --j) {
153                Task task = taskList.get(j);
154                // Return the next task in the line.
155                if (found)
156                    return task;
157                // Remember the first possible task as the top task.
158                if (returnTask == null)
159                    returnTask = task;
160                if (task == taskToSearch)
161                    found = true;
162            }
163        }
164        return returnTask;
165    }
166
167    /** Launches the focused task from the first stack if possible */
168    public boolean launchFocusedTask() {
169        if (mTaskStackView != null) {
170            TaskStack stack = mTaskStackView.getStack();
171            Task task = mTaskStackView.getFocusedTask();
172            if (task != null) {
173                TaskView taskView = mTaskStackView.getChildViewForTask(task);
174                onTaskViewClicked(mTaskStackView, taskView, stack, task, false, null,
175                        INVALID_STACK_ID);
176                return true;
177            }
178        }
179        return false;
180    }
181
182    /** Launches a given task. */
183    public boolean launchTask(Task task, Rect taskBounds, int destinationStack) {
184        if (mTaskStackView != null) {
185            TaskStack stack = mTaskStackView.getStack();
186            // Iterate the stack views and try and find the given task.
187            List<TaskView> taskViews = mTaskStackView.getTaskViews();
188            int taskViewCount = taskViews.size();
189            for (int j = 0; j < taskViewCount; j++) {
190                TaskView tv = taskViews.get(j);
191                if (tv.getTask() == task) {
192                    onTaskViewClicked(mTaskStackView, tv, stack, task, false,
193                            taskBounds, destinationStack);
194                    return true;
195                }
196            }
197        }
198        return false;
199    }
200
201    /** Requests all task stacks to start their enter-recents animation */
202    public void startEnterRecentsAnimation(ViewAnimation.TaskViewEnterContext ctx) {
203        // We have to increment/decrement the post animation trigger in case there are no children
204        // to ensure that it runs
205        ctx.postAnimationTrigger.increment();
206        if (mTaskStackView != null) {
207            mTaskStackView.startEnterRecentsAnimation(ctx);
208        }
209        ctx.postAnimationTrigger.decrement();
210    }
211
212    /** Requests all task stacks to start their exit-recents animation */
213    public void startExitToHomeAnimation(ViewAnimation.TaskViewExitContext ctx) {
214        // We have to increment/decrement the post animation trigger in case there are no children
215        // to ensure that it runs
216        ctx.postAnimationTrigger.increment();
217        if (mTaskStackView != null) {
218            mTaskStackView.startExitToHomeAnimation(ctx);
219        }
220        ctx.postAnimationTrigger.decrement();
221
222        // If we are going home, cancel the previous task's window transition
223        EventBus.getDefault().send(new CancelEnterRecentsWindowAnimationEvent(null));
224
225        // Notify of the exit animation
226        EventBus.getDefault().send(new DismissRecentsToHomeAnimationStarted());
227    }
228
229    /** Adds the search bar */
230    public void setSearchBar(RecentsAppWidgetHostView searchBar) {
231        // Remove the previous search bar if one exists
232        if (mSearchBar != null && indexOfChild(mSearchBar) > -1) {
233            removeView(mSearchBar);
234        }
235        // Add the new search bar
236        if (searchBar != null) {
237            mSearchBar = searchBar;
238            addView(mSearchBar);
239        }
240    }
241
242    /** Returns whether there is currently a search bar */
243    public boolean hasValidSearchBar() {
244        return mSearchBar != null && !mSearchBar.isReinflateRequired();
245    }
246
247    /** Sets the visibility of the search bar */
248    public void setSearchBarVisibility(int visibility) {
249        if (mSearchBar != null) {
250            mSearchBar.setVisibility(visibility);
251            // Always bring the search bar to the top
252            mSearchBar.bringToFront();
253        }
254    }
255
256    @Override
257    protected void onAttachedToWindow() {
258        EventBus.getDefault().register(this, RecentsActivity.EVENT_BUS_PRIORITY + 1);
259        EventBus.getDefault().register(mTouchHandler, RecentsActivity.EVENT_BUS_PRIORITY + 1);
260        super.onAttachedToWindow();
261    }
262
263    @Override
264    protected void onDetachedFromWindow() {
265        super.onDetachedFromWindow();
266        EventBus.getDefault().unregister(this);
267        EventBus.getDefault().unregister(mTouchHandler);
268    }
269
270    /**
271     * This is called with the full size of the window since we are handling our own insets.
272     */
273    @Override
274    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
275        RecentsConfiguration config = Recents.getConfiguration();
276        int width = MeasureSpec.getSize(widthMeasureSpec);
277        int height = MeasureSpec.getSize(heightMeasureSpec);
278
279        // Get the search bar bounds and measure the search bar layout
280        Rect searchBarSpaceBounds = new Rect();
281        if (mSearchBar != null) {
282            config.getSearchBarBounds(new Rect(0, 0, width, height), mSystemInsets.top,
283                    searchBarSpaceBounds);
284            mSearchBar.measure(
285                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.width(), MeasureSpec.EXACTLY),
286                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.height(), MeasureSpec.EXACTLY));
287        }
288
289        Rect taskStackBounds = new Rect();
290        config.getTaskStackBounds(new Rect(0, 0, width, height), mSystemInsets.top,
291                mSystemInsets.right, searchBarSpaceBounds, taskStackBounds);
292        if (mTaskStackView != null && mTaskStackView.getVisibility() != GONE) {
293            mTaskStackView.setTaskStackBounds(taskStackBounds, mSystemInsets);
294            mTaskStackView.measure(widthMeasureSpec, heightMeasureSpec);
295        }
296
297        if (mDragView != null) {
298            Rect taskRect = mTaskStackView.mLayoutAlgorithm.mTaskRect;
299            mDragView.measure(
300                    MeasureSpec.makeMeasureSpec(taskRect.width(), MeasureSpec.AT_MOST),
301                    MeasureSpec.makeMeasureSpec(taskRect.height(), MeasureSpec.AT_MOST));
302        }
303
304        setMeasuredDimension(width, height);
305    }
306
307    /**
308     * This is called with the full size of the window since we are handling our own insets.
309     */
310    @Override
311    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
312        RecentsConfiguration config = Recents.getConfiguration();
313
314        // Get the search bar bounds so that we lay it out
315        Rect measuredRect = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight());
316        Rect searchBarSpaceBounds = new Rect();
317        if (mSearchBar != null) {
318            config.getSearchBarBounds(measuredRect,
319                    mSystemInsets.top, searchBarSpaceBounds);
320            mSearchBar.layout(searchBarSpaceBounds.left, searchBarSpaceBounds.top,
321                    searchBarSpaceBounds.right, searchBarSpaceBounds.bottom);
322        }
323
324        if (mTaskStackView != null && mTaskStackView.getVisibility() != GONE) {
325            mTaskStackView.layout(left, top, left + getMeasuredWidth(), top + getMeasuredHeight());
326        }
327
328        if (mDragView != null) {
329            mDragView.layout(left, top, left + mDragView.getMeasuredWidth(),
330                    top + mDragView.getMeasuredHeight());
331        }
332
333        if (mAwaitingFirstLayout) {
334            mAwaitingFirstLayout = false;
335
336            // If launched via dragging from the nav bar, then we should translate the whole view
337            // down offscreen
338            RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
339            if (launchState.launchedViaDragGesture) {
340                setTranslationY(getMeasuredHeight());
341            }
342        }
343    }
344
345    @Override
346    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
347        mSystemInsets.set(insets.getSystemWindowInsets());
348        requestLayout();
349        return insets.consumeSystemWindowInsets();
350    }
351
352    @Override
353    public boolean onInterceptTouchEvent(MotionEvent ev) {
354        return mTouchHandler.onInterceptTouchEvent(ev);
355    }
356
357    @Override
358    public boolean onTouchEvent(MotionEvent ev) {
359        return mTouchHandler.onTouchEvent(ev);
360    }
361
362    @Override
363    protected void dispatchDraw(Canvas canvas) {
364        super.dispatchDraw(canvas);
365        for (int i = mVisibleDockStates.length - 1; i >= 0; i--) {
366            Drawable d = mVisibleDockStates[i].viewState.dockAreaOverlay;
367            if (d.getAlpha() > 0) {
368                d.draw(canvas);
369            }
370        }
371    }
372
373    @Override
374    protected boolean verifyDrawable(Drawable who) {
375        for (int i = mVisibleDockStates.length - 1; i >= 0; i--) {
376            Drawable d = mVisibleDockStates[i].viewState.dockAreaOverlay;
377            if (d == who) {
378                return true;
379            }
380        }
381        return super.verifyDrawable(who);
382    }
383
384    public void disableLayersForOneFrame() {
385        if (mTaskStackView != null) {
386            mTaskStackView.disableLayersForOneFrame();
387        }
388    }
389
390    /**** TaskStackView.TaskStackCallbacks Implementation ****/
391
392    @Override
393    public void onTaskViewClicked(final TaskStackView stackView, final TaskView tv,
394            final TaskStack stack, final Task task, final boolean lockToTask,
395            final Rect bounds, int destinationStack) {
396        mLastTaskLaunchedWasFreeform = SystemServicesProxy.isFreeformStack(task.key.stackId);
397        mTransitionHelper.launchTaskFromRecents(stack, task, stackView, tv, lockToTask, bounds,
398                destinationStack);
399    }
400
401    /**** EventBus Events ****/
402
403    public final void onBusEvent(DragStartEvent event) {
404        // Add the drag view
405        mDragView = event.dragView;
406        addView(mDragView);
407
408        updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
409                TaskStack.DockState.NONE.viewState.dockAreaAlpha);
410    }
411
412    public final void onBusEvent(DragDropTargetChangedEvent event) {
413        if (event.dropTarget == null || !(event.dropTarget instanceof TaskStack.DockState)) {
414            updateVisibleDockRegions(mTouchHandler.getDockStatesForCurrentOrientation(),
415                    TaskStack.DockState.NONE.viewState.dockAreaAlpha);
416        } else {
417            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
418            updateVisibleDockRegions(new TaskStack.DockState[] {dockState}, -1);
419        }
420    }
421
422    public final void onBusEvent(final DragEndEvent event) {
423        final Runnable cleanUpRunnable = new Runnable() {
424            @Override
425            public void run() {
426                // Remove the drag view
427                removeView(mDragView);
428                mDragView = null;
429            }
430        };
431
432        // Animate the overlay alpha back to 0
433        updateVisibleDockRegions(null, -1);
434
435        if (event.dropTarget == null) {
436            // No drop targets for hit, so just animate the task back to its place
437            event.postAnimationTrigger.increment();
438            event.postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
439                @Override
440                public void run() {
441                    cleanUpRunnable.run();
442                }
443            });
444            // Animate the task back to where it was before then clean up afterwards
445            TaskViewTransform taskTransform = new TaskViewTransform();
446            TaskStackLayoutAlgorithm layoutAlgorithm = mTaskStackView.getStackAlgorithm();
447            layoutAlgorithm.getStackTransform(event.task,
448                    mTaskStackView.getScroller().getStackScroll(), taskTransform, null);
449            event.dragView.animate()
450                    .scaleX(taskTransform.scale)
451                    .scaleY(taskTransform.scale)
452                    .translationX((layoutAlgorithm.mTaskRect.left - event.dragView.getLeft())
453                            + taskTransform.translationX)
454                    .translationY((layoutAlgorithm.mTaskRect.top - event.dragView.getTop())
455                            + taskTransform.translationY)
456                    .setDuration(175)
457                    .setInterpolator(mFastOutSlowInInterpolator)
458                    .withEndAction(event.postAnimationTrigger.decrementAsRunnable())
459                    .start();
460
461        } else if (event.dropTarget instanceof TaskStack.DockState) {
462            final TaskStack.DockState dockState = (TaskStack.DockState) event.dropTarget;
463
464            // For now, just remove the drag view and the original task
465            // TODO: Animate the task to the drop target rect before launching it above
466            cleanUpRunnable.run();
467
468            // Dock the task and launch it
469            SystemServicesProxy ssp = Recents.getSystemServices();
470            ssp.startTaskInDockedMode(event.task.key.id, dockState.createMode);
471            launchTask(event.task, null, INVALID_STACK_ID);
472
473        } else {
474            // We dropped on another drop target, so just add the cleanup to the post animation
475            // trigger
476            event.postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
477                @Override
478                public void run() {
479                    cleanUpRunnable.run();
480                }
481            });
482        }
483    }
484
485    public final void onBusEvent(DraggingInRecentsEvent event) {
486        setTranslationY(event.distanceFromTop - mTaskStackView.getTaskViews().get(0).getY());
487    }
488
489    public final void onBusEvent(DraggingInRecentsEndedEvent event) {
490        animate().translationY(0f);
491    }
492
493    /**
494     * Updates the dock region to match the specified dock state.
495     */
496    private void updateVisibleDockRegions(TaskStack.DockState[] newDockStates, int overrideAlpha) {
497        ArraySet<TaskStack.DockState> newDockStatesSet = new ArraySet<>();
498        if (newDockStates != null) {
499            for (TaskStack.DockState dockState : newDockStates) {
500                newDockStatesSet.add(dockState);
501            }
502        }
503        for (TaskStack.DockState dockState : mVisibleDockStates) {
504            TaskStack.DockState.ViewState viewState = dockState.viewState;
505            if (newDockStates == null || !newDockStatesSet.contains(dockState)) {
506                // This is no longer visible, so hide it
507                viewState.startAlphaAnimation(0, 150);
508            } else {
509                // This state is now visible, update the bounds and show it
510                int alpha = (overrideAlpha != -1 ? overrideAlpha : viewState.dockAreaAlpha);
511                viewState.dockAreaOverlay.setBounds(
512                        dockState.getDockedBounds(getMeasuredWidth(), getMeasuredHeight()));
513                viewState.dockAreaOverlay.setCallback(this);
514                viewState.startAlphaAnimation(alpha, 150);
515            }
516        }
517    }
518
519    public final void onBusEvent(RecentsVisibilityChangedEvent event) {
520        if (!event.visible) {
521            // Reset the view state
522            mAwaitingFirstLayout = true;
523            mLastTaskLaunchedWasFreeform = false;
524        }
525    }
526}
527