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