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