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