RecentsPanelView.java revision 6f983a7906ce98a1a8e3f5e805da8c933f53fc3d
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 java.util.ArrayList;
20import java.util.List;
21
22import android.animation.Animator;
23import android.animation.LayoutTransition;
24import android.app.ActivityManager;
25import android.content.Context;
26import android.content.Intent;
27import android.content.pm.ActivityInfo;
28import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
30import android.content.res.Configuration;
31import android.content.res.Resources;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.graphics.Canvas;
35import android.graphics.Matrix;
36import android.graphics.Paint;
37import android.graphics.Rect;
38import android.graphics.RectF;
39import android.graphics.Shader.TileMode;
40import android.graphics.drawable.BitmapDrawable;
41import android.graphics.drawable.Drawable;
42import android.net.Uri;
43import android.os.AsyncTask;
44import android.os.Handler;
45import android.os.Process;
46import android.os.SystemClock;
47import android.provider.Settings;
48import android.util.AttributeSet;
49import android.util.DisplayMetrics;
50import android.util.Log;
51import android.view.KeyEvent;
52import android.view.LayoutInflater;
53import android.view.MenuItem;
54import android.view.MotionEvent;
55import android.view.View;
56import android.view.ViewGroup;
57import android.view.animation.AnimationUtils;
58import android.widget.AdapterView;
59import android.widget.BaseAdapter;
60import android.widget.HorizontalScrollView;
61import android.widget.ImageView;
62import android.widget.PopupMenu;
63import android.widget.RelativeLayout;
64import android.widget.ScrollView;
65import android.widget.TextView;
66import android.widget.AdapterView.OnItemClickListener;
67
68import com.android.systemui.R;
69import com.android.systemui.statusbar.StatusBar;
70import com.android.systemui.statusbar.phone.PhoneStatusBar;
71import com.android.systemui.statusbar.tablet.StatusBarPanel;
72import com.android.systemui.statusbar.tablet.TabletStatusBar;
73
74public class RecentsPanelView extends RelativeLayout
75        implements OnItemClickListener, RecentsCallback, StatusBarPanel, Animator.AnimatorListener {
76    static final String TAG = "RecentsPanelView";
77    static final boolean DEBUG = TabletStatusBar.DEBUG || PhoneStatusBar.DEBUG || false;
78    private static final int DISPLAY_TASKS = 20;
79    private static final int MAX_TASKS = DISPLAY_TASKS + 1; // allow extra for non-apps
80    private StatusBar mBar;
81    private ArrayList<ActivityDescription> mActivityDescriptions;
82    private AsyncTask<Void, Integer, Void> mThumbnailLoader;
83    private int mIconDpi;
84    private View mRecentsScrim;
85    private View mRecentsGlowView;
86    private ViewGroup mRecentsContainer;
87    private Bitmap mAppThumbnailBackground;
88
89    private boolean mShowing;
90    private Choreographer mChoreo;
91    private View mRecentsDismissButton;
92    private ActivityDescriptionAdapter mListAdapter;
93    private final Handler mHandler = new Handler();
94
95    /* package */ final class ActivityDescription {
96        final ActivityManager.RecentTaskInfo recentTaskInfo;
97        final ResolveInfo resolveInfo;
98        int taskId; // application task id for curating apps
99        Intent intent; // launch intent for application
100        Matrix matrix; // arbitrary rotation matrix to correct orientation
101        String packageName; // used to override animations (see onClick())
102        int position; // position in list
103
104        private Bitmap mThumbnail; // generated by Activity.onCreateThumbnail()
105        private Drawable mIcon; // application package icon
106        private CharSequence mLabel; // application package label
107
108        public ActivityDescription(ActivityManager.RecentTaskInfo _recentInfo,
109                ResolveInfo _resolveInfo, Intent _intent,
110                int _id, int _pos, String _packageName) {
111            recentTaskInfo = _recentInfo;
112            resolveInfo = _resolveInfo;
113            intent = _intent;
114            taskId = _id;
115            position = _pos;
116            packageName = _packageName;
117        }
118
119        public CharSequence getLabel() {
120            return mLabel;
121        }
122
123        public Drawable getIcon() {
124            return mIcon;
125        }
126
127        public void setThumbnail(Bitmap thumbnail) {
128            mThumbnail = compositeBitmap(mAppThumbnailBackground, thumbnail);
129        }
130
131        public Bitmap getThumbnail() {
132            return mThumbnail;
133        }
134    }
135
136    private final class OnLongClickDelegate implements View.OnLongClickListener {
137        View mOtherView;
138        OnLongClickDelegate(View other) {
139            mOtherView = other;
140        }
141        public boolean onLongClick(View v) {
142            return mOtherView.performLongClick();
143        }
144    }
145
146    /* package */ final static class ViewHolder {
147        View thumbnailView;
148        ImageView thumbnailViewImage;
149        ImageView iconView;
150        TextView labelView;
151        TextView descriptionView;
152        ActivityDescription activityDescription;
153    }
154
155    /* package */ final class ActivityDescriptionAdapter extends BaseAdapter {
156        private LayoutInflater mInflater;
157
158        public ActivityDescriptionAdapter(Context context) {
159            mInflater = LayoutInflater.from(context);
160        }
161
162        public int getCount() {
163            return mActivityDescriptions != null ? mActivityDescriptions.size() : 0;
164        }
165
166        public Object getItem(int position) {
167            return position; // we only need the index
168        }
169
170        public long getItemId(int position) {
171            return position; // we just need something unique for this position
172        }
173
174        public View getView(int position, View convertView, ViewGroup parent) {
175            ViewHolder holder;
176            if (convertView == null) {
177                convertView = mInflater.inflate(R.layout.status_bar_recent_item, parent, false);
178                holder = new ViewHolder();
179                holder.thumbnailView = convertView.findViewById(R.id.app_thumbnail);
180                holder.thumbnailViewImage = (ImageView) convertView.findViewById(
181                        R.id.app_thumbnail_image);
182                holder.iconView = (ImageView) convertView.findViewById(R.id.app_icon);
183                holder.labelView = (TextView) convertView.findViewById(R.id.app_label);
184                holder.descriptionView = (TextView) convertView.findViewById(R.id.app_description);
185                convertView.setTag(holder);
186            } else {
187                holder = (ViewHolder) convertView.getTag();
188            }
189
190            // activityId is reverse since most recent appears at the bottom...
191            final int activityId = mActivityDescriptions.size() - position - 1;
192
193            final ActivityDescription activityDescription = mActivityDescriptions.get(activityId);
194            holder.thumbnailViewImage.setImageBitmap(activityDescription.getThumbnail());
195            holder.iconView.setImageDrawable(activityDescription.getIcon());
196            holder.labelView.setText(activityDescription.getLabel());
197            holder.descriptionView.setText(activityDescription.recentTaskInfo.description);
198            holder.thumbnailView.setTag(activityDescription);
199            holder.thumbnailView.setOnLongClickListener(new OnLongClickDelegate(convertView));
200            holder.activityDescription = activityDescription;
201
202            return convertView;
203        }
204    }
205
206    @Override
207    public boolean onKeyUp(int keyCode, KeyEvent event) {
208        if (keyCode == KeyEvent.KEYCODE_BACK && !event.isCanceled()) {
209            show(false, true);
210            return true;
211        }
212        return super.onKeyUp(keyCode, event);
213    }
214
215    public boolean isInContentArea(int x, int y) {
216        // use mRecentsContainer's exact bounds to determine horizontal position
217        final int l = mRecentsContainer.getLeft();
218        final int r = mRecentsContainer.getRight();
219        // use surrounding mRecentsGlowView's position in parent determine vertical bounds
220        final int t = mRecentsGlowView.getTop();
221        final int b = mRecentsGlowView.getBottom();
222        return x >= l && x < r && y >= t && y < b;
223    }
224
225    public void show(boolean show, boolean animate) {
226        if (animate) {
227            if (mShowing != show) {
228                mShowing = show;
229                if (show) {
230                    setVisibility(View.VISIBLE);
231                }
232                mChoreo.startAnimation(show);
233            }
234        } else {
235            mShowing = show;
236            setVisibility(show ? View.VISIBLE : View.GONE);
237            mChoreo.jumpTo(show);
238        }
239        if (show) {
240            setFocusable(true);
241            setFocusableInTouchMode(true);
242            requestFocus();
243        }
244    }
245
246    public void hide(boolean animate) {
247        mShowing = false;
248        if (!animate) {
249            setVisibility(View.GONE);
250        }
251        if (mBar != null) {
252            mBar.animateCollapse();
253        }
254    }
255
256    public void handleShowBackground(boolean show) {
257        if (show) {
258            mRecentsScrim.setBackgroundResource(R.drawable.status_bar_recents_background);
259        } else {
260            mRecentsScrim.setBackgroundDrawable(null);
261        }
262    }
263
264    public boolean isRecentsVisible() {
265        return getVisibility() == VISIBLE;
266    }
267
268    public void onAnimationCancel(Animator animation) {
269    }
270
271    public void onAnimationEnd(Animator animation) {
272        if (mShowing) {
273            final LayoutTransition transitioner = new LayoutTransition();
274            ((ViewGroup)mRecentsContainer).setLayoutTransition(transitioner);
275            createCustomAnimations(transitioner);
276        } else {
277            ((ViewGroup)mRecentsContainer).setLayoutTransition(null);
278        }
279    }
280
281    public void onAnimationRepeat(Animator animation) {
282    }
283
284    public void onAnimationStart(Animator animation) {
285    }
286
287
288    /**
289     * We need to be aligned at the bottom.  LinearLayout can't do this, so instead,
290     * let LinearLayout do all the hard work, and then shift everything down to the bottom.
291     */
292    @Override
293    protected void onLayout(boolean changed, int l, int t, int r, int b) {
294        super.onLayout(changed, l, t, r, b);
295        mChoreo.setPanelHeight(mRecentsContainer.getHeight());
296    }
297
298    @Override
299    public boolean dispatchHoverEvent(MotionEvent event) {
300        // Ignore hover events outside of this panel bounds since such events
301        // generate spurious accessibility events with the panel content when
302        // tapping outside of it, thus confusing the user.
303        final int x = (int) event.getX();
304        final int y = (int) event.getY();
305        if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) {
306            return super.dispatchHoverEvent(event);
307        }
308        return true;
309    }
310
311    /**
312     * Whether the panel is showing, or, if it's animating, whether it will be
313     * when the animation is done.
314     */
315    public boolean isShowing() {
316        return mShowing;
317    }
318
319    public void setBar(StatusBar bar) {
320        mBar = bar;
321    }
322
323    public RecentsPanelView(Context context, AttributeSet attrs) {
324        this(context, attrs, 0);
325    }
326
327    public RecentsPanelView(Context context, AttributeSet attrs, int defStyle) {
328        super(context, attrs, defStyle);
329
330        Resources res = context.getResources();
331        boolean xlarge = (res.getConfiguration().screenLayout
332                & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE;
333
334        mIconDpi = xlarge ? DisplayMetrics.DENSITY_HIGH : res.getDisplayMetrics().densityDpi;
335
336        int width = (int) res.getDimension(R.dimen.status_bar_recents_thumbnail_width);
337        int height = (int) res.getDimension(R.dimen.status_bar_recents_thumbnail_height);
338        int color = res.getColor(R.drawable.status_bar_recents_app_thumbnail_background);
339        mAppThumbnailBackground = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
340        Canvas c = new Canvas(mAppThumbnailBackground);
341        c.drawColor(color);
342    }
343
344    @Override
345    protected void onFinishInflate() {
346        super.onFinishInflate();
347        mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
348        mRecentsContainer = (ViewGroup) findViewById(R.id.recents_container);
349        mListAdapter = new ActivityDescriptionAdapter(mContext);
350        if (mRecentsContainer instanceof RecentsHorizontalScrollView){
351            RecentsHorizontalScrollView scrollView
352                    = (RecentsHorizontalScrollView) mRecentsContainer;
353            scrollView.setAdapter(mListAdapter);
354            scrollView.setCallback(this);
355        } else if (mRecentsContainer instanceof RecentsVerticalScrollView){
356            RecentsVerticalScrollView scrollView
357                    = (RecentsVerticalScrollView) mRecentsContainer;
358            scrollView.setAdapter(mListAdapter);
359            scrollView.setCallback(this);
360        }
361        else {
362            throw new IllegalArgumentException("missing Recents[Horizontal]ScrollView");
363        }
364
365
366        mRecentsGlowView = findViewById(R.id.recents_glow);
367        mRecentsScrim = (View) findViewById(R.id.recents_bg_protect);
368        mChoreo = new Choreographer(this, mRecentsScrim, mRecentsGlowView, this);
369        mRecentsDismissButton = findViewById(R.id.recents_dismiss_button);
370        mRecentsDismissButton.setOnClickListener(new OnClickListener() {
371            public void onClick(View v) {
372                hide(true);
373            }
374        });
375
376        // In order to save space, we make the background texture repeat in the Y direction
377        if (mRecentsScrim != null && mRecentsScrim.getBackground() instanceof BitmapDrawable) {
378            ((BitmapDrawable) mRecentsScrim.getBackground()).setTileModeY(TileMode.REPEAT);
379        }
380    }
381
382    private void createCustomAnimations(LayoutTransition transitioner) {
383        transitioner.setDuration(200);
384        transitioner.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0);
385        transitioner.setAnimator(LayoutTransition.DISAPPEARING, null);
386    }
387
388    @Override
389    protected void onVisibilityChanged(View changedView, int visibility) {
390        super.onVisibilityChanged(changedView, visibility);
391        if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + changedView + ", " + visibility + ")");
392        if (visibility == View.VISIBLE && changedView == this) {
393            refreshApplicationList();
394        }
395
396        if (mRecentsContainer instanceof RecentsHorizontalScrollView) {
397            ((RecentsHorizontalScrollView) mRecentsContainer).onRecentsVisibilityChanged();
398        } else if (mRecentsContainer instanceof RecentsVerticalScrollView) {
399            ((RecentsVerticalScrollView) mRecentsContainer).onRecentsVisibilityChanged();
400        } else {
401            throw new IllegalArgumentException("missing Recents[Horizontal]ScrollView");
402        }
403    }
404
405    Drawable getFullResDefaultActivityIcon() {
406        return getFullResIcon(Resources.getSystem(),
407                com.android.internal.R.mipmap.sym_def_app_icon);
408    }
409
410    Drawable getFullResIcon(Resources resources, int iconId) {
411        try {
412            return resources.getDrawableForDensity(iconId, mIconDpi);
413        } catch (Resources.NotFoundException e) {
414            return getFullResDefaultActivityIcon();
415        }
416    }
417
418    private Drawable getFullResIcon(ResolveInfo info, PackageManager packageManager) {
419        Resources resources;
420        try {
421            resources = packageManager.getResourcesForApplication(
422                    info.activityInfo.applicationInfo);
423        } catch (PackageManager.NameNotFoundException e) {
424            resources = null;
425        }
426        if (resources != null) {
427            int iconId = info.activityInfo.getIconResource();
428            if (iconId != 0) {
429                return getFullResIcon(resources, iconId);
430            }
431        }
432        return getFullResDefaultActivityIcon();
433    }
434
435    private ArrayList<ActivityDescription> getRecentTasks() {
436        ArrayList<ActivityDescription> activityDescriptions = new ArrayList<ActivityDescription>();
437        final PackageManager pm = mContext.getPackageManager();
438        final ActivityManager am = (ActivityManager)
439                mContext.getSystemService(Context.ACTIVITY_SERVICE);
440
441        final List<ActivityManager.RecentTaskInfo> recentTasks =
442                am.getRecentTasks(MAX_TASKS, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
443
444        ActivityInfo homeInfo = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
445                    .resolveActivityInfo(pm, 0);
446
447        int numTasks = recentTasks.size();
448
449        // skip the first activity - assume it's either the home screen or the current app.
450        final int first = 1;
451        for (int i = first, index = 0; i < numTasks && (index < MAX_TASKS); ++i) {
452            final ActivityManager.RecentTaskInfo recentInfo = recentTasks.get(i);
453
454            Intent intent = new Intent(recentInfo.baseIntent);
455            if (recentInfo.origActivity != null) {
456                intent.setComponent(recentInfo.origActivity);
457            }
458
459            // Skip the current home activity.
460            if (homeInfo != null
461                    && homeInfo.packageName.equals(intent.getComponent().getPackageName())
462                    && homeInfo.name.equals(intent.getComponent().getClassName())) {
463                continue;
464            }
465
466            intent.setFlags((intent.getFlags()&~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
467                    | Intent.FLAG_ACTIVITY_NEW_TASK);
468            final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
469            if (resolveInfo != null) {
470                final ActivityInfo info = resolveInfo.activityInfo;
471                final String title = info.loadLabel(pm).toString();
472                // Drawable icon = info.loadIcon(pm);
473                Drawable icon = getFullResIcon(resolveInfo, pm);
474                int id = recentInfo.id;
475                if (title != null && title.length() > 0 && icon != null) {
476                    if (DEBUG) Log.v(TAG, "creating activity desc for id=" + id + ", label=" + title);
477                    ActivityManager.TaskThumbnails thumbs = am.getTaskThumbnails(
478                            recentInfo.persistentId);
479                    ActivityDescription item = new ActivityDescription(recentInfo,
480                            resolveInfo, intent, id, index, info.packageName);
481                    activityDescriptions.add(item);
482                    ++index;
483                } else {
484                    if (DEBUG) Log.v(TAG, "SKIPPING item " + id);
485                }
486            }
487        }
488        return activityDescriptions;
489    }
490
491    ActivityDescription findActivityDescription(int id)
492    {
493        ActivityDescription desc = null;
494        for (int i = 0; i < mActivityDescriptions.size(); i++) {
495            ActivityDescription item = mActivityDescriptions.get(i);
496            if (item != null && item.taskId == id) {
497                desc = item;
498                break;
499            }
500        }
501        return desc;
502    }
503
504    void loadActivityDescription(ActivityDescription ad, int index) {
505        final ActivityManager am = (ActivityManager)
506                mContext.getSystemService(Context.ACTIVITY_SERVICE);
507        final PackageManager pm = mContext.getPackageManager();
508        ActivityManager.TaskThumbnails thumbs = am.getTaskThumbnails(
509                ad.recentTaskInfo.persistentId);
510        CharSequence label = ad.resolveInfo.activityInfo.loadLabel(pm);
511        Drawable icon = getFullResIcon(ad.resolveInfo, pm);
512        if (DEBUG) Log.v(TAG, "Loaded bitmap for #" + index + " in "
513                + ad + ": " + thumbs.mainThumbnail);
514        synchronized (ad) {
515            ad.mLabel = label;
516            ad.mIcon = icon;
517            ad.setThumbnail(thumbs != null ? thumbs.mainThumbnail : null);
518        }
519    }
520
521    void applyActivityDescription(ActivityDescription ad, int index, boolean anim) {
522        synchronized (ad) {
523            if (mRecentsContainer != null) {
524                ViewGroup container = mRecentsContainer;
525                if (container instanceof HorizontalScrollView
526                        || container instanceof ScrollView) {
527                    container = (ViewGroup)container.findViewById(
528                            R.id.recents_linear_layout);
529                }
530                // Look for a view showing this thumbnail, to update.
531                for (int i=0; i<container.getChildCount(); i++) {
532                    View v = container.getChildAt(i);
533                    if (v.getTag() instanceof ViewHolder) {
534                        ViewHolder h = (ViewHolder)v.getTag();
535                        if (h.activityDescription == ad) {
536                            if (DEBUG) Log.v(TAG, "Updatating thumbnail #" + index + " in "
537                                    + h.activityDescription
538                                    + ": " + ad.getThumbnail());
539                            h.iconView.setImageDrawable(ad.getIcon());
540                            if (anim) {
541                                h.iconView.setAnimation(AnimationUtils.loadAnimation(
542                                        mContext, R.anim.recent_appear));
543                            }
544                            h.iconView.setVisibility(View.VISIBLE);
545                            h.labelView.setText(ad.getLabel());
546                            if (anim) {
547                                h.labelView.setAnimation(AnimationUtils.loadAnimation(
548                                        mContext, R.anim.recent_appear));
549                            }
550                            h.labelView.setVisibility(View.VISIBLE);
551                            Bitmap thumbnail = ad.getThumbnail();
552                            if (thumbnail != null) {
553                                // Should remove the default image in the frame
554                                // that this now covers, to improve scrolling speed.
555                                // That can't be done until the anim is complete though.
556                                h.thumbnailViewImage.setImageBitmap(thumbnail);
557                                if (anim) {
558                                    h.thumbnailViewImage.setAnimation(AnimationUtils.loadAnimation(
559                                            mContext, R.anim.recent_appear));
560                                }
561                                h.thumbnailViewImage.setVisibility(View.VISIBLE);
562                            }
563                        }
564                    }
565                }
566            }
567        }
568    }
569
570    private void refreshApplicationList() {
571        if (mThumbnailLoader != null) {
572            mThumbnailLoader.cancel(false);
573            mThumbnailLoader = null;
574        }
575        mActivityDescriptions = getRecentTasks();
576        for (ActivityDescription ad : mActivityDescriptions) {
577            ad.setThumbnail(mAppThumbnailBackground);
578        }
579        mListAdapter.notifyDataSetInvalidated();
580        if (mActivityDescriptions.size() > 0) {
581            if (DEBUG) Log.v(TAG, "Showing " + mActivityDescriptions.size() + " apps");
582            updateUiElements(getResources().getConfiguration());
583            final ArrayList<ActivityDescription> descriptions = mActivityDescriptions;
584            loadActivityDescription(descriptions.get(0), 0);
585            applyActivityDescription(descriptions.get(0), 0, false);
586            if (descriptions.size() > 1) {
587                mThumbnailLoader = new AsyncTask<Void, Integer, Void>() {
588                    @Override
589                    protected void onProgressUpdate(Integer... values) {
590                        final ActivityDescription ad = descriptions.get(values[0]);
591                        if (!isCancelled()) {
592                            applyActivityDescription(ad, values[0], true);
593                        }
594                        // This is to prevent the loader thread from getting ahead
595                        // of our UI updates.
596                        mHandler.post(new Runnable() {
597                            @Override public void run() {
598                                synchronized (ad) {
599                                    ad.notifyAll();
600                                }
601                            }
602                        });
603                    }
604
605                    @Override
606                    protected Void doInBackground(Void... params) {
607                        final int origPri = Process.getThreadPriority(Process.myTid());
608                        Process.setThreadPriority(Process.THREAD_GROUP_BG_NONINTERACTIVE);
609                        long nextTime = SystemClock.uptimeMillis();
610                        for (int i=1; i<descriptions.size(); i++) {
611                            ActivityDescription ad = descriptions.get(i);
612                            loadActivityDescription(ad, i);
613                            long now = SystemClock.uptimeMillis();
614                            nextTime += 150;
615                            if (nextTime > now) {
616                                try {
617                                    Thread.sleep(nextTime-now);
618                                } catch (InterruptedException e) {
619                                }
620                            }
621                            if (isCancelled()) {
622                                break;
623                            }
624                            synchronized (ad) {
625                                publishProgress(i);
626                                try {
627                                    ad.wait(500);
628                                } catch (InterruptedException e) {
629                                }
630                            }
631                        }
632                        Process.setThreadPriority(origPri);
633                        return null;
634                    }
635                };
636                mThumbnailLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
637            }
638        } else {
639            // Immediately hide this panel
640            if (DEBUG) Log.v(TAG, "Nothing to show");
641            hide(false);
642        }
643    }
644
645    private Bitmap compositeBitmap(Bitmap background, Bitmap thumbnail) {
646        Bitmap outBitmap = background.copy(background.getConfig(), true);
647        if (thumbnail != null) {
648            Canvas canvas = new Canvas(outBitmap);
649            Paint paint = new Paint();
650            paint.setAntiAlias(true);
651            paint.setFilterBitmap(true);
652            paint.setAlpha(255);
653            canvas.drawBitmap(thumbnail, null,
654                    new RectF(0, 0, outBitmap.getWidth(), outBitmap.getHeight()), paint);
655            canvas.setBitmap(null);
656        }
657        return outBitmap;
658    }
659
660    private void updateUiElements(Configuration config) {
661        final int items = mActivityDescriptions.size();
662
663        mRecentsContainer.setVisibility(items > 0 ? View.VISIBLE : View.GONE);
664        mRecentsGlowView.setVisibility(items > 0 ? View.VISIBLE : View.GONE);
665    }
666
667    public void handleOnClick(View view) {
668        ActivityDescription ad = ((ViewHolder) view.getTag()).activityDescription;
669        final Context context = view.getContext();
670        final ActivityManager am = (ActivityManager)
671                context.getSystemService(Context.ACTIVITY_SERVICE);
672        if (ad.taskId >= 0) {
673            // This is an active task; it should just go to the foreground.
674            am.moveTaskToFront(ad.taskId, ActivityManager.MOVE_TASK_WITH_HOME);
675        } else {
676            Intent intent = ad.intent;
677            intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
678                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
679            if (DEBUG) Log.v(TAG, "Starting activity " + intent);
680            context.startActivity(intent);
681        }
682        hide(true);
683    }
684
685    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
686        handleOnClick(view);
687    }
688
689    public void handleSwipe(View view) {
690        ActivityDescription ad = ((ViewHolder) view.getTag()).activityDescription;
691        if (DEBUG) Log.v(TAG, "Jettison " + ad.getLabel());
692        mActivityDescriptions.remove(ad);
693
694        // Handled by widget containers to enable LayoutTransitions properly
695        // mListAdapter.notifyDataSetChanged();
696
697        if (mActivityDescriptions.size() == 0) {
698            hide(false);
699        }
700
701        // Currently, either direction means the same thing, so ignore direction and remove
702        // the task.
703        final ActivityManager am = (ActivityManager)
704                mContext.getSystemService(Context.ACTIVITY_SERVICE);
705        am.removeTask(ad.taskId, ActivityManager.REMOVE_TASK_KILL_PROCESS);
706    }
707
708    private void startApplicationDetailsActivity(String packageName) {
709        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
710                Uri.fromParts("package", packageName, null));
711        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
712        getContext().startActivity(intent);
713    }
714
715    public void handleLongPress(final View selectedView, final View anchorView) {
716        PopupMenu popup = new PopupMenu(mContext, anchorView == null ? selectedView : anchorView);
717        popup.getMenuInflater().inflate(R.menu.recent_popup_menu, popup.getMenu());
718        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
719            public boolean onMenuItemClick(MenuItem item) {
720                if (item.getItemId() == R.id.recent_remove_item) {
721                    mRecentsContainer.removeViewInLayout(selectedView);
722                } else if (item.getItemId() == R.id.recent_inspect_item) {
723                    ViewHolder viewHolder = (ViewHolder) selectedView.getTag();
724                    if (viewHolder != null) {
725                        final ActivityDescription ad = viewHolder.activityDescription;
726                        startApplicationDetailsActivity(ad.packageName);
727                        mBar.animateCollapse();
728                    } else {
729                        throw new IllegalStateException("Oops, no tag on view " + selectedView);
730                    }
731                } else {
732                    return false;
733                }
734                return true;
735            }
736        });
737        popup.show();
738    }
739}
740