RecentsPanelView.java revision 211cb86ab23f06d833919d4c3fef725d7fbb5858
1/*
2 * Copyright (C) 2011 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.recent;
18
19import android.animation.Animator;
20import android.animation.LayoutTransition;
21import android.animation.TimeInterpolator;
22import android.app.ActivityManager;
23import android.app.ActivityManagerNative;
24import android.app.ActivityOptions;
25import android.app.TaskStackBuilder;
26import android.content.Context;
27import android.content.Intent;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.content.res.TypedArray;
31import android.graphics.Bitmap;
32import android.graphics.Matrix;
33import android.graphics.Shader.TileMode;
34import android.graphics.drawable.BitmapDrawable;
35import android.graphics.drawable.Drawable;
36import android.net.Uri;
37import android.os.Bundle;
38import android.os.RemoteException;
39import android.os.UserHandle;
40import android.provider.Settings;
41import android.util.AttributeSet;
42import android.util.Log;
43import android.view.LayoutInflater;
44import android.view.MenuItem;
45import android.view.MotionEvent;
46import android.view.View;
47import android.view.ViewGroup;
48import android.view.ViewPropertyAnimator;
49import android.view.ViewRootImpl;
50import android.view.accessibility.AccessibilityEvent;
51import android.view.animation.AnimationUtils;
52import android.view.animation.DecelerateInterpolator;
53import android.widget.AdapterView;
54import android.widget.AdapterView.OnItemClickListener;
55import android.widget.BaseAdapter;
56import android.widget.FrameLayout;
57import android.widget.ImageView;
58import android.widget.ImageView.ScaleType;
59import android.widget.PopupMenu;
60import android.widget.TextView;
61
62import com.android.systemui.R;
63import com.android.systemui.statusbar.BaseStatusBar;
64import com.android.systemui.statusbar.StatusBarPanel;
65import com.android.systemui.statusbar.phone.PhoneStatusBar;
66
67import java.util.ArrayList;
68
69public class RecentsPanelView extends FrameLayout implements OnItemClickListener, RecentsCallback,
70        StatusBarPanel, Animator.AnimatorListener {
71    static final String TAG = "RecentsPanelView";
72    static final boolean DEBUG = PhoneStatusBar.DEBUG || false;
73    private PopupMenu mPopup;
74    private View mRecentsScrim;
75    private View mRecentsNoApps;
76    private ViewGroup mRecentsContainer;
77
78    private boolean mShowing;
79    private boolean mWaitingToShow;
80    private ViewHolder mItemToAnimateInWhenWindowAnimationIsFinished;
81    private boolean mAnimateIconOfFirstTask;
82    private boolean mWaitingForWindowAnimation;
83    private long mWindowAnimationStartTime;
84    private boolean mCallUiHiddenBeforeNextReload;
85
86    private RecentTasksLoader mRecentTasksLoader;
87    private ArrayList<TaskDescription> mRecentTaskDescriptions;
88    private TaskDescriptionAdapter mListAdapter;
89    private int mThumbnailWidth;
90    private boolean mFitThumbnailToXY;
91    private int mRecentItemLayoutId;
92    private boolean mHighEndGfx;
93
94    public static interface RecentsScrollView {
95        public int numItemsInOneScreenful();
96        public void setAdapter(TaskDescriptionAdapter adapter);
97        public void setCallback(RecentsCallback callback);
98        public void setMinSwipeAlpha(float minAlpha);
99        public View findViewForTask(int persistentTaskId);
100    }
101
102    private final class OnLongClickDelegate implements View.OnLongClickListener {
103        View mOtherView;
104        OnLongClickDelegate(View other) {
105            mOtherView = other;
106        }
107        public boolean onLongClick(View v) {
108            return mOtherView.performLongClick();
109        }
110    }
111
112    /* package */ final static class ViewHolder {
113        View thumbnailView;
114        ImageView thumbnailViewImage;
115        Bitmap thumbnailViewImageBitmap;
116        ImageView iconView;
117        TextView labelView;
118        TextView descriptionView;
119        View calloutLine;
120        TaskDescription taskDescription;
121        boolean loadedThumbnailAndIcon;
122    }
123
124    /* package */ final class TaskDescriptionAdapter extends BaseAdapter {
125        private LayoutInflater mInflater;
126
127        public TaskDescriptionAdapter(Context context) {
128            mInflater = LayoutInflater.from(context);
129        }
130
131        public int getCount() {
132            return mRecentTaskDescriptions != null ? mRecentTaskDescriptions.size() : 0;
133        }
134
135        public Object getItem(int position) {
136            return position; // we only need the index
137        }
138
139        public long getItemId(int position) {
140            return position; // we just need something unique for this position
141        }
142
143        public View createView(ViewGroup parent) {
144            View convertView = mInflater.inflate(mRecentItemLayoutId, parent, false);
145            ViewHolder holder = new ViewHolder();
146            holder.thumbnailView = convertView.findViewById(R.id.app_thumbnail);
147            holder.thumbnailViewImage =
148                    (ImageView) convertView.findViewById(R.id.app_thumbnail_image);
149            // If we set the default thumbnail now, we avoid an onLayout when we update
150            // the thumbnail later (if they both have the same dimensions)
151            updateThumbnail(holder, mRecentTasksLoader.getDefaultThumbnail(), false, false);
152            holder.iconView = (ImageView) convertView.findViewById(R.id.app_icon);
153            holder.iconView.setImageBitmap(mRecentTasksLoader.getDefaultIcon());
154            holder.labelView = (TextView) convertView.findViewById(R.id.app_label);
155            holder.calloutLine = convertView.findViewById(R.id.recents_callout_line);
156            holder.descriptionView = (TextView) convertView.findViewById(R.id.app_description);
157
158            convertView.setTag(holder);
159            return convertView;
160        }
161
162        public View getView(int position, View convertView, ViewGroup parent) {
163            if (convertView == null) {
164                convertView = createView(parent);
165            }
166            final ViewHolder holder = (ViewHolder) convertView.getTag();
167
168            // index is reverse since most recent appears at the bottom...
169            final int index = mRecentTaskDescriptions.size() - position - 1;
170
171            final TaskDescription td = mRecentTaskDescriptions.get(index);
172
173            holder.labelView.setText(td.getLabel());
174            holder.thumbnailView.setContentDescription(td.getLabel());
175            holder.loadedThumbnailAndIcon = td.isLoaded();
176            if (td.isLoaded()) {
177                updateThumbnail(holder, td.getThumbnail(), true, false);
178                updateIcon(holder, td.getIcon(), true, false);
179            }
180            if (index == 0) {
181                if (mAnimateIconOfFirstTask) {
182                    ViewHolder oldHolder = mItemToAnimateInWhenWindowAnimationIsFinished;
183                    if (oldHolder != null) {
184                        oldHolder.iconView.setAlpha(1f);
185                        oldHolder.iconView.setTranslationX(0f);
186                        oldHolder.iconView.setTranslationY(0f);
187                        oldHolder.labelView.setAlpha(1f);
188                        oldHolder.labelView.setTranslationX(0f);
189                        oldHolder.labelView.setTranslationY(0f);
190                        if (oldHolder.calloutLine != null) {
191                            oldHolder.calloutLine.setAlpha(1f);
192                            oldHolder.calloutLine.setTranslationX(0f);
193                            oldHolder.calloutLine.setTranslationY(0f);
194                        }
195                    }
196                    mItemToAnimateInWhenWindowAnimationIsFinished = holder;
197                    int translation = -getResources().getDimensionPixelSize(
198                            R.dimen.status_bar_recents_app_icon_translate_distance);
199                    final Configuration config = getResources().getConfiguration();
200                    if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
201                        if (getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
202                            translation = -translation;
203                        }
204                        holder.iconView.setAlpha(0f);
205                        holder.iconView.setTranslationX(translation);
206                        holder.labelView.setAlpha(0f);
207                        holder.labelView.setTranslationX(translation);
208                        holder.calloutLine.setAlpha(0f);
209                        holder.calloutLine.setTranslationX(translation);
210                    } else {
211                        holder.iconView.setAlpha(0f);
212                        holder.iconView.setTranslationY(translation);
213                    }
214                    if (!mWaitingForWindowAnimation) {
215                        animateInIconOfFirstTask();
216                    }
217                }
218            }
219
220            holder.thumbnailView.setTag(td);
221            holder.thumbnailView.setOnLongClickListener(new OnLongClickDelegate(convertView));
222            holder.taskDescription = td;
223            return convertView;
224        }
225
226        public void recycleView(View v) {
227            ViewHolder holder = (ViewHolder) v.getTag();
228            updateThumbnail(holder, mRecentTasksLoader.getDefaultThumbnail(), false, false);
229            holder.iconView.setImageBitmap(mRecentTasksLoader.getDefaultIcon());
230            holder.iconView.setVisibility(INVISIBLE);
231            holder.iconView.animate().cancel();
232            holder.labelView.setText(null);
233            holder.labelView.animate().cancel();
234            holder.thumbnailView.setContentDescription(null);
235            holder.thumbnailView.setTag(null);
236            holder.thumbnailView.setOnLongClickListener(null);
237            holder.thumbnailView.setVisibility(INVISIBLE);
238            holder.iconView.setAlpha(1f);
239            holder.iconView.setTranslationX(0f);
240            holder.iconView.setTranslationY(0f);
241            holder.labelView.setAlpha(1f);
242            holder.labelView.setTranslationX(0f);
243            holder.labelView.setTranslationY(0f);
244            if (holder.calloutLine != null) {
245                holder.calloutLine.setAlpha(1f);
246                holder.calloutLine.setTranslationX(0f);
247                holder.calloutLine.setTranslationY(0f);
248                holder.calloutLine.animate().cancel();
249            }
250            holder.taskDescription = null;
251            holder.loadedThumbnailAndIcon = false;
252        }
253    }
254
255    public RecentsPanelView(Context context, AttributeSet attrs) {
256        this(context, attrs, 0);
257    }
258
259    public RecentsPanelView(Context context, AttributeSet attrs, int defStyle) {
260        super(context, attrs, defStyle);
261        updateValuesFromResources();
262
263        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecentsPanelView,
264                defStyle, 0);
265
266        mRecentItemLayoutId = a.getResourceId(R.styleable.RecentsPanelView_recentItemLayout, 0);
267        mRecentTasksLoader = RecentTasksLoader.getInstance(context);
268        a.recycle();
269    }
270
271    public int numItemsInOneScreenful() {
272        if (mRecentsContainer instanceof RecentsScrollView){
273            RecentsScrollView scrollView
274                    = (RecentsScrollView) mRecentsContainer;
275            return scrollView.numItemsInOneScreenful();
276        }  else {
277            throw new IllegalArgumentException("missing Recents[Horizontal]ScrollView");
278        }
279    }
280
281    private boolean pointInside(int x, int y, View v) {
282        final int l = v.getLeft();
283        final int r = v.getRight();
284        final int t = v.getTop();
285        final int b = v.getBottom();
286        return x >= l && x < r && y >= t && y < b;
287    }
288
289    public boolean isInContentArea(int x, int y) {
290        return pointInside(x, y, mRecentsContainer);
291    }
292
293    public void show(boolean show) {
294        show(show, null, false, false);
295    }
296
297    public void show(boolean show, ArrayList<TaskDescription> recentTaskDescriptions,
298            boolean firstScreenful, boolean animateIconOfFirstTask) {
299        if (show && mCallUiHiddenBeforeNextReload) {
300            onUiHidden();
301            recentTaskDescriptions = null;
302            mAnimateIconOfFirstTask = false;
303            mWaitingForWindowAnimation = false;
304        } else {
305            mAnimateIconOfFirstTask = animateIconOfFirstTask;
306            mWaitingForWindowAnimation = animateIconOfFirstTask;
307        }
308        if (show) {
309            mWaitingToShow = true;
310            refreshRecentTasksList(recentTaskDescriptions, firstScreenful);
311            showIfReady();
312        } else {
313            showImpl(false);
314        }
315    }
316
317    private void showIfReady() {
318        // mWaitingToShow => there was a touch up on the recents button
319        // mRecentTaskDescriptions != null => we've created views for the first screenful of items
320        if (mWaitingToShow && mRecentTaskDescriptions != null) {
321            showImpl(true);
322        }
323    }
324
325    static void sendCloseSystemWindows(Context context, String reason) {
326        if (ActivityManagerNative.isSystemReady()) {
327            try {
328                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
329            } catch (RemoteException e) {
330            }
331        }
332    }
333
334    private void showImpl(boolean show) {
335        sendCloseSystemWindows(mContext, BaseStatusBar.SYSTEM_DIALOG_REASON_RECENT_APPS);
336
337        mShowing = show;
338
339        if (show) {
340            // if there are no apps, bring up a "No recent apps" message
341            boolean noApps = mRecentTaskDescriptions != null
342                    && (mRecentTaskDescriptions.size() == 0);
343            mRecentsNoApps.setAlpha(1f);
344            mRecentsNoApps.setVisibility(noApps ? View.VISIBLE : View.INVISIBLE);
345
346            onAnimationEnd(null);
347            setFocusable(true);
348            setFocusableInTouchMode(true);
349            requestFocus();
350        } else {
351            mWaitingToShow = false;
352            // call onAnimationEnd() and clearRecentTasksList() in onUiHidden()
353            mCallUiHiddenBeforeNextReload = true;
354            if (mPopup != null) {
355                mPopup.dismiss();
356            }
357            ((RecentsActivity) mContext).moveTaskToBack(true);
358        }
359    }
360
361    protected void onAttachedToWindow () {
362        super.onAttachedToWindow();
363        final ViewRootImpl root = getViewRootImpl();
364        if (root != null) {
365            root.setDrawDuringWindowsAnimating(true);
366        }
367    }
368
369    public void onUiHidden() {
370        mCallUiHiddenBeforeNextReload = false;
371        if (!mShowing && mRecentTaskDescriptions != null) {
372            onAnimationEnd(null);
373            clearRecentTasksList();
374        }
375    }
376
377    public void dismiss() {
378        ((RecentsActivity) mContext).dismissAndGoHome();
379    }
380
381    public void dismissAndGoBack() {
382        ((RecentsActivity) mContext).dismissAndGoBack();
383    }
384
385    public void onAnimationCancel(Animator animation) {
386    }
387
388    public void onAnimationEnd(Animator animation) {
389        if (mShowing) {
390            final LayoutTransition transitioner = new LayoutTransition();
391            ((ViewGroup)mRecentsContainer).setLayoutTransition(transitioner);
392            createCustomAnimations(transitioner);
393        } else {
394            ((ViewGroup)mRecentsContainer).setLayoutTransition(null);
395        }
396    }
397
398    public void onAnimationRepeat(Animator animation) {
399    }
400
401    public void onAnimationStart(Animator animation) {
402    }
403
404    @Override
405    public boolean dispatchHoverEvent(MotionEvent event) {
406        // Ignore hover events outside of this panel bounds since such events
407        // generate spurious accessibility events with the panel content when
408        // tapping outside of it, thus confusing the user.
409        final int x = (int) event.getX();
410        final int y = (int) event.getY();
411        if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) {
412            return super.dispatchHoverEvent(event);
413        }
414        return true;
415    }
416
417    /**
418     * Whether the panel is showing, or, if it's animating, whether it will be
419     * when the animation is done.
420     */
421    public boolean isShowing() {
422        return mShowing;
423    }
424
425    public void setRecentTasksLoader(RecentTasksLoader loader) {
426        mRecentTasksLoader = loader;
427    }
428
429    public void updateValuesFromResources() {
430        final Resources res = mContext.getResources();
431        mThumbnailWidth = Math.round(res.getDimension(R.dimen.status_bar_recents_thumbnail_width));
432        mFitThumbnailToXY = res.getBoolean(R.bool.config_recents_thumbnail_image_fits_to_xy);
433    }
434
435    @Override
436    protected void onFinishInflate() {
437        super.onFinishInflate();
438
439        mRecentsContainer = (ViewGroup) findViewById(R.id.recents_container);
440        mListAdapter = new TaskDescriptionAdapter(mContext);
441        if (mRecentsContainer instanceof RecentsScrollView){
442            RecentsScrollView scrollView
443                    = (RecentsScrollView) mRecentsContainer;
444            scrollView.setAdapter(mListAdapter);
445            scrollView.setCallback(this);
446        } else {
447            throw new IllegalArgumentException("missing Recents[Horizontal]ScrollView");
448        }
449
450        mRecentsScrim = findViewById(R.id.recents_bg_protect);
451        mRecentsNoApps = findViewById(R.id.recents_no_apps);
452
453        if (mRecentsScrim != null) {
454            mHighEndGfx = ActivityManager.isHighEndGfx();
455            if (!mHighEndGfx) {
456                mRecentsScrim.setBackground(null);
457            } else if (mRecentsScrim.getBackground() instanceof BitmapDrawable) {
458                // In order to save space, we make the background texture repeat in the Y direction
459                ((BitmapDrawable) mRecentsScrim.getBackground()).setTileModeY(TileMode.REPEAT);
460            }
461        }
462    }
463
464    public void setMinSwipeAlpha(float minAlpha) {
465        if (mRecentsContainer instanceof RecentsScrollView){
466            RecentsScrollView scrollView
467                = (RecentsScrollView) mRecentsContainer;
468            scrollView.setMinSwipeAlpha(minAlpha);
469        }
470    }
471
472    private void createCustomAnimations(LayoutTransition transitioner) {
473        transitioner.setDuration(200);
474        transitioner.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0);
475        transitioner.setAnimator(LayoutTransition.DISAPPEARING, null);
476    }
477
478    private void updateIcon(ViewHolder h, Drawable icon, boolean show, boolean anim) {
479        if (icon != null) {
480            h.iconView.setImageDrawable(icon);
481            if (show && h.iconView.getVisibility() != View.VISIBLE) {
482                if (anim) {
483                    h.iconView.setAnimation(
484                            AnimationUtils.loadAnimation(mContext, R.anim.recent_appear));
485                }
486                h.iconView.setVisibility(View.VISIBLE);
487            }
488        }
489    }
490
491    private void updateThumbnail(ViewHolder h, Bitmap thumbnail, boolean show, boolean anim) {
492        if (thumbnail != null) {
493            // Should remove the default image in the frame
494            // that this now covers, to improve scrolling speed.
495            // That can't be done until the anim is complete though.
496            h.thumbnailViewImage.setImageBitmap(thumbnail);
497
498            // scale the image to fill the full width of the ImageView. do this only if
499            // we haven't set a bitmap before, or if the bitmap size has changed
500            if (h.thumbnailViewImageBitmap == null ||
501                h.thumbnailViewImageBitmap.getWidth() != thumbnail.getWidth() ||
502                h.thumbnailViewImageBitmap.getHeight() != thumbnail.getHeight()) {
503                if (mFitThumbnailToXY) {
504                    h.thumbnailViewImage.setScaleType(ScaleType.FIT_XY);
505                } else {
506                    Matrix scaleMatrix = new Matrix();
507                    float scale = mThumbnailWidth / (float) thumbnail.getWidth();
508                    scaleMatrix.setScale(scale, scale);
509                    h.thumbnailViewImage.setScaleType(ScaleType.MATRIX);
510                    h.thumbnailViewImage.setImageMatrix(scaleMatrix);
511                }
512            }
513            if (show && h.thumbnailView.getVisibility() != View.VISIBLE) {
514                if (anim) {
515                    h.thumbnailView.setAnimation(
516                            AnimationUtils.loadAnimation(mContext, R.anim.recent_appear));
517                }
518                h.thumbnailView.setVisibility(View.VISIBLE);
519            }
520            h.thumbnailViewImageBitmap = thumbnail;
521        }
522    }
523
524    void onTaskThumbnailLoaded(TaskDescription td) {
525        synchronized (td) {
526            if (mRecentsContainer != null) {
527                ViewGroup container = mRecentsContainer;
528                if (container instanceof RecentsScrollView) {
529                    container = (ViewGroup) container.findViewById(
530                            R.id.recents_linear_layout);
531                }
532                // Look for a view showing this thumbnail, to update.
533                for (int i=0; i < container.getChildCount(); i++) {
534                    View v = container.getChildAt(i);
535                    if (v.getTag() instanceof ViewHolder) {
536                        ViewHolder h = (ViewHolder)v.getTag();
537                        if (!h.loadedThumbnailAndIcon && h.taskDescription == td) {
538                            // only fade in the thumbnail if recents is already visible-- we
539                            // show it immediately otherwise
540                            //boolean animateShow = mShowing &&
541                            //    mRecentsContainer.getAlpha() > ViewConfiguration.ALPHA_THRESHOLD;
542                            boolean animateShow = false;
543                            updateIcon(h, td.getIcon(), true, animateShow);
544                            updateThumbnail(h, td.getThumbnail(), true, animateShow);
545                            h.loadedThumbnailAndIcon = true;
546                        }
547                    }
548                }
549            }
550        }
551        showIfReady();
552    }
553
554    private void animateInIconOfFirstTask() {
555        if (mItemToAnimateInWhenWindowAnimationIsFinished != null &&
556                !mRecentTasksLoader.isFirstScreenful()) {
557            int timeSinceWindowAnimation =
558                    (int) (System.currentTimeMillis() - mWindowAnimationStartTime);
559            final int minStartDelay = 150;
560            final int startDelay = Math.max(0, Math.min(
561                    minStartDelay - timeSinceWindowAnimation, minStartDelay));
562            final int duration = 250;
563            final ViewHolder holder = mItemToAnimateInWhenWindowAnimationIsFinished;
564            final TimeInterpolator cubic = new DecelerateInterpolator(1.5f);
565            FirstFrameAnimatorHelper.initializeDrawListener(holder.iconView);
566            for (View v :
567                new View[] { holder.iconView, holder.labelView, holder.calloutLine }) {
568                if (v != null) {
569                    ViewPropertyAnimator vpa = v.animate().translationX(0).translationY(0)
570                            .alpha(1f).setStartDelay(startDelay)
571                            .setDuration(duration).setInterpolator(cubic);
572                    FirstFrameAnimatorHelper h = new FirstFrameAnimatorHelper(vpa, v);
573                }
574            }
575            mItemToAnimateInWhenWindowAnimationIsFinished = null;
576            mAnimateIconOfFirstTask = false;
577        }
578    }
579
580    public void onWindowAnimationStart() {
581        mWaitingForWindowAnimation = false;
582        mWindowAnimationStartTime = System.currentTimeMillis();
583        animateInIconOfFirstTask();
584    }
585
586    public void clearRecentTasksList() {
587        // Clear memory used by screenshots
588        if (mRecentTaskDescriptions != null) {
589            mRecentTasksLoader.cancelLoadingThumbnailsAndIcons(this);
590            onTaskLoadingCancelled();
591        }
592    }
593
594    public void onTaskLoadingCancelled() {
595        // Gets called by RecentTasksLoader when it's cancelled
596        if (mRecentTaskDescriptions != null) {
597            mRecentTaskDescriptions = null;
598            mListAdapter.notifyDataSetInvalidated();
599        }
600    }
601
602    public void refreshViews() {
603        mListAdapter.notifyDataSetInvalidated();
604        updateUiElements();
605        showIfReady();
606    }
607
608    public void refreshRecentTasksList() {
609        refreshRecentTasksList(null, false);
610    }
611
612    private void refreshRecentTasksList(
613            ArrayList<TaskDescription> recentTasksList, boolean firstScreenful) {
614        if (mRecentTaskDescriptions == null && recentTasksList != null) {
615            onTasksLoaded(recentTasksList, firstScreenful);
616        } else {
617            mRecentTasksLoader.loadTasksInBackground();
618        }
619    }
620
621    public void onTasksLoaded(ArrayList<TaskDescription> tasks, boolean firstScreenful) {
622        if (mRecentTaskDescriptions == null) {
623            mRecentTaskDescriptions = new ArrayList<TaskDescription>(tasks);
624        } else {
625            mRecentTaskDescriptions.addAll(tasks);
626        }
627        if (((RecentsActivity) mContext).isActivityShowing()) {
628            refreshViews();
629        }
630    }
631
632    private void updateUiElements() {
633        final int items = mRecentTaskDescriptions != null
634                ? mRecentTaskDescriptions.size() : 0;
635
636        mRecentsContainer.setVisibility(items > 0 ? View.VISIBLE : View.GONE);
637
638        // Set description for accessibility
639        int numRecentApps = mRecentTaskDescriptions != null
640                ? mRecentTaskDescriptions.size() : 0;
641        String recentAppsAccessibilityDescription;
642        if (numRecentApps == 0) {
643            recentAppsAccessibilityDescription =
644                getResources().getString(R.string.status_bar_no_recent_apps);
645        } else {
646            recentAppsAccessibilityDescription = getResources().getQuantityString(
647                R.plurals.status_bar_accessibility_recent_apps, numRecentApps, numRecentApps);
648        }
649        setContentDescription(recentAppsAccessibilityDescription);
650    }
651
652    public boolean simulateClick(int persistentTaskId) {
653        if (mRecentsContainer instanceof RecentsScrollView){
654            RecentsScrollView scrollView
655                = (RecentsScrollView) mRecentsContainer;
656            View v = scrollView.findViewForTask(persistentTaskId);
657            if (v != null) {
658                handleOnClick(v);
659                return true;
660            }
661        }
662        return false;
663    }
664
665    public void handleOnClick(View view) {
666        ViewHolder holder = (ViewHolder)view.getTag();
667        TaskDescription ad = holder.taskDescription;
668        final Context context = view.getContext();
669        final ActivityManager am = (ActivityManager)
670                context.getSystemService(Context.ACTIVITY_SERVICE);
671        Bitmap bm = holder.thumbnailViewImageBitmap;
672        boolean usingDrawingCache;
673        if (bm.getWidth() == holder.thumbnailViewImage.getWidth() &&
674                bm.getHeight() == holder.thumbnailViewImage.getHeight()) {
675            usingDrawingCache = false;
676        } else {
677            holder.thumbnailViewImage.setDrawingCacheEnabled(true);
678            bm = holder.thumbnailViewImage.getDrawingCache();
679            usingDrawingCache = true;
680        }
681        Bundle opts = (bm == null) ?
682                null :
683                ActivityOptions.makeThumbnailScaleUpAnimation(
684                        holder.thumbnailViewImage, bm, 0, 0, null).toBundle();
685
686        show(false);
687        if (ad.taskId >= 0) {
688            // This is an active task; it should just go to the foreground.
689            am.moveTaskToFront(ad.taskId, ActivityManager.MOVE_TASK_WITH_HOME,
690                    opts);
691        } else {
692            Intent intent = ad.intent;
693            intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
694                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME
695                    | Intent.FLAG_ACTIVITY_NEW_TASK);
696            if (DEBUG) Log.v(TAG, "Starting activity " + intent);
697            try {
698                context.startActivityAsUser(intent, opts,
699                        new UserHandle(UserHandle.USER_CURRENT));
700            } catch (SecurityException e) {
701                Log.e(TAG, "Recents does not have the permission to launch " + intent, e);
702            }
703        }
704        if (usingDrawingCache) {
705            holder.thumbnailViewImage.setDrawingCacheEnabled(false);
706        }
707    }
708
709    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
710        handleOnClick(view);
711    }
712
713    public void handleSwipe(View view) {
714        TaskDescription ad = ((ViewHolder) view.getTag()).taskDescription;
715        if (ad == null) {
716            Log.v(TAG, "Not able to find activity description for swiped task; view=" + view +
717                    " tag=" + view.getTag());
718            return;
719        }
720        if (DEBUG) Log.v(TAG, "Jettison " + ad.getLabel());
721        mRecentTaskDescriptions.remove(ad);
722        mRecentTasksLoader.remove(ad);
723
724        // Handled by widget containers to enable LayoutTransitions properly
725        // mListAdapter.notifyDataSetChanged();
726
727        if (mRecentTaskDescriptions.size() == 0) {
728            dismissAndGoBack();
729        }
730
731        // Currently, either direction means the same thing, so ignore direction and remove
732        // the task.
733        final ActivityManager am = (ActivityManager)
734                mContext.getSystemService(Context.ACTIVITY_SERVICE);
735        if (am != null) {
736            am.removeTask(ad.persistentTaskId, ActivityManager.REMOVE_TASK_KILL_PROCESS);
737
738            // Accessibility feedback
739            setContentDescription(
740                    mContext.getString(R.string.accessibility_recents_item_dismissed, ad.getLabel()));
741            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
742            setContentDescription(null);
743        }
744    }
745
746    private void startApplicationDetailsActivity(String packageName) {
747        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
748                Uri.fromParts("package", packageName, null));
749        intent.setComponent(intent.resolveActivity(mContext.getPackageManager()));
750        TaskStackBuilder.create(getContext())
751                .addNextIntentWithParentStack(intent).startActivities();
752    }
753
754    public boolean onInterceptTouchEvent(MotionEvent ev) {
755        if (mPopup != null) {
756            return true;
757        } else {
758            return super.onInterceptTouchEvent(ev);
759        }
760    }
761
762    public void handleLongPress(
763            final View selectedView, final View anchorView, final View thumbnailView) {
764        thumbnailView.setSelected(true);
765        final PopupMenu popup =
766            new PopupMenu(mContext, anchorView == null ? selectedView : anchorView);
767        mPopup = popup;
768        popup.getMenuInflater().inflate(R.menu.recent_popup_menu, popup.getMenu());
769        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
770            public boolean onMenuItemClick(MenuItem item) {
771                if (item.getItemId() == R.id.recent_remove_item) {
772                    mRecentsContainer.removeViewInLayout(selectedView);
773                } else if (item.getItemId() == R.id.recent_inspect_item) {
774                    ViewHolder viewHolder = (ViewHolder) selectedView.getTag();
775                    if (viewHolder != null) {
776                        final TaskDescription ad = viewHolder.taskDescription;
777                        startApplicationDetailsActivity(ad.packageName);
778                        show(false);
779                    } else {
780                        throw new IllegalStateException("Oops, no tag on view " + selectedView);
781                    }
782                } else {
783                    return false;
784                }
785                return true;
786            }
787        });
788        popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
789            public void onDismiss(PopupMenu menu) {
790                thumbnailView.setSelected(false);
791                mPopup = null;
792            }
793        });
794        popup.show();
795    }
796}
797