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