RecentsView.java revision d54b578e47fb410c776bb3a4272c2c523153f657
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;
34import com.android.systemui.recents.Constants;
35import com.android.systemui.recents.RecentsConfiguration;
36import com.android.systemui.recents.misc.SystemServicesProxy;
37import com.android.systemui.recents.model.RecentsPackageMonitor;
38import com.android.systemui.recents.model.RecentsTaskLoader;
39import com.android.systemui.recents.model.Task;
40import com.android.systemui.recents.model.TaskStack;
41
42import java.util.ArrayList;
43
44/**
45 * This view is the the top level layout that contains TaskStacks (which are laid out according
46 * to their SpaceNode bounds.
47 */
48public class RecentsView extends FrameLayout implements TaskStackView.TaskStackViewCallbacks,
49        RecentsPackageMonitor.PackageCallbacks {
50
51    /** The RecentsView callbacks */
52    public interface RecentsViewCallbacks {
53        public void onTaskViewClicked();
54        public void onTaskLaunchFailed();
55        public void onAllTaskViewsDismissed();
56        public void onExitToHomeAnimationTriggered();
57    }
58
59    RecentsConfiguration mConfig;
60    LayoutInflater mInflater;
61    DebugOverlayView mDebugOverlay;
62
63    ArrayList<TaskStack> mStacks;
64    View mSearchBar;
65    RecentsViewCallbacks mCb;
66    boolean mAlreadyLaunchingTask;
67
68    public RecentsView(Context context) {
69        super(context);
70    }
71
72    public RecentsView(Context context, AttributeSet attrs) {
73        this(context, attrs, 0);
74    }
75
76    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr) {
77        this(context, attrs, defStyleAttr, 0);
78    }
79
80    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
81        super(context, attrs, defStyleAttr, defStyleRes);
82        mConfig = RecentsConfiguration.getInstance();
83        mInflater = LayoutInflater.from(context);
84    }
85
86    /** Sets the callbacks */
87    public void setCallbacks(RecentsViewCallbacks cb) {
88        mCb = cb;
89    }
90
91    /** Sets the debug overlay */
92    public void setDebugOverlay(DebugOverlayView overlay) {
93        mDebugOverlay = overlay;
94    }
95
96    /** Set/get the bsp root node */
97    public void setTaskStacks(ArrayList<TaskStack> stacks) {
98        // Remove all TaskStackViews (but leave the search bar)
99        int childCount = getChildCount();
100        for (int i = childCount - 1; i >= 0; i--) {
101            View v = getChildAt(i);
102            if (v != mSearchBar) {
103                removeViewAt(i);
104            }
105        }
106
107        // Create and add all the stacks for this partition of space.
108        mStacks = stacks;
109        int numStacks = mStacks.size();
110        for (int i = 0; i < numStacks; i++) {
111            TaskStack stack = mStacks.get(i);
112            TaskStackView stackView = new TaskStackView(getContext(), stack);
113            stackView.setCallbacks(this);
114            // Enable debug mode drawing
115            if (mConfig.debugModeEnabled) {
116                stackView.setDebugOverlay(mDebugOverlay);
117            }
118            addView(stackView);
119        }
120
121        // Reset the launched state
122        mAlreadyLaunchingTask = false;
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        int childCount = getChildCount();
320        for (int i = 0; i < childCount; i++) {
321            View child = getChildAt(i);
322            if (child != mSearchBar) {
323                TaskStackView stackView = (TaskStackView) child;
324                stackView.onUserInteraction();
325            }
326        }
327    }
328
329    /** Focuses the next task in the first stack view */
330    public void focusNextTask(boolean forward) {
331        // Get the first stack view
332        int childCount = getChildCount();
333        for (int i = 0; i < childCount; i++) {
334            View child = getChildAt(i);
335            if (child != mSearchBar) {
336                TaskStackView stackView = (TaskStackView) child;
337                stackView.focusNextTask(forward, true);
338                break;
339            }
340        }
341    }
342
343    /** Dismisses the focused task. */
344    public void dismissFocusedTask() {
345        // Get the first stack view
346        int childCount = getChildCount();
347        for (int i = 0; i < childCount; i++) {
348            View child = getChildAt(i);
349            if (child != mSearchBar) {
350                TaskStackView stackView = (TaskStackView) child;
351                stackView.dismissFocusedTask();
352                break;
353            }
354        }
355    }
356
357    /** Unfilters any filtered stacks */
358    public boolean unfilterFilteredStacks() {
359        if (mStacks != null) {
360            // Check if there are any filtered stacks and unfilter them before we back out of Recents
361            boolean stacksUnfiltered = false;
362            int numStacks = mStacks.size();
363            for (int i = 0; i < numStacks; i++) {
364                TaskStack stack = mStacks.get(i);
365                if (stack.hasFilteredTasks()) {
366                    stack.unfilterTasks();
367                    stacksUnfiltered = true;
368                }
369            }
370            return stacksUnfiltered;
371        }
372        return false;
373    }
374
375    /**** TaskStackView.TaskStackCallbacks Implementation ****/
376
377    @Override
378    public void onTaskViewClicked(final TaskStackView stackView, final TaskView tv,
379                                  final TaskStack stack, final Task task, final boolean lockToTask) {
380        // Notify any callbacks of the launching of a new task
381        if (mCb != null) {
382            mCb.onTaskViewClicked();
383        }
384        // Skip if we are already launching tasks
385        if (mAlreadyLaunchingTask) {
386            return;
387        }
388        mAlreadyLaunchingTask = true;
389
390        // Upfront the processing of the thumbnail
391        TaskViewTransform transform = new TaskViewTransform();
392        View sourceView;
393        int offsetX = 0;
394        int offsetY = 0;
395        float stackScroll = stackView.getScroller().getStackScroll();
396        if (tv == null) {
397            // If there is no actual task view, then use the stack view as the source view
398            // and then offset to the expected transform rect, but bound this to just
399            // outside the display rect (to ensure we don't animate from too far away)
400            sourceView = stackView;
401            transform = stackView.getStackAlgorithm().getStackTransform(task, stackScroll, transform, null);
402            offsetX = transform.rect.left;
403            offsetY = mConfig.displayRect.height();
404        } else {
405            sourceView = tv.mThumbnailView;
406            transform = stackView.getStackAlgorithm().getStackTransform(task, stackScroll, transform, null);
407        }
408
409        // Compute the thumbnail to scale up from
410        final SystemServicesProxy ssp =
411                RecentsTaskLoader.getInstance().getSystemServicesProxy();
412        ActivityOptions opts = null;
413        if (task.thumbnail != null && task.thumbnail.getWidth() > 0 &&
414                task.thumbnail.getHeight() > 0) {
415            Bitmap b;
416            if (tv != null) {
417                // Disable any focused state before we draw the header
418                if (tv.isFocusedTask()) {
419                    tv.unsetFocusedTask();
420                }
421
422                float scale = tv.getScaleX();
423                int fromHeaderWidth = (int) (tv.mHeaderView.getMeasuredWidth() * scale);
424                int fromHeaderHeight = (int) (tv.mHeaderView.getMeasuredHeight() * scale);
425                b = Bitmap.createBitmap(fromHeaderWidth, fromHeaderHeight,
426                        Bitmap.Config.ARGB_8888);
427                if (Constants.DebugFlags.App.EnableTransitionThumbnailDebugMode) {
428                    b.eraseColor(0xFFff0000);
429                } else {
430                    Canvas c = new Canvas(b);
431                    c.scale(tv.getScaleX(), tv.getScaleY());
432                    tv.mHeaderView.draw(c);
433                    c.setBitmap(null);
434                }
435            } else {
436                // Notify the system to skip the thumbnail layer by using an ALPHA_8 bitmap
437                b = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8);
438            }
439            ActivityOptions.OnAnimationStartedListener animStartedListener = null;
440            if (lockToTask) {
441                animStartedListener = new ActivityOptions.OnAnimationStartedListener() {
442                    boolean mTriggered = false;
443                    @Override
444                    public void onAnimationStarted() {
445                        if (!mTriggered) {
446                            postDelayed(new Runnable() {
447                                @Override
448                                public void run() {
449                                    ssp.lockCurrentTask();
450                                }
451                            }, 350);
452                            mTriggered = true;
453                        }
454                    }
455                };
456            }
457            opts = ActivityOptions.makeThumbnailAspectScaleUpAnimation(sourceView,
458                    b, offsetX, offsetY, transform.rect.width(), transform.rect.height(),
459                    animStartedListener);
460        }
461
462        final ActivityOptions launchOpts = opts;
463        final Runnable launchRunnable = new Runnable() {
464            @Override
465            public void run() {
466                if (task.isActive) {
467                    // Bring an active task to the foreground
468                    ssp.moveTaskToFront(task.key.id, launchOpts);
469                } else {
470                    if (ssp.startActivityFromRecents(getContext(), task.key.id,
471                            task.activityLabel, launchOpts)) {
472                        if (launchOpts == null && lockToTask) {
473                            ssp.lockCurrentTask();
474                        }
475                    } else {
476                        // Dismiss the task and return the user to home if we fail to
477                        // launch the task
478                        onTaskViewDismissed(task);
479                        if (mCb != null) {
480                            mCb.onTaskLaunchFailed();
481                        }
482                    }
483                }
484            }
485        };
486
487        // Launch the app right away if there is no task view, otherwise, animate the icon out first
488        if (tv == null) {
489            post(launchRunnable);
490        } else {
491            if (!task.group.isFrontMostTask(task)) {
492                // For affiliated tasks that are behind other tasks, we must animate the front cards
493                // out of view before starting the task transition
494                stackView.startLaunchTaskAnimation(tv, launchRunnable, lockToTask);
495            } else {
496                // Otherwise, we can start the task transition immediately
497                stackView.startLaunchTaskAnimation(tv, null, lockToTask);
498                postDelayed(launchRunnable, 17);
499            }
500        }
501    }
502
503    @Override
504    public void onTaskViewAppInfoClicked(Task t) {
505        // Create a new task stack with the application info details activity
506        Intent baseIntent = t.key.baseIntent;
507        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
508                Uri.fromParts("package", baseIntent.getComponent().getPackageName(), null));
509        intent.setComponent(intent.resolveActivity(getContext().getPackageManager()));
510        TaskStackBuilder.create(getContext())
511                .addNextIntentWithParentStack(intent).startActivities(null,
512                new UserHandle(t.key.userId));
513    }
514
515    @Override
516    public void onTaskViewDismissed(Task t) {
517        // Remove any stored data from the loader.  We currently don't bother notifying the views
518        // that the data has been unloaded because at the point we call onTaskViewDismissed(), the views
519        // either don't need to be updated, or have already been removed.
520        RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
521        loader.deleteTaskData(t, false);
522
523        // Remove the old task from activity manager
524        RecentsTaskLoader.getInstance().getSystemServicesProxy().removeTask(t.key.id);
525    }
526
527    @Override
528    public void onAllTaskViewsDismissed() {
529        mCb.onAllTaskViewsDismissed();
530    }
531
532    @Override
533    public void onTaskStackFilterTriggered() {
534        // Hide the search bar
535        if (mSearchBar != null) {
536            mSearchBar.animate()
537                    .alpha(0f)
538                    .setStartDelay(0)
539                    .setInterpolator(mConfig.fastOutSlowInInterpolator)
540                    .setDuration(mConfig.filteringCurrentViewsAnimDuration)
541                    .withLayer()
542                    .start();
543        }
544    }
545
546    @Override
547    public void onTaskStackUnfilterTriggered() {
548        // Show the search bar
549        if (mSearchBar != null) {
550            mSearchBar.animate()
551                    .alpha(1f)
552                    .setStartDelay(0)
553                    .setInterpolator(mConfig.fastOutSlowInInterpolator)
554                    .setDuration(mConfig.filteringNewViewsAnimDuration)
555                    .withLayer()
556                    .start();
557        }
558    }
559
560    /**** RecentsPackageMonitor.PackageCallbacks Implementation ****/
561
562    @Override
563    public void onPackagesChanged(RecentsPackageMonitor monitor, String packageName, int userId) {
564        // Propagate this event down to each task stack view
565        int childCount = getChildCount();
566        for (int i = 0; i < childCount; i++) {
567            View child = getChildAt(i);
568            if (child != mSearchBar) {
569                TaskStackView stackView = (TaskStackView) child;
570                stackView.onPackagesChanged(monitor, packageName, userId);
571            }
572        }
573    }
574}
575