RecentsPanelView.java revision 622a97646d316ca753c577752ac9010415e9a472
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 handleShowBackground(boolean show) {
247        if (show) {
248            mRecentsScrim.setBackgroundResource(R.drawable.status_bar_recents_background);
249        } else {
250            mRecentsScrim.setBackgroundDrawable(null);
251        }
252    }
253
254    public boolean isRecentsVisible() {
255        return getVisibility() == VISIBLE;
256    }
257
258    public void onAnimationCancel(Animator animation) {
259    }
260
261    public void onAnimationEnd(Animator animation) {
262        if (mShowing) {
263            final LayoutTransition transitioner = new LayoutTransition();
264            ((ViewGroup)mRecentsContainer).setLayoutTransition(transitioner);
265            createCustomAnimations(transitioner);
266        } else {
267            ((ViewGroup)mRecentsContainer).setLayoutTransition(null);
268        }
269    }
270
271    public void onAnimationRepeat(Animator animation) {
272    }
273
274    public void onAnimationStart(Animator animation) {
275    }
276
277
278    /**
279     * We need to be aligned at the bottom.  LinearLayout can't do this, so instead,
280     * let LinearLayout do all the hard work, and then shift everything down to the bottom.
281     */
282    @Override
283    protected void onLayout(boolean changed, int l, int t, int r, int b) {
284        super.onLayout(changed, l, t, r, b);
285        mChoreo.setPanelHeight(mRecentsContainer.getHeight());
286    }
287
288    @Override
289    public boolean dispatchHoverEvent(MotionEvent event) {
290        // Ignore hover events outside of this panel bounds since such events
291        // generate spurious accessibility events with the panel content when
292        // tapping outside of it, thus confusing the user.
293        final int x = (int) event.getX();
294        final int y = (int) event.getY();
295        if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) {
296            return super.dispatchHoverEvent(event);
297        }
298        return true;
299    }
300
301    /**
302     * Whether the panel is showing, or, if it's animating, whether it will be
303     * when the animation is done.
304     */
305    public boolean isShowing() {
306        return mShowing;
307    }
308
309    public void setBar(StatusBar bar) {
310        mBar = bar;
311    }
312
313    public RecentsPanelView(Context context, AttributeSet attrs) {
314        this(context, attrs, 0);
315    }
316
317    public RecentsPanelView(Context context, AttributeSet attrs, int defStyle) {
318        super(context, attrs, defStyle);
319
320        Resources res = context.getResources();
321        boolean xlarge = (res.getConfiguration().screenLayout
322                & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE;
323
324        mIconDpi = xlarge ? DisplayMetrics.DENSITY_HIGH : res.getDisplayMetrics().densityDpi;
325
326        int width = (int) res.getDimension(R.dimen.status_bar_recents_thumbnail_width);
327        int height = (int) res.getDimension(R.dimen.status_bar_recents_thumbnail_height);
328        int color = res.getColor(R.drawable.status_bar_recents_app_thumbnail_background);
329        mAppThumbnailBackground = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
330        Canvas c = new Canvas(mAppThumbnailBackground);
331        c.drawColor(color);
332    }
333
334    @Override
335    protected void onFinishInflate() {
336        super.onFinishInflate();
337        mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
338        mRecentsContainer = (ViewGroup) findViewById(R.id.recents_container);
339        mListAdapter = new ActivityDescriptionAdapter(mContext);
340        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 Recents[Horizontal]ScrollView");
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        if (mRecentsContainer instanceof RecentsHorizontalScrollView) {
387            ((RecentsHorizontalScrollView) mRecentsContainer).onRecentsVisibilityChanged();
388        } else if (mRecentsContainer instanceof RecentsVerticalScrollView) {
389            ((RecentsVerticalScrollView) mRecentsContainer).onRecentsVisibilityChanged();
390        } else {
391            throw new IllegalArgumentException("missing Recents[Horizontal]ScrollView");
392        }
393    }
394
395    Drawable getFullResDefaultActivityIcon() {
396        return getFullResIcon(Resources.getSystem(),
397                com.android.internal.R.mipmap.sym_def_app_icon);
398    }
399
400    Drawable getFullResIcon(Resources resources, int iconId) {
401        try {
402            return resources.getDrawableForDensity(iconId, mIconDpi);
403        } catch (Resources.NotFoundException e) {
404            return getFullResDefaultActivityIcon();
405        }
406    }
407
408    private Drawable getFullResIcon(ResolveInfo info, PackageManager packageManager) {
409        Resources resources;
410        try {
411            resources = packageManager.getResourcesForApplication(
412                    info.activityInfo.applicationInfo);
413        } catch (PackageManager.NameNotFoundException e) {
414            resources = null;
415        }
416        if (resources != null) {
417            int iconId = info.activityInfo.getIconResource();
418            if (iconId != 0) {
419                return getFullResIcon(resources, iconId);
420            }
421        }
422        return getFullResDefaultActivityIcon();
423    }
424
425    private ArrayList<ActivityDescription> getRecentTasks() {
426        ArrayList<ActivityDescription> activityDescriptions = new ArrayList<ActivityDescription>();
427        final PackageManager pm = mContext.getPackageManager();
428        final ActivityManager am = (ActivityManager)
429                mContext.getSystemService(Context.ACTIVITY_SERVICE);
430
431        final List<ActivityManager.RecentTaskInfo> recentTasks =
432                am.getRecentTasks(MAX_TASKS, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
433
434        ActivityInfo homeInfo = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
435                    .resolveActivityInfo(pm, 0);
436
437        int numTasks = recentTasks.size();
438
439        // skip the first activity - assume it's either the home screen or the current app.
440        final int first = 1;
441        for (int i = first, index = 0; i < numTasks && (index < MAX_TASKS); ++i) {
442            final ActivityManager.RecentTaskInfo recentInfo = recentTasks.get(i);
443
444            Intent intent = new Intent(recentInfo.baseIntent);
445            if (recentInfo.origActivity != null) {
446                intent.setComponent(recentInfo.origActivity);
447            }
448
449            // Skip the current home activity.
450            if (homeInfo != null
451                    && homeInfo.packageName.equals(intent.getComponent().getPackageName())
452                    && homeInfo.name.equals(intent.getComponent().getClassName())) {
453                continue;
454            }
455
456            intent.setFlags((intent.getFlags()&~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
457                    | Intent.FLAG_ACTIVITY_NEW_TASK);
458            final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
459            if (resolveInfo != null) {
460                final ActivityInfo info = resolveInfo.activityInfo;
461                final String title = info.loadLabel(pm).toString();
462                // Drawable icon = info.loadIcon(pm);
463                Drawable icon = getFullResIcon(resolveInfo, pm);
464                int id = recentInfo.id;
465                if (title != null && title.length() > 0 && icon != null) {
466                    if (DEBUG) Log.v(TAG, "creating activity desc for id=" + id + ", label=" + title);
467                    ActivityManager.TaskThumbnails thumbs = am.getTaskThumbnails(
468                            recentInfo.persistentId);
469                    ActivityDescription item = new ActivityDescription(recentInfo,
470                            resolveInfo, intent, id, index, info.packageName);
471                    activityDescriptions.add(item);
472                    ++index;
473                } else {
474                    if (DEBUG) Log.v(TAG, "SKIPPING item " + id);
475                }
476            }
477        }
478        return activityDescriptions;
479    }
480
481    ActivityDescription findActivityDescription(int id)
482    {
483        ActivityDescription desc = null;
484        for (int i = 0; i < mActivityDescriptions.size(); i++) {
485            ActivityDescription item = mActivityDescriptions.get(i);
486            if (item != null && item.taskId == id) {
487                desc = item;
488                break;
489            }
490        }
491        return desc;
492    }
493
494    void loadActivityDescription(ActivityDescription ad, int index) {
495        final ActivityManager am = (ActivityManager)
496                mContext.getSystemService(Context.ACTIVITY_SERVICE);
497        final PackageManager pm = mContext.getPackageManager();
498        ActivityManager.TaskThumbnails thumbs = am.getTaskThumbnails(
499                ad.recentTaskInfo.persistentId);
500        CharSequence label = ad.resolveInfo.activityInfo.loadLabel(pm);
501        Drawable icon = getFullResIcon(ad.resolveInfo, pm);
502        if (DEBUG) Log.v(TAG, "Loaded bitmap for #" + index + " in "
503                + ad + ": " + thumbs.mainThumbnail);
504        synchronized (ad) {
505            ad.mLabel = label;
506            ad.mIcon = icon;
507            ad.setThumbnail(thumbs != null ? thumbs.mainThumbnail : null);
508        }
509    }
510
511    void applyActivityDescription(ActivityDescription ad, int index, boolean anim) {
512        synchronized (ad) {
513            if (mRecentsContainer != null) {
514                ViewGroup container = mRecentsContainer;
515                if (container instanceof HorizontalScrollView
516                        || container instanceof ScrollView) {
517                    container = (ViewGroup)container.findViewById(
518                            R.id.recents_linear_layout);
519                }
520                // Look for a view showing this thumbnail, to update.
521                for (int i=0; i<container.getChildCount(); i++) {
522                    View v = container.getChildAt(i);
523                    if (v.getTag() instanceof ViewHolder) {
524                        ViewHolder h = (ViewHolder)v.getTag();
525                        if (h.activityDescription == ad) {
526                            if (DEBUG) Log.v(TAG, "Updatating thumbnail #" + index + " in "
527                                    + h.activityDescription
528                                    + ": " + ad.getThumbnail());
529                            h.iconView.setImageDrawable(ad.getIcon());
530                            if (anim) {
531                                h.iconView.setAnimation(AnimationUtils.loadAnimation(
532                                        mContext, R.anim.recent_appear));
533                            }
534                            h.iconView.setVisibility(View.VISIBLE);
535                            h.labelView.setText(ad.getLabel());
536                            if (anim) {
537                                h.labelView.setAnimation(AnimationUtils.loadAnimation(
538                                        mContext, R.anim.recent_appear));
539                            }
540                            h.labelView.setVisibility(View.VISIBLE);
541                            Bitmap thumbnail = ad.getThumbnail();
542                            if (thumbnail != null) {
543                                // Should remove the default image in the frame
544                                // that this now covers, to improve scrolling speed.
545                                // That can't be done until the anim is complete though.
546                                h.thumbnailViewImage.setImageBitmap(thumbnail);
547                                if (anim) {
548                                    h.thumbnailViewImage.setAnimation(AnimationUtils.loadAnimation(
549                                            mContext, R.anim.recent_appear));
550                                }
551                                h.thumbnailViewImage.setVisibility(View.VISIBLE);
552                            }
553                        }
554                    }
555                }
556            }
557        }
558    }
559
560    private void refreshApplicationList() {
561        if (mThumbnailLoader != null) {
562            mThumbnailLoader.cancel(false);
563            mThumbnailLoader = null;
564        }
565        mActivityDescriptions = getRecentTasks();
566        for (ActivityDescription ad : mActivityDescriptions) {
567            ad.setThumbnail(mAppThumbnailBackground);
568        }
569        mListAdapter.notifyDataSetInvalidated();
570        if (mActivityDescriptions.size() > 0) {
571            if (DEBUG) Log.v(TAG, "Showing " + mActivityDescriptions.size() + " apps");
572            updateUiElements(getResources().getConfiguration());
573            final ArrayList<ActivityDescription> descriptions = mActivityDescriptions;
574            loadActivityDescription(descriptions.get(0), 0);
575            applyActivityDescription(descriptions.get(0), 0, false);
576            if (descriptions.size() > 1) {
577                mThumbnailLoader = new AsyncTask<Void, Integer, Void>() {
578                    @Override
579                    protected void onProgressUpdate(Integer... values) {
580                        final ActivityDescription ad = descriptions.get(values[0]);
581                        if (!isCancelled()) {
582                            applyActivityDescription(ad, values[0], true);
583                        }
584                        // This is to prevent the loader thread from getting ahead
585                        // of our UI updates.
586                        mHandler.post(new Runnable() {
587                            @Override public void run() {
588                                synchronized (ad) {
589                                    ad.notifyAll();
590                                }
591                            }
592                        });
593                    }
594
595                    @Override
596                    protected Void doInBackground(Void... params) {
597                        final int origPri = Process.getThreadPriority(Process.myTid());
598                        Process.setThreadPriority(Process.THREAD_GROUP_BG_NONINTERACTIVE);
599                        long nextTime = SystemClock.uptimeMillis();
600                        for (int i=1; i<descriptions.size(); i++) {
601                            ActivityDescription ad = descriptions.get(i);
602                            loadActivityDescription(ad, i);
603                            long now = SystemClock.uptimeMillis();
604                            nextTime += 150;
605                            if (nextTime > now) {
606                                try {
607                                    Thread.sleep(nextTime-now);
608                                } catch (InterruptedException e) {
609                                }
610                            }
611                            if (isCancelled()) {
612                                break;
613                            }
614                            synchronized (ad) {
615                                publishProgress(i);
616                                try {
617                                    ad.wait(500);
618                                } catch (InterruptedException e) {
619                                }
620                            }
621                        }
622                        Process.setThreadPriority(origPri);
623                        return null;
624                    }
625                };
626                mThumbnailLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
627            }
628        } else {
629            // Immediately hide this panel
630            if (DEBUG) Log.v(TAG, "Nothing to show");
631            hide(false);
632        }
633    }
634
635    private Bitmap compositeBitmap(Bitmap background, Bitmap thumbnail) {
636        Bitmap outBitmap = background.copy(background.getConfig(), true);
637        if (thumbnail != null) {
638            Canvas canvas = new Canvas(outBitmap);
639            Paint paint = new Paint();
640            paint.setAntiAlias(true);
641            paint.setFilterBitmap(true);
642            paint.setAlpha(255);
643            canvas.drawBitmap(thumbnail, null,
644                    new RectF(0, 0, outBitmap.getWidth(), outBitmap.getHeight()), paint);
645            canvas.setBitmap(null);
646        }
647        return outBitmap;
648    }
649
650    private void updateUiElements(Configuration config) {
651        final int items = mActivityDescriptions.size();
652
653        mRecentsContainer.setVisibility(items > 0 ? View.VISIBLE : View.GONE);
654        mRecentsGlowView.setVisibility(items > 0 ? View.VISIBLE : View.GONE);
655    }
656
657    public void hide(boolean animate) {
658        if (!animate) {
659            setVisibility(View.GONE);
660        }
661        if (mBar != null) {
662            mBar.animateCollapse();
663        }
664    }
665
666    public void handleOnClick(View view) {
667        ActivityDescription ad = ((ViewHolder) view.getTag()).activityDescription;
668        final Context context = view.getContext();
669        final ActivityManager am = (ActivityManager)
670                context.getSystemService(Context.ACTIVITY_SERVICE);
671        if (ad.taskId >= 0) {
672            // This is an active task; it should just go to the foreground.
673            am.moveTaskToFront(ad.taskId, ActivityManager.MOVE_TASK_WITH_HOME);
674        } else {
675            Intent intent = ad.intent;
676            intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
677                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
678            if (DEBUG) Log.v(TAG, "Starting activity " + intent);
679            context.startActivity(intent);
680        }
681        hide(true);
682    }
683
684    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
685        handleOnClick(view);
686    }
687
688    public void handleSwipe(View view) {
689        ActivityDescription ad = ((ViewHolder) view.getTag()).activityDescription;
690        if (DEBUG) Log.v(TAG, "Jettison " + ad.getLabel());
691        mActivityDescriptions.remove(ad);
692
693        // Handled by widget containers to enable LayoutTransitions properly
694        // mListAdapter.notifyDataSetChanged();
695
696        if (mActivityDescriptions.size() == 0) {
697            hide(false);
698        }
699
700        // Currently, either direction means the same thing, so ignore direction and remove
701        // the task.
702        final ActivityManager am = (ActivityManager)
703                mContext.getSystemService(Context.ACTIVITY_SERVICE);
704        am.removeTask(ad.taskId, ActivityManager.REMOVE_TASK_KILL_PROCESS);
705    }
706
707    private void startApplicationDetailsActivity(String packageName) {
708        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
709                Uri.fromParts("package", packageName, null));
710        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
711        getContext().startActivity(intent);
712    }
713
714    public void handleLongPress(final View selectedView, final View anchorView) {
715        PopupMenu popup = new PopupMenu(mContext, anchorView == null ? selectedView : anchorView);
716        popup.getMenuInflater().inflate(R.menu.recent_popup_menu, popup.getMenu());
717        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
718            public boolean onMenuItemClick(MenuItem item) {
719                if (item.getItemId() == R.id.recent_remove_item) {
720                    mRecentsContainer.removeViewInLayout(selectedView);
721                } else if (item.getItemId() == R.id.recent_inspect_item) {
722                    ViewHolder viewHolder = (ViewHolder) selectedView.getTag();
723                    if (viewHolder != null) {
724                        final ActivityDescription ad = viewHolder.activityDescription;
725                        startApplicationDetailsActivity(ad.packageName);
726                        mBar.animateCollapse();
727                    } else {
728                        throw new IllegalStateException("Oops, no tag on view " + selectedView);
729                    }
730                } else {
731                    return false;
732                }
733                return true;
734            }
735        });
736        popup.show();
737    }
738}
739