RecentsView.java revision e41ab847a5c12cb7a6a5b2d0f40e101bc9ea6b59
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.app.ActivityOptions;
20import android.app.TaskStackBuilder;
21import android.content.ActivityNotFoundException;
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.graphics.Bitmap;
26import android.graphics.Canvas;
27import android.graphics.Rect;
28import android.net.Uri;
29import android.os.UserHandle;
30import android.provider.Settings;
31import android.util.AttributeSet;
32import android.view.LayoutInflater;
33import android.view.View;
34import android.view.WindowInsets;
35import android.widget.FrameLayout;
36import com.android.systemui.recents.Constants;
37import com.android.systemui.recents.RecentsConfiguration;
38import com.android.systemui.recents.misc.Console;
39import com.android.systemui.recents.misc.SystemServicesProxy;
40import com.android.systemui.recents.misc.Utilities;
41import com.android.systemui.recents.model.RecentsPackageMonitor;
42import com.android.systemui.recents.model.RecentsTaskLoader;
43import com.android.systemui.recents.model.Task;
44import com.android.systemui.recents.model.TaskStack;
45
46import java.util.ArrayList;
47import java.util.HashSet;
48
49/**
50 * This view is the the top level layout that contains TaskStacks (which are laid out according
51 * to their SpaceNode bounds.
52 */
53public class RecentsView extends FrameLayout implements TaskStackView.TaskStackViewCallbacks,
54        RecentsPackageMonitor.PackageCallbacks {
55
56    /** The RecentsView callbacks */
57    public interface RecentsViewCallbacks {
58        public void onTaskViewClicked();
59        public void onAllTaskViewsDismissed();
60        public void onExitToHomeAnimationTriggered();
61    }
62
63    RecentsConfiguration mConfig;
64    LayoutInflater mInflater;
65    DebugOverlayView mDebugOverlay;
66
67    ArrayList<TaskStack> mStacks;
68    View mSearchBar;
69    RecentsViewCallbacks mCb;
70
71    public RecentsView(Context context) {
72        super(context);
73    }
74
75    public RecentsView(Context context, AttributeSet attrs) {
76        this(context, attrs, 0);
77    }
78
79    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr) {
80        this(context, attrs, defStyleAttr, 0);
81    }
82
83    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
84        super(context, attrs, defStyleAttr, defStyleRes);
85        mConfig = RecentsConfiguration.getInstance();
86        mInflater = LayoutInflater.from(context);
87    }
88
89    /** Sets the callbacks */
90    public void setCallbacks(RecentsViewCallbacks cb) {
91        mCb = cb;
92    }
93
94    /** Sets the debug overlay */
95    public void setDebugOverlay(DebugOverlayView overlay) {
96        mDebugOverlay = overlay;
97    }
98
99    /** Set/get the bsp root node */
100    public void setTaskStacks(ArrayList<TaskStack> stacks) {
101        // Remove all TaskStackViews (but leave the search bar)
102        int childCount = getChildCount();
103        for (int i = childCount - 1; i >= 0; i--) {
104            View v = getChildAt(i);
105            if (v != mSearchBar) {
106                removeViewAt(i);
107            }
108        }
109
110        // Create and add all the stacks for this partition of space.
111        mStacks = stacks;
112        int numStacks = mStacks.size();
113        for (int i = 0; i < numStacks; i++) {
114            TaskStack stack = mStacks.get(i);
115            TaskStackView stackView = new TaskStackView(getContext(), stack);
116            stackView.setCallbacks(this);
117            // Enable debug mode drawing
118            if (mConfig.debugModeEnabled) {
119                stackView.setDebugOverlay(mDebugOverlay);
120            }
121            addView(stackView);
122        }
123    }
124
125    /** Removes all the task stack views from this recents view. */
126    public void removeAllTaskStacks() {
127        int childCount = getChildCount();
128        for (int i = childCount - 1; i >= 0; i--) {
129            View child = getChildAt(i);
130            if (child != mSearchBar) {
131                removeViewAt(i);
132            }
133        }
134    }
135
136    /** Launches the focused task from the first stack if possible */
137    public boolean launchFocusedTask() {
138        // Get the first stack view
139        int childCount = getChildCount();
140        for (int i = 0; i < childCount; i++) {
141            View child = getChildAt(i);
142            if (child != mSearchBar) {
143                TaskStackView stackView = (TaskStackView) child;
144                TaskStack stack = stackView.mStack;
145                // Iterate the stack views and try and find the focused task
146                int taskCount = stackView.getChildCount();
147                for (int j = 0; j < taskCount; j++) {
148                    TaskView tv = (TaskView) stackView.getChildAt(j);
149                    Task task = tv.getTask();
150                    if (tv.isFocusedTask()) {
151                        onTaskViewClicked(stackView, tv, stack, task, false);
152                        return true;
153                    }
154                }
155            }
156        }
157        return false;
158    }
159
160    /** Launches the task that Recents was launched from, if possible */
161    public boolean launchPreviousTask() {
162        // Get the first stack view
163        int childCount = getChildCount();
164        for (int i = 0; i < childCount; i++) {
165            View child = getChildAt(i);
166            if (child != mSearchBar) {
167                TaskStackView stackView = (TaskStackView) child;
168                TaskStack stack = stackView.mStack;
169                ArrayList<Task> tasks = stack.getTasks();
170
171                // Find the launch task in the stack
172                if (!tasks.isEmpty()) {
173                    int taskCount = tasks.size();
174                    for (int j = 0; j < taskCount; j++) {
175                        if (tasks.get(j).isLaunchTarget) {
176                            Task task = tasks.get(j);
177                            TaskView tv = stackView.getChildViewForTask(task);
178                            onTaskViewClicked(stackView, tv, stack, task, false);
179                            return true;
180                        }
181                    }
182                }
183            }
184        }
185        return false;
186    }
187
188    /** Requests all task stacks to start their enter-recents animation */
189    public void startEnterRecentsAnimation(ViewAnimation.TaskViewEnterContext ctx) {
190        int childCount = getChildCount();
191        for (int i = 0; i < childCount; i++) {
192            View child = getChildAt(i);
193            if (child != mSearchBar) {
194                TaskStackView stackView = (TaskStackView) child;
195                stackView.startEnterRecentsAnimation(ctx);
196            }
197        }
198    }
199
200    /** Requests all task stacks to start their exit-recents animation */
201    public void startExitToHomeAnimation(ViewAnimation.TaskViewExitContext ctx) {
202        int childCount = getChildCount();
203        for (int i = 0; i < childCount; i++) {
204            View child = getChildAt(i);
205            if (child != mSearchBar) {
206                TaskStackView stackView = (TaskStackView) child;
207                stackView.startExitToHomeAnimation(ctx);
208            }
209        }
210
211        // Notify of the exit animation
212        mCb.onExitToHomeAnimationTriggered();
213    }
214
215    /** Adds the search bar */
216    public void setSearchBar(View searchBar) {
217        // Create the search bar (and hide it if we have no recent tasks)
218        if (Constants.DebugFlags.App.EnableSearchLayout) {
219            // Remove the previous search bar if one exists
220            if (mSearchBar != null && indexOfChild(mSearchBar) > -1) {
221                removeView(mSearchBar);
222            }
223            // Add the new search bar
224            if (searchBar != null) {
225                mSearchBar = searchBar;
226                addView(mSearchBar);
227            }
228        }
229    }
230
231    /** Returns whether there is currently a search bar */
232    public boolean hasSearchBar() {
233        return mSearchBar != null;
234    }
235
236    /** Sets the visibility of the search bar */
237    public void setSearchBarVisibility(int visibility) {
238        if (mSearchBar != null) {
239            mSearchBar.setVisibility(visibility);
240            // Always bring the search bar to the top
241            mSearchBar.bringToFront();
242        }
243    }
244
245    /**
246     * This is called with the full size of the window since we are handling our own insets.
247     */
248    @Override
249    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
250        int width = MeasureSpec.getSize(widthMeasureSpec);
251        int height = MeasureSpec.getSize(heightMeasureSpec);
252
253        // Get the search bar bounds and measure the search bar layout
254        if (mSearchBar != null) {
255            Rect searchBarSpaceBounds = new Rect();
256            mConfig.getSearchBarBounds(width, height, mConfig.systemInsets.top, searchBarSpaceBounds);
257            mSearchBar.measure(
258                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.width(), MeasureSpec.EXACTLY),
259                    MeasureSpec.makeMeasureSpec(searchBarSpaceBounds.height(), MeasureSpec.EXACTLY));
260        }
261
262        Rect taskStackBounds = new Rect();
263        mConfig.getTaskStackBounds(width, height, mConfig.systemInsets.top,
264                mConfig.systemInsets.right, taskStackBounds);
265
266        // Measure each TaskStackView with the full width and height of the window since the
267        // transition view is a child of that stack view
268        int childCount = getChildCount();
269        for (int i = 0; i < childCount; i++) {
270            View child = getChildAt(i);
271            if (child != mSearchBar && child.getVisibility() != GONE) {
272                TaskStackView tsv = (TaskStackView) child;
273                // Set the insets to be the top/left inset + search bounds
274                tsv.setStackInsetRect(taskStackBounds);
275                tsv.measure(widthMeasureSpec, heightMeasureSpec);
276            }
277        }
278
279        setMeasuredDimension(width, height);
280    }
281
282    /**
283     * This is called with the full size of the window since we are handling our own insets.
284     */
285    @Override
286    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
287        // Get the search bar bounds so that we lay it out
288        if (mSearchBar != null) {
289            Rect searchBarSpaceBounds = new Rect();
290            mConfig.getSearchBarBounds(getMeasuredWidth(), getMeasuredHeight(),
291                    mConfig.systemInsets.top, searchBarSpaceBounds);
292            mSearchBar.layout(searchBarSpaceBounds.left, searchBarSpaceBounds.top,
293                    searchBarSpaceBounds.right, searchBarSpaceBounds.bottom);
294        }
295
296        // Layout each TaskStackView with the full width and height of the window since the
297        // transition view is a child of that stack view
298        int childCount = getChildCount();
299        for (int i = 0; i < childCount; i++) {
300            View child = getChildAt(i);
301            if (child != mSearchBar && child.getVisibility() != GONE) {
302                child.layout(left, top, left + child.getMeasuredWidth(),
303                        top + child.getMeasuredHeight());
304            }
305        }
306    }
307
308    @Override
309    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
310        // Update the configuration with the latest system insets and trigger a relayout
311        mConfig.updateSystemInsets(insets.getSystemWindowInsets());
312        requestLayout();
313        return insets.consumeSystemWindowInsets();
314    }
315
316    /** Notifies each task view of the user interaction. */
317    public void onUserInteraction() {
318        // Get the first stack view
319        TaskStackView stackView = null;
320        int childCount = getChildCount();
321        for (int i = 0; i < childCount; i++) {
322            View child = getChildAt(i);
323            if (child != mSearchBar) {
324                stackView = (TaskStackView) child;
325                stackView.onUserInteraction();
326            }
327        }
328    }
329
330    /** Focuses the next task in the first stack view */
331    public void focusNextTask(boolean forward) {
332        // Get the first stack view
333        TaskStackView stackView = null;
334        int childCount = getChildCount();
335        for (int i = 0; i < childCount; i++) {
336            View child = getChildAt(i);
337            if (child != mSearchBar) {
338                stackView = (TaskStackView) child;
339                break;
340            }
341        }
342
343        if (stackView != null) {
344            stackView.focusNextTask(forward);
345        }
346    }
347
348    /** Unfilters any filtered stacks */
349    public boolean unfilterFilteredStacks() {
350        if (mStacks != null) {
351            // Check if there are any filtered stacks and unfilter them before we back out of Recents
352            boolean stacksUnfiltered = false;
353            int numStacks = mStacks.size();
354            for (int i = 0; i < numStacks; i++) {
355                TaskStack stack = mStacks.get(i);
356                if (stack.hasFilteredTasks()) {
357                    stack.unfilterTasks();
358                    stacksUnfiltered = true;
359                }
360            }
361            return stacksUnfiltered;
362        }
363        return false;
364    }
365
366    /**** TaskStackView.TaskStackCallbacks Implementation ****/
367
368    @Override
369    public void onTaskViewClicked(final TaskStackView stackView, final TaskView tv,
370                                  final TaskStack stack, final Task task, final boolean lockToTask) {
371        // Notify any callbacks of the launching of a new task
372        if (mCb != null) {
373            mCb.onTaskViewClicked();
374        }
375
376        // Upfront the processing of the thumbnail
377        TaskViewTransform transform = new TaskViewTransform();
378        View sourceView = tv;
379        int offsetX = 0;
380        int offsetY = 0;
381        float stackScroll = stackView.getScroller().getStackScroll();
382        if (tv == null) {
383            // If there is no actual task view, then use the stack view as the source view
384            // and then offset to the expected transform rect, but bound this to just
385            // outside the display rect (to ensure we don't animate from too far away)
386            sourceView = stackView;
387            transform = stackView.getStackAlgorithm().getStackTransform(task, stackScroll, transform, null);
388            offsetX = transform.rect.left;
389            offsetY = mConfig.displayRect.height();
390        } else {
391            transform = stackView.getStackAlgorithm().getStackTransform(task, stackScroll, transform, null);
392        }
393
394        // Compute the thumbnail to scale up from
395        final SystemServicesProxy ssp =
396                RecentsTaskLoader.getInstance().getSystemServicesProxy();
397        ActivityOptions opts = null;
398        int thumbnailWidth = transform.rect.width();
399        int thumbnailHeight = transform.rect.height();
400        if (task.thumbnail != null && thumbnailWidth > 0 && thumbnailHeight > 0 &&
401                task.thumbnail.getWidth() > 0 && task.thumbnail.getHeight() > 0) {
402            // Resize the thumbnail to the size of the view that we are animating from
403            Bitmap b = Bitmap.createBitmap(thumbnailWidth, thumbnailHeight,
404                    Bitmap.Config.ARGB_8888);
405            Canvas c = new Canvas(b);
406            c.drawBitmap(task.thumbnail,
407                    new Rect(0, 0, task.thumbnail.getWidth(), task.thumbnail.getHeight()),
408                    new Rect(0, 0, thumbnailWidth, thumbnailHeight), null);
409            c.setBitmap(null);
410            ActivityOptions.OnAnimationStartedListener animStartedListener = null;
411            if (lockToTask) {
412                animStartedListener = new ActivityOptions.OnAnimationStartedListener() {
413                    boolean mTriggered = false;
414                    @Override
415                    public void onAnimationStarted() {
416                        if (!mTriggered) {
417                            postDelayed(new Runnable() {
418                                @Override
419                                public void run() {
420                                    ssp.lockCurrentTask();
421                                }
422                            }, 350);
423                            mTriggered = true;
424                        }
425                    }
426                };
427            }
428            opts = ActivityOptions.makeThumbnailScaleUpAnimation(sourceView,
429                    b, offsetX, offsetY, animStartedListener);
430        }
431
432        final ActivityOptions launchOpts = opts;
433        final Runnable launchRunnable = new Runnable() {
434            @Override
435            public void run() {
436                if (task.isActive) {
437                    // Bring an active task to the foreground
438                    ssp.moveTaskToFront(task.key.id, launchOpts);
439                } else {
440                    // Launch the activity anew with the desired animation
441                    Intent i = new Intent(task.key.baseIntent);
442                    i.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
443                            | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
444                    if (!Utilities.isDocument(i)) {
445                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
446                    }
447                    try {
448                        ssp.startActivityFromRecents(task.key.id, launchOpts);
449                        if (launchOpts == null && lockToTask) {
450                            ssp.lockCurrentTask();
451                        }
452                    } catch (ActivityNotFoundException anfe) {
453                        Console.logError(getContext(), "Could not start Activity");
454                    }
455
456                    // And clean up the old task
457                    onTaskViewDismissed(task);
458                }
459            }
460        };
461
462        // Launch the app right away if there is no task view, otherwise, animate the icon out first
463        if (tv == null) {
464            post(launchRunnable);
465        } else {
466            stackView.startLaunchTaskAnimation(tv, launchRunnable);
467        }
468    }
469
470    @Override
471    public void onTaskViewAppInfoClicked(Task t) {
472        // Create a new task stack with the application info details activity
473        Intent baseIntent = t.key.baseIntent;
474        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
475                Uri.fromParts("package", baseIntent.getComponent().getPackageName(), null));
476        intent.setComponent(intent.resolveActivity(getContext().getPackageManager()));
477        TaskStackBuilder.create(getContext())
478                .addNextIntentWithParentStack(intent).startActivities(null,
479                new UserHandle(t.userId));
480    }
481
482    @Override
483    public void onTaskViewDismissed(Task t) {
484        // Remove any stored data from the loader.  We currently don't bother notifying the views
485        // that the data has been unloaded because at the point we call onTaskViewDismissed(), the views
486        // either don't need to be updated, or have already been removed.
487        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
488        loader.deleteTaskData(t, false);
489
490        // Remove the old task from activity manager
491        RecentsTaskLoader.getInstance().getSystemServicesProxy().removeTask(t.key.id,
492                Utilities.isDocument(t.key.baseIntent));
493    }
494
495    @Override
496    public void onAllTaskViewsDismissed() {
497        mCb.onAllTaskViewsDismissed();
498    }
499
500    @Override
501    public void onTaskStackFilterTriggered() {
502        // Hide the search bar
503        if (mSearchBar != null) {
504            mSearchBar.animate()
505                    .alpha(0f)
506                    .setStartDelay(0)
507                    .setInterpolator(mConfig.fastOutSlowInInterpolator)
508                    .setDuration(mConfig.filteringCurrentViewsAnimDuration)
509                    .withLayer()
510                    .start();
511        }
512    }
513
514    @Override
515    public void onTaskStackUnfilterTriggered() {
516        // Show the search bar
517        if (mSearchBar != null) {
518            mSearchBar.animate()
519                    .alpha(1f)
520                    .setStartDelay(0)
521                    .setInterpolator(mConfig.fastOutSlowInInterpolator)
522                    .setDuration(mConfig.filteringNewViewsAnimDuration)
523                    .withLayer()
524                    .start();
525        }
526    }
527
528    /**** RecentsPackageMonitor.PackageCallbacks Implementation ****/
529
530    @Override
531    public void onComponentRemoved(HashSet<ComponentName> cns) {
532        // Propagate this event down to each task stack view
533        int childCount = getChildCount();
534        for (int i = 0; i < childCount; i++) {
535            View child = getChildAt(i);
536            if (child != mSearchBar) {
537                TaskStackView stackView = (TaskStackView) child;
538                stackView.onComponentRemoved(cns);
539            }
540        }
541    }
542}
543