AppsCustomizePagedView.java revision 68f681bc7a10fc014ae0864c6e2db465ce4c30df
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.launcher2;
18
19import android.animation.AnimatorSet;
20import android.animation.ObjectAnimator;
21import android.animation.ValueAnimator;
22import android.appwidget.AppWidgetHostView;
23import android.appwidget.AppWidgetManager;
24import android.appwidget.AppWidgetProviderInfo;
25import android.content.ComponentName;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
30import android.content.res.Configuration;
31import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.graphics.Bitmap;
34import android.graphics.Bitmap.Config;
35import android.graphics.Canvas;
36import android.graphics.ColorMatrix;
37import android.graphics.ColorMatrixColorFilter;
38import android.graphics.Insets;
39import android.graphics.MaskFilter;
40import android.graphics.Matrix;
41import android.graphics.Paint;
42import android.graphics.PorterDuff;
43import android.graphics.Rect;
44import android.graphics.RectF;
45import android.graphics.Shader;
46import android.graphics.TableMaskFilter;
47import android.graphics.drawable.BitmapDrawable;
48import android.graphics.drawable.Drawable;
49import android.os.AsyncTask;
50import android.os.Process;
51import android.util.AttributeSet;
52import android.util.Log;
53import android.view.Gravity;
54import android.view.KeyEvent;
55import android.view.LayoutInflater;
56import android.view.MotionEvent;
57import android.view.View;
58import android.view.ViewGroup;
59import android.view.animation.AccelerateInterpolator;
60import android.view.animation.DecelerateInterpolator;
61import android.widget.GridLayout;
62import android.widget.ImageView;
63import android.widget.LinearLayout;
64import android.widget.Toast;
65
66import com.android.launcher.R;
67import com.android.launcher2.DropTarget.DragObject;
68
69import java.util.ArrayList;
70import java.util.Collections;
71import java.util.Iterator;
72import java.util.List;
73import java.lang.ref.WeakReference;
74
75/**
76 * A simple callback interface which also provides the results of the task.
77 */
78interface AsyncTaskCallback {
79    void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
80}
81
82/**
83 * The data needed to perform either of the custom AsyncTasks.
84 */
85class AsyncTaskPageData {
86    enum Type {
87        LoadWidgetPreviewData
88    }
89
90    AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
91            AsyncTaskCallback postR) {
92        page = p;
93        items = l;
94        sourceImages = si;
95        generatedImages = new ArrayList<Bitmap>();
96        maxImageWidth = maxImageHeight = -1;
97        doInBackgroundCallback = bgR;
98        postExecuteCallback = postR;
99    }
100    AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR,
101            AsyncTaskCallback postR) {
102        page = p;
103        items = l;
104        generatedImages = new ArrayList<Bitmap>();
105        maxImageWidth = cw;
106        maxImageHeight = ch;
107        doInBackgroundCallback = bgR;
108        postExecuteCallback = postR;
109    }
110    void cleanup(boolean cancelled) {
111        // Clean up any references to source/generated bitmaps
112        if (sourceImages != null) {
113            if (cancelled) {
114                for (Bitmap b : sourceImages) {
115                    b.recycle();
116                }
117            }
118            sourceImages.clear();
119        }
120        if (generatedImages != null) {
121            if (cancelled) {
122                for (Bitmap b : generatedImages) {
123                    b.recycle();
124                }
125            }
126            generatedImages.clear();
127        }
128    }
129    int page;
130    ArrayList<Object> items;
131    ArrayList<Bitmap> sourceImages;
132    ArrayList<Bitmap> generatedImages;
133    int maxImageWidth;
134    int maxImageHeight;
135    AsyncTaskCallback doInBackgroundCallback;
136    AsyncTaskCallback postExecuteCallback;
137}
138
139/**
140 * A generic template for an async task used in AppsCustomize.
141 */
142class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
143    AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) {
144        page = p;
145        threadPriority = Process.THREAD_PRIORITY_DEFAULT;
146        dataType = ty;
147    }
148    @Override
149    protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
150        if (params.length != 1) return null;
151        // Load each of the widget previews in the background
152        params[0].doInBackgroundCallback.run(this, params[0]);
153        return params[0];
154    }
155    @Override
156    protected void onPostExecute(AsyncTaskPageData result) {
157        // All the widget previews are loaded, so we can just callback to inflate the page
158        result.postExecuteCallback.run(this, result);
159    }
160
161    void setThreadPriority(int p) {
162        threadPriority = p;
163    }
164    void syncThreadPriority() {
165        Process.setThreadPriority(threadPriority);
166    }
167
168    // The page that this async task is associated with
169    AsyncTaskPageData.Type dataType;
170    int page;
171    int threadPriority;
172}
173
174abstract class WeakReferenceThreadLocal<T> {
175    private ThreadLocal<WeakReference<T>> mThreadLocal;
176    public WeakReferenceThreadLocal() {
177        mThreadLocal = new ThreadLocal<WeakReference<T>>();
178    }
179
180    abstract T initialValue();
181
182    public void set(T t) {
183        mThreadLocal.set(new WeakReference<T>(t));
184    }
185
186    public T get() {
187        WeakReference<T> reference = mThreadLocal.get();
188        T obj;
189        if (reference == null) {
190            obj = initialValue();
191            mThreadLocal.set(new WeakReference<T>(obj));
192            return obj;
193        } else {
194            obj = reference.get();
195            if (obj == null) {
196                obj = initialValue();
197                mThreadLocal.set(new WeakReference<T>(obj));
198            }
199            return obj;
200        }
201    }
202}
203
204class CanvasCache extends WeakReferenceThreadLocal<Canvas> {
205    @Override
206    protected Canvas initialValue() {
207        return new Canvas();
208    }
209}
210
211class PaintCache extends WeakReferenceThreadLocal<Paint> {
212    @Override
213    protected Paint initialValue() {
214        return null;
215    }
216}
217
218class BitmapCache extends WeakReferenceThreadLocal<Bitmap> {
219    @Override
220    protected Bitmap initialValue() {
221        return null;
222    }
223}
224
225class RectCache extends WeakReferenceThreadLocal<Rect> {
226    @Override
227    protected Rect initialValue() {
228        return new Rect();
229    }
230}
231
232/**
233 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
234 */
235public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
236        AllAppsView, View.OnClickListener, View.OnKeyListener, DragSource,
237        PagedViewIcon.PressedCallback, PagedViewWidget.ShortPressListener,
238        LauncherTransitionable {
239    static final String TAG = "AppsCustomizePagedView";
240
241    /**
242     * The different content types that this paged view can show.
243     */
244    public enum ContentType {
245        Applications,
246        Widgets
247    }
248
249    // Refs
250    private Launcher mLauncher;
251    private DragController mDragController;
252    private final LayoutInflater mLayoutInflater;
253    private final PackageManager mPackageManager;
254
255    // Save and Restore
256    private int mSaveInstanceStateItemIndex = -1;
257    private PagedViewIcon mPressedIcon;
258
259    // Content
260    private ArrayList<ApplicationInfo> mApps;
261    private ArrayList<Object> mWidgets;
262
263    // Cling
264    private boolean mHasShownAllAppsCling;
265    private int mClingFocusedX;
266    private int mClingFocusedY;
267
268    // Caching
269    private Canvas mCanvas;
270    private Drawable mDefaultWidgetBackground;
271    private IconCache mIconCache;
272
273    // Dimens
274    private int mContentWidth;
275    private int mAppIconSize;
276    private int mMaxAppCellCountX, mMaxAppCellCountY;
277    private int mWidgetCountX, mWidgetCountY;
278    private int mWidgetWidthGap, mWidgetHeightGap;
279    private final int mWidgetPreviewIconPaddedDimension;
280    private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
281    private PagedViewCellLayout mWidgetSpacingLayout;
282    private int mNumAppsPages;
283    private int mNumWidgetPages;
284
285    // Relating to the scroll and overscroll effects
286    Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f);
287    private static float CAMERA_DISTANCE = 6500;
288    private static float TRANSITION_SCALE_FACTOR = 0.74f;
289    private static float TRANSITION_PIVOT = 0.65f;
290    private static float TRANSITION_MAX_ROTATION = 22;
291    private static final boolean PERFORM_OVERSCROLL_ROTATION = true;
292    private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f);
293    private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4);
294
295    // Previews & outlines
296    ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
297    private static final int sPageSleepDelay = 200;
298
299    private Runnable mInflateWidgetRunnable = null;
300    private Runnable mBindWidgetRunnable = null;
301    static final int WIDGET_NO_CLEANUP_REQUIRED = -1;
302    static final int WIDGET_BOUND = 0;
303    static final int WIDGET_INFLATED = 1;
304    int mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
305    int mWidgetLoadingId = -1;
306    PendingAddWidgetInfo mCreateWidgetInfo = null;
307    private boolean mDraggingWidget = false;
308
309    // Deferral of loading widget previews during launcher transitions
310    private boolean mInTransition;
311    private ArrayList<AsyncTaskPageData> mDeferredSyncWidgetPageItems =
312        new ArrayList<AsyncTaskPageData>();
313
314    // Used for drawing shortcut previews
315    BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
316    PaintCache mCachedShortcutPreviewPaint = new PaintCache();
317    CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
318
319    // Used for drawing widget previews
320    CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
321    RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
322    RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
323    PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
324
325    public AppsCustomizePagedView(Context context, AttributeSet attrs) {
326        super(context, attrs);
327        mLayoutInflater = LayoutInflater.from(context);
328        mPackageManager = context.getPackageManager();
329        mApps = new ArrayList<ApplicationInfo>();
330        mWidgets = new ArrayList<Object>();
331        mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
332        mCanvas = new Canvas();
333        mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
334
335        // Save the default widget preview background
336        Resources resources = context.getResources();
337        mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo);
338        mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
339
340        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
341        mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1);
342        mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1);
343        mWidgetWidthGap =
344            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
345        mWidgetHeightGap =
346            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
347        mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
348        mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
349        mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0);
350        mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0);
351        a.recycle();
352        mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
353
354        // The padding on the non-matched dimension for the default widget preview icons
355        // (top + bottom)
356        mWidgetPreviewIconPaddedDimension =
357            (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage)));
358        mFadeInAdjacentScreens = false;
359
360        // Unless otherwise specified this view is important for accessibility.
361        if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
362            setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
363        }
364    }
365
366    @Override
367    protected void init() {
368        super.init();
369        mCenterPagesVertically = false;
370
371        Context context = getContext();
372        Resources r = context.getResources();
373        setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
374    }
375
376    @Override
377    protected void onUnhandledTap(MotionEvent ev) {
378        if (LauncherApplication.isScreenLarge()) {
379            // Dismiss AppsCustomize if we tap
380            mLauncher.showWorkspace(true);
381        }
382    }
383
384    /** Returns the item index of the center item on this page so that we can restore to this
385     *  item index when we rotate. */
386    private int getMiddleComponentIndexOnCurrentPage() {
387        int i = -1;
388        if (getPageCount() > 0) {
389            int currentPage = getCurrentPage();
390            if (currentPage < mNumAppsPages) {
391                PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage);
392                PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout();
393                int numItemsPerPage = mCellCountX * mCellCountY;
394                int childCount = childrenLayout.getChildCount();
395                if (childCount > 0) {
396                    i = (currentPage * numItemsPerPage) + (childCount / 2);
397                }
398            } else {
399                int numApps = mApps.size();
400                PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage);
401                int numItemsPerPage = mWidgetCountX * mWidgetCountY;
402                int childCount = layout.getChildCount();
403                if (childCount > 0) {
404                    i = numApps +
405                        ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2);
406                }
407            }
408        }
409        return i;
410    }
411
412    /** Get the index of the item to restore to if we need to restore the current page. */
413    int getSaveInstanceStateIndex() {
414        if (mSaveInstanceStateItemIndex == -1) {
415            mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage();
416        }
417        return mSaveInstanceStateItemIndex;
418    }
419
420    /** Returns the page in the current orientation which is expected to contain the specified
421     *  item index. */
422    int getPageForComponent(int index) {
423        if (index < 0) return 0;
424
425        if (index < mApps.size()) {
426            int numItemsPerPage = mCellCountX * mCellCountY;
427            return (index / numItemsPerPage);
428        } else {
429            int numItemsPerPage = mWidgetCountX * mWidgetCountY;
430            return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage);
431        }
432    }
433
434    /**
435     * This differs from isDataReady as this is the test done if isDataReady is not set.
436     */
437    private boolean testDataReady() {
438        // We only do this test once, and we default to the Applications page, so we only really
439        // have to wait for there to be apps.
440        // TODO: What if one of them is validly empty
441        return !mApps.isEmpty() && !mWidgets.isEmpty();
442    }
443
444    /** Restores the page for an item at the specified index */
445    void restorePageForIndex(int index) {
446        if (index < 0) return;
447        mSaveInstanceStateItemIndex = index;
448    }
449
450    private void updatePageCounts() {
451        mNumWidgetPages = (int) Math.ceil(mWidgets.size() /
452                (float) (mWidgetCountX * mWidgetCountY));
453        mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
454    }
455
456    protected void onDataReady(int width, int height) {
457        // Note that we transpose the counts in portrait so that we get a similar layout
458        boolean isLandscape = getResources().getConfiguration().orientation ==
459            Configuration.ORIENTATION_LANDSCAPE;
460        int maxCellCountX = Integer.MAX_VALUE;
461        int maxCellCountY = Integer.MAX_VALUE;
462        if (LauncherApplication.isScreenLarge()) {
463            maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
464                LauncherModel.getCellCountY());
465            maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
466                LauncherModel.getCellCountX());
467        }
468        if (mMaxAppCellCountX > -1) {
469            maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX);
470        }
471        if (mMaxAppCellCountY > -1) {
472            maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY);
473        }
474
475        // Now that the data is ready, we can calculate the content width, the number of cells to
476        // use for each page
477        mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
478        mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
479                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
480        mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
481        mCellCountX = mWidgetSpacingLayout.getCellCountX();
482        mCellCountY = mWidgetSpacingLayout.getCellCountY();
483        updatePageCounts();
484
485        // Force a measure to update recalculate the gaps
486        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
487        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
488        mWidgetSpacingLayout.measure(widthSpec, heightSpec);
489        mContentWidth = mWidgetSpacingLayout.getContentWidth();
490
491        AppsCustomizeTabHost host = (AppsCustomizeTabHost) getTabHost();
492        final boolean hostIsTransitioning = host.isTransitioning();
493
494        // Restore the page
495        int page = getPageForComponent(mSaveInstanceStateItemIndex);
496        invalidatePageData(Math.max(0, page), hostIsTransitioning);
497
498        // Show All Apps cling if we are finished transitioning, otherwise, we will try again when
499        // the transition completes in AppsCustomizeTabHost (otherwise the wrong offsets will be
500        // returned while animating)
501        if (!hostIsTransitioning) {
502            post(new Runnable() {
503                @Override
504                public void run() {
505                    showAllAppsCling();
506                }
507            });
508        }
509    }
510
511    void showAllAppsCling() {
512        if (!mHasShownAllAppsCling && isDataReady() && testDataReady()) {
513            mHasShownAllAppsCling = true;
514            // Calculate the position for the cling punch through
515            int[] offset = new int[2];
516            int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY);
517            mLauncher.getDragLayer().getLocationInDragLayer(this, offset);
518            // PagedViews are centered horizontally but top aligned
519            pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 +
520                    offset[0];
521            pos[1] += offset[1];
522            mLauncher.showFirstRunAllAppsCling(pos);
523        }
524    }
525
526    @Override
527    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
528        int width = MeasureSpec.getSize(widthMeasureSpec);
529        int height = MeasureSpec.getSize(heightMeasureSpec);
530        if (!isDataReady()) {
531            if (testDataReady()) {
532                setDataIsReady();
533                setMeasuredDimension(width, height);
534                onDataReady(width, height);
535            }
536        }
537
538        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
539    }
540
541    public void onPackagesUpdated() {
542        // TODO: this isn't ideal, but we actually need to delay here. This call is triggered
543        // by a broadcast receiver, and in order for it to work correctly, we need to know that
544        // the AppWidgetService has already received and processed the same broadcast. Since there
545        // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally,
546        // we should have a more precise way of ensuring the AppWidgetService is up to date.
547        postDelayed(new Runnable() {
548           public void run() {
549               updatePackages();
550           }
551        }, 500);
552    }
553
554    public void updatePackages() {
555        // Get the list of widgets and shortcuts
556        boolean wasEmpty = mWidgets.isEmpty();
557        mWidgets.clear();
558        List<AppWidgetProviderInfo> widgets =
559            AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
560        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
561        List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
562        for (AppWidgetProviderInfo widget : widgets) {
563            if (widget.minWidth > 0 && widget.minHeight > 0) {
564                // Ensure that all widgets we show can be added on a workspace of this size
565                int[] spanXY = Launcher.getSpanForWidget(mLauncher, widget);
566                int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, widget);
567                int minSpanX = Math.min(spanXY[0], minSpanXY[0]);
568                int minSpanY = Math.min(spanXY[1], minSpanXY[1]);
569                if (minSpanX <= LauncherModel.getCellCountX() &&
570                        minSpanY <= LauncherModel.getCellCountY()) {
571                    mWidgets.add(widget);
572                }
573            } else {
574                Log.e(TAG, "Widget " + widget.provider + " has invalid dimensions (" +
575                        widget.minWidth + ", " + widget.minHeight + ")");
576            }
577        }
578        mWidgets.addAll(shortcuts);
579        Collections.sort(mWidgets,
580                new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
581        updatePageCounts();
582
583        if (wasEmpty) {
584            // The next layout pass will trigger data-ready if both widgets and apps are set, so request
585            // a layout to do this test and invalidate the page data when ready.
586            if (testDataReady()) requestLayout();
587        } else {
588            cancelAllTasks();
589            invalidatePageData();
590        }
591    }
592
593    @Override
594    public void onClick(View v) {
595        // When we have exited all apps or are in transition, disregard clicks
596        if (!mLauncher.isAllAppsCustomizeOpen() ||
597                mLauncher.getWorkspace().isSwitchingState()) return;
598
599        if (v instanceof PagedViewIcon) {
600            // Animate some feedback to the click
601            final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
602
603            // Lock the drawable state to pressed until we return to Launcher
604            if (mPressedIcon != null) {
605                mPressedIcon.lockDrawableState();
606            }
607
608            // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
609            // to be consistent.  So re-enable the flag here, and we will re-disable it as necessary
610            // when Launcher resumes and we are still in AllApps.
611            mLauncher.updateWallpaperVisibility(true);
612            mLauncher.startActivitySafely(v, appInfo.intent, appInfo);
613
614        } else if (v instanceof PagedViewWidget) {
615            // Let the user know that they have to long press to add a widget
616            Toast.makeText(getContext(), R.string.long_press_widget_to_add,
617                    Toast.LENGTH_SHORT).show();
618
619            // Create a little animation to show that the widget can move
620            float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
621            final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
622            AnimatorSet bounce = new AnimatorSet();
623            ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
624            tyuAnim.setDuration(125);
625            ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
626            tydAnim.setDuration(100);
627            bounce.play(tyuAnim).before(tydAnim);
628            bounce.setInterpolator(new AccelerateInterpolator());
629            bounce.start();
630        }
631    }
632
633    public boolean onKey(View v, int keyCode, KeyEvent event) {
634        return FocusHelper.handleAppsCustomizeKeyEvent(v,  keyCode, event);
635    }
636
637    /*
638     * PagedViewWithDraggableItems implementation
639     */
640    @Override
641    protected void determineDraggingStart(android.view.MotionEvent ev) {
642        // Disable dragging by pulling an app down for now.
643    }
644
645    private void beginDraggingApplication(View v) {
646        mLauncher.getWorkspace().onDragStartedWithItem(v);
647        mLauncher.getWorkspace().beginDragShared(v, this);
648    }
649
650    private void preloadWidget(final PendingAddWidgetInfo info) {
651        Log.d(TAG, "6557954 Preload widget: " + info.info);
652        final AppWidgetProviderInfo pInfo = info.info;
653        if (pInfo.configure != null) {
654            return;
655        }
656
657        mBindWidgetRunnable = new Runnable() {
658            @Override
659            public void run() {
660                Log.d(TAG, "    6557954 Preload, bind widget: " + info.info);
661                mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId();
662                if (AppWidgetManager.getInstance(mLauncher)
663                            .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) {
664                    mWidgetCleanupState = WIDGET_BOUND;
665                }
666            }
667        };
668        post(mBindWidgetRunnable);
669
670        mInflateWidgetRunnable = new Runnable() {
671            @Override
672            public void run() {
673                AppWidgetHostView hostView = mLauncher.
674                        getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo);
675                info.boundWidget = hostView;
676                Log.d(TAG, "    6557954 Preload, inflate widget: " + info.info);
677                mWidgetCleanupState = WIDGET_INFLATED;
678                hostView.setVisibility(INVISIBLE);
679                int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX,
680                        info.spanY, info, false);
681
682                // We want the first widget layout to be the correct size. This will be important
683                // for width size reporting to the AppWidgetManager.
684                DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0],
685                        unScaledSize[1]);
686                lp.x = lp.y = 0;
687                lp.customPosition = true;
688                hostView.setLayoutParams(lp);
689                mLauncher.getDragLayer().addView(hostView);
690            }
691        };
692        post(mInflateWidgetRunnable);
693    }
694
695    @Override
696    public void onShortPress(View v) {
697        // We are anticipating a long press, and we use this time to load bind and instantiate
698        // the widget. This will need to be cleaned up if it turns out no long press occurs.
699        if (mCreateWidgetInfo != null) {
700            // Just in case the cleanup process wasn't properly executed. This shouldn't happen.
701            Log.d(TAG, "**** 6557954 Previous shortpress not cleaned up, cleaning up now: " + mCreateWidgetInfo.info);
702            cleanupWidgetPreloading(false);
703        }
704        mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag());
705        Log.d(TAG, "6557954 Short press triggered for view: " + v + ", widget info: " + mCreateWidgetInfo.info);
706        preloadWidget(mCreateWidgetInfo);
707    }
708
709    private void cleanupWidgetPreloading(boolean widgetWasAdded) {
710        Log.d(TAG, "6557954 Cleaning up widget, was added: " + widgetWasAdded);
711        if (mCreateWidgetInfo != null) {
712            Log.d(TAG, "    6557954 Cleaning up widget, widget info: " + mCreateWidgetInfo.info);
713        }
714
715        if (!widgetWasAdded) {
716            // If the widget was not added, we may need to do further cleanup.
717            PendingAddWidgetInfo info = mCreateWidgetInfo;
718            mCreateWidgetInfo = null;
719            // First step was to allocate a widget id, revert that.
720            if ((mWidgetCleanupState == WIDGET_BOUND || mWidgetCleanupState == WIDGET_INFLATED) &&
721                    mWidgetLoadingId != -1) {
722                Log.d(TAG, "    6557954 Cleaning up widget, delete widget id");
723                mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
724            }
725            if (mWidgetCleanupState == WIDGET_BOUND) {
726                // We never actually inflated the widget, so remove the callback to do so.
727                Log.d(TAG, "    6557954 Cleaning up widget, remove callbacks");
728                removeCallbacks(mInflateWidgetRunnable);
729            } else if (mWidgetCleanupState == WIDGET_INFLATED) {
730                // The widget was inflated and added to the DragLayer -- remove it.
731                Log.d(TAG, "    6557954 Cleaning up widget, remove inflated widget from draglayer");
732                AppWidgetHostView widget = info.boundWidget;
733                mLauncher.getDragLayer().removeView(widget);
734            }
735        }
736        mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
737        mWidgetLoadingId = -1;
738        mCreateWidgetInfo = null;
739        PagedViewWidget.resetShortPressTarget();
740    }
741
742    @Override
743    public void cleanUpShortPress(View v) {
744        Log.d(TAG, "6557954 Cleanup shortpress");
745        if (!mDraggingWidget) {
746            Log.d(TAG, "    6557954 Cleanup shortpress, cleanup cleanup preloading");
747            cleanupWidgetPreloading(false);
748        }
749    }
750
751    private boolean beginDraggingWidget(View v) {
752        mDraggingWidget = true;
753        // Get the widget preview as the drag representation
754        ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
755        PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
756
757        if (createItemInfo instanceof PendingAddWidgetInfo) {
758            PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
759            Log.d(TAG, "6557954 Begin dragging widget, view: " + v + ", widget info: " + createWidgetInfo.info);
760        }
761
762        // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
763        // we abort the drag.
764        if (image.getDrawable() == null) {
765            Log.d(TAG, "    6557954 Begin dragging widget, abort, no drawable set");
766            mDraggingWidget = false;
767            return false;
768        }
769
770        // Compose the drag image
771        Bitmap preview;
772        Bitmap outline;
773        float scale = 1f;
774        if (createItemInfo instanceof PendingAddWidgetInfo) {
775            // This can happen in some weird cases involving multi-touch. We can't start dragging
776            // the widget if this is null, so we break out.
777            if (mCreateWidgetInfo == null) {
778                return false;
779            }
780
781            PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
782            createItemInfo = createWidgetInfo;
783            int spanX = createItemInfo.spanX;
784            int spanY = createItemInfo.spanY;
785            int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY,
786                    createWidgetInfo, true);
787
788            FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
789            float minScale = 1.25f;
790            int maxWidth, maxHeight;
791            maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
792            maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
793            preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
794                    createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight);
795
796            // Determine the image view drawable scale relative to the preview
797            float[] mv = new float[9];
798            Matrix m = new Matrix();
799            m.setRectToRect(
800                    new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
801                    new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
802                            (float) previewDrawable.getIntrinsicHeight()),
803                    Matrix.ScaleToFit.START);
804            m.getValues(mv);
805            scale = (float) mv[0];
806        } else {
807            PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
808            Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
809            preview = Bitmap.createBitmap(icon.getIntrinsicWidth(),
810                    icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
811
812            mCanvas.setBitmap(preview);
813            mCanvas.save();
814            renderDrawableToBitmap(icon, preview, 0, 0,
815                    icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
816            mCanvas.restore();
817            mCanvas.setBitmap(null);
818            createItemInfo.spanX = createItemInfo.spanY = 1;
819        }
820
821        // We use a custom alpha clip table for the default widget previews
822        Paint alphaClipPaint = null;
823        if (createItemInfo instanceof PendingAddWidgetInfo) {
824            if (((PendingAddWidgetInfo) createItemInfo).previewImage != 0) {
825                MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255);
826                alphaClipPaint = new Paint();
827                alphaClipPaint.setMaskFilter(alphaClipTable);
828            }
829        }
830
831        // Save the preview for the outline generation, then dim the preview
832        outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(),
833                false);
834
835        // Start the drag
836        alphaClipPaint = null;
837        mLauncher.lockScreenOrientation();
838        mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, alphaClipPaint);
839        mDragController.startDrag(image, preview, this, createItemInfo,
840                DragController.DRAG_ACTION_COPY, null, scale);
841        outline.recycle();
842        preview.recycle();
843        return true;
844    }
845
846    @Override
847    protected boolean beginDragging(final View v) {
848        if (!super.beginDragging(v)) return false;
849
850        if (v instanceof PagedViewIcon) {
851            beginDraggingApplication(v);
852        } else if (v instanceof PagedViewWidget) {
853            if (!beginDraggingWidget(v)) {
854                return false;
855            }
856        }
857
858        // We delay entering spring-loaded mode slightly to make sure the UI
859        // thready is free of any work.
860        postDelayed(new Runnable() {
861            @Override
862            public void run() {
863                // We don't enter spring-loaded mode if the drag has been cancelled
864                if (mLauncher.getDragController().isDragging()) {
865                    // Dismiss the cling
866                    mLauncher.dismissAllAppsCling(null);
867
868                    // Reset the alpha on the dragged icon before we drag
869                    resetDrawableState();
870
871                    // Go into spring loaded mode (must happen before we startDrag())
872                    mLauncher.enterSpringLoadedDragMode();
873                }
874            }
875        }, 150);
876
877        return true;
878    }
879
880    /**
881     * Clean up after dragging.
882     *
883     * @param target where the item was dragged to (can be null if the item was flung)
884     */
885    private void endDragging(View target, boolean isFlingToDelete, boolean success) {
886        if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() &&
887                !(target instanceof DeleteDropTarget))) {
888            // Exit spring loaded mode if we have not successfully dropped or have not handled the
889            // drop in Workspace
890            mLauncher.exitSpringLoadedDragMode();
891        }
892        mLauncher.unlockScreenOrientation(false);
893    }
894
895    @Override
896    public View getContent() {
897        return null;
898    }
899
900    @Override
901    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
902        mInTransition = true;
903        if (toWorkspace) {
904            cancelAllTasks();
905        }
906    }
907
908    @Override
909    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
910    }
911
912    @Override
913    public void onLauncherTransitionStep(Launcher l, float t) {
914    }
915
916    @Override
917    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
918        mInTransition = false;
919        for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
920            onSyncWidgetPageItems(d);
921        }
922        mDeferredSyncWidgetPageItems.clear();
923        mForceDrawAllChildrenNextFrame = !toWorkspace;
924    }
925
926    @Override
927    public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
928            boolean success) {
929        // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
930        if (isFlingToDelete) return;
931
932        endDragging(target, false, success);
933
934        // Display an error message if the drag failed due to there not being enough space on the
935        // target layout we were dropping on.
936        if (!success) {
937            boolean showOutOfSpaceMessage = false;
938            if (target instanceof Workspace) {
939                int currentScreen = mLauncher.getCurrentWorkspaceScreen();
940                Workspace workspace = (Workspace) target;
941                CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
942                ItemInfo itemInfo = (ItemInfo) d.dragInfo;
943                if (layout != null) {
944                    layout.calculateSpans(itemInfo);
945                    showOutOfSpaceMessage =
946                            !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
947                }
948            }
949            if (showOutOfSpaceMessage) {
950                mLauncher.showOutOfSpaceMessage(false);
951            }
952
953            d.deferDragViewCleanupPostAnimation = false;
954        }
955        cleanupWidgetPreloading(success);
956        mDraggingWidget = false;
957    }
958
959    @Override
960    public void onFlingToDeleteCompleted() {
961        // We just dismiss the drag when we fling, so cleanup here
962        endDragging(null, true, true);
963        cleanupWidgetPreloading(false);
964        mDraggingWidget = false;
965    }
966
967    @Override
968    public boolean supportsFlingToDelete() {
969        return true;
970    }
971
972    @Override
973    protected void onDetachedFromWindow() {
974        super.onDetachedFromWindow();
975        cancelAllTasks();
976    }
977
978    public void clearAllWidgetPages() {
979        cancelAllTasks();
980        int count = getChildCount();
981        for (int i = 0; i < count; i++) {
982            View v = getPageAt(i);
983            if (v instanceof PagedViewGridLayout) {
984                ((PagedViewGridLayout) v).removeAllViewsOnPage();
985                mDirtyPageContent.set(i, true);
986            }
987        }
988    }
989
990    private void cancelAllTasks() {
991        // Clean up all the async tasks
992        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
993        while (iter.hasNext()) {
994            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
995            task.cancel(false);
996            iter.remove();
997            mDirtyPageContent.set(task.page, true);
998
999            // We've already preallocated the views for the data to load into, so clear them as well
1000            View v = getPageAt(task.page);
1001            if (v instanceof PagedViewGridLayout) {
1002                ((PagedViewGridLayout) v).removeAllViewsOnPage();
1003            }
1004        }
1005        mDeferredSyncWidgetPageItems.clear();
1006    }
1007
1008    public void setContentType(ContentType type) {
1009        if (type == ContentType.Widgets) {
1010            invalidatePageData(mNumAppsPages, true);
1011        } else if (type == ContentType.Applications) {
1012            invalidatePageData(0, true);
1013        }
1014    }
1015
1016    protected void snapToPage(int whichPage, int delta, int duration) {
1017        super.snapToPage(whichPage, delta, duration);
1018        updateCurrentTab(whichPage);
1019
1020        // Update the thread priorities given the direction lookahead
1021        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1022        while (iter.hasNext()) {
1023            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1024            int pageIndex = task.page;
1025            if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
1026                (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
1027                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1028            } else {
1029                task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
1030            }
1031        }
1032    }
1033
1034    private void updateCurrentTab(int currentPage) {
1035        AppsCustomizeTabHost tabHost = getTabHost();
1036        if (tabHost != null) {
1037            String tag = tabHost.getCurrentTabTag();
1038            if (tag != null) {
1039                if (currentPage >= mNumAppsPages &&
1040                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
1041                    tabHost.setCurrentTabFromContent(ContentType.Widgets);
1042                } else if (currentPage < mNumAppsPages &&
1043                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1044                    tabHost.setCurrentTabFromContent(ContentType.Applications);
1045                }
1046            }
1047        }
1048    }
1049
1050    /*
1051     * Apps PagedView implementation
1052     */
1053    private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
1054        int childCount = layout.getChildCount();
1055        for (int i = 0; i < childCount; ++i) {
1056            layout.getChildAt(i).setVisibility(visibility);
1057        }
1058    }
1059    private void setupPage(PagedViewCellLayout layout) {
1060        layout.setCellCount(mCellCountX, mCellCountY);
1061        layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
1062        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1063                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1064
1065        // Note: We force a measure here to get around the fact that when we do layout calculations
1066        // immediately after syncing, we don't have a proper width.  That said, we already know the
1067        // expected page width, so we can actually optimize by hiding all the TextView-based
1068        // children that are expensive to measure, and let that happen naturally later.
1069        setVisibilityOnChildren(layout, View.GONE);
1070        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1071        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
1072        layout.setMinimumWidth(getPageContentWidth());
1073        layout.measure(widthSpec, heightSpec);
1074        setVisibilityOnChildren(layout, View.VISIBLE);
1075    }
1076
1077    public void syncAppsPageItems(int page, boolean immediate) {
1078        // ensure that we have the right number of items on the pages
1079        int numCells = mCellCountX * mCellCountY;
1080        int startIndex = page * numCells;
1081        int endIndex = Math.min(startIndex + numCells, mApps.size());
1082        PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
1083
1084        layout.removeAllViewsOnPage();
1085        ArrayList<Object> items = new ArrayList<Object>();
1086        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
1087        for (int i = startIndex; i < endIndex; ++i) {
1088            ApplicationInfo info = mApps.get(i);
1089            PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
1090                    R.layout.apps_customize_application, layout, false);
1091            icon.applyFromApplicationInfo(info, true, this);
1092            icon.setOnClickListener(this);
1093            icon.setOnLongClickListener(this);
1094            icon.setOnTouchListener(this);
1095            icon.setOnKeyListener(this);
1096
1097            int index = i - startIndex;
1098            int x = index % mCellCountX;
1099            int y = index / mCellCountX;
1100            layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
1101
1102            items.add(info);
1103            images.add(info.iconBitmap);
1104        }
1105
1106        layout.createHardwareLayers();
1107    }
1108
1109    /**
1110     * A helper to return the priority for loading of the specified widget page.
1111     */
1112    private int getWidgetPageLoadPriority(int page) {
1113        // If we are snapping to another page, use that index as the target page index
1114        int toPage = mCurrentPage;
1115        if (mNextPage > -1) {
1116            toPage = mNextPage;
1117        }
1118
1119        // We use the distance from the target page as an initial guess of priority, but if there
1120        // are no pages of higher priority than the page specified, then bump up the priority of
1121        // the specified page.
1122        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1123        int minPageDiff = Integer.MAX_VALUE;
1124        while (iter.hasNext()) {
1125            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1126            minPageDiff = Math.abs(task.page - toPage);
1127        }
1128
1129        int rawPageDiff = Math.abs(page - toPage);
1130        return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
1131    }
1132    /**
1133     * Return the appropriate thread priority for loading for a given page (we give the current
1134     * page much higher priority)
1135     */
1136    private int getThreadPriorityForPage(int page) {
1137        // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
1138        int pageDiff = getWidgetPageLoadPriority(page);
1139        if (pageDiff <= 0) {
1140            return Process.THREAD_PRIORITY_LESS_FAVORABLE;
1141        } else if (pageDiff <= 1) {
1142            return Process.THREAD_PRIORITY_LOWEST;
1143        } else {
1144            return Process.THREAD_PRIORITY_LOWEST;
1145        }
1146    }
1147    private int getSleepForPage(int page) {
1148        int pageDiff = getWidgetPageLoadPriority(page);
1149        return Math.max(0, pageDiff * sPageSleepDelay);
1150    }
1151    /**
1152     * Creates and executes a new AsyncTask to load a page of widget previews.
1153     */
1154    private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
1155            int cellWidth, int cellHeight, int cellCountX) {
1156
1157        // Prune all tasks that are no longer needed
1158        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1159        while (iter.hasNext()) {
1160            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1161            int taskPage = task.page;
1162            if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
1163                    taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
1164                task.cancel(false);
1165                iter.remove();
1166            } else {
1167                task.setThreadPriority(getThreadPriorityForPage(taskPage));
1168            }
1169        }
1170
1171        // We introduce a slight delay to order the loading of side pages so that we don't thrash
1172        final int sleepMs = getSleepForPage(page);
1173        AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
1174            new AsyncTaskCallback() {
1175                @Override
1176                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1177                    try {
1178                        try {
1179                            Thread.sleep(sleepMs);
1180                        } catch (Exception e) {}
1181                        loadWidgetPreviewsInBackground(task, data);
1182                    } finally {
1183                        if (task.isCancelled()) {
1184                            data.cleanup(true);
1185                        }
1186                    }
1187                }
1188            },
1189            new AsyncTaskCallback() {
1190                @Override
1191                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1192                    mRunningTasks.remove(task);
1193                    if (task.isCancelled()) return;
1194                    // do cleanup inside onSyncWidgetPageItems
1195                    onSyncWidgetPageItems(data);
1196                }
1197            });
1198
1199        // Ensure that the task is appropriately prioritized and runs in parallel
1200        AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
1201                AsyncTaskPageData.Type.LoadWidgetPreviewData);
1202        t.setThreadPriority(getThreadPriorityForPage(page));
1203        t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
1204        mRunningTasks.add(t);
1205    }
1206
1207    /*
1208     * Widgets PagedView implementation
1209     */
1210    private void setupPage(PagedViewGridLayout layout) {
1211        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1212                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1213
1214        // Note: We force a measure here to get around the fact that when we do layout calculations
1215        // immediately after syncing, we don't have a proper width.
1216        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1217        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
1218        layout.setMinimumWidth(getPageContentWidth());
1219        layout.measure(widthSpec, heightSpec);
1220    }
1221
1222    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
1223        renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
1224    }
1225
1226    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
1227            float scale) {
1228        if (bitmap != null) {
1229            Canvas c = new Canvas(bitmap);
1230            c.scale(scale, scale);
1231            Rect oldBounds = d.copyBounds();
1232            d.setBounds(x, y, x + w, y + h);
1233            d.draw(c);
1234            d.setBounds(oldBounds); // Restore the bounds
1235            c.setBitmap(null);
1236        }
1237    }
1238
1239    private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
1240        Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
1241        final Canvas c = mCachedShortcutPreviewCanvas.get();
1242        if (tempBitmap == null ||
1243                tempBitmap.getWidth() != maxWidth ||
1244                tempBitmap.getHeight() != maxHeight) {
1245            tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1246            mCachedShortcutPreviewBitmap.set(tempBitmap);
1247        } else {
1248            c.setBitmap(tempBitmap);
1249            c.drawColor(0, PorterDuff.Mode.CLEAR);
1250            c.setBitmap(null);
1251        }
1252        // Render the icon
1253        Drawable icon = mIconCache.getFullResIcon(info);
1254
1255        int paddingTop =
1256                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
1257        int paddingLeft =
1258                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
1259        int paddingRight =
1260                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
1261
1262        int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
1263        float scaleSize = scaledIconWidth / (float) mAppIconSize;
1264
1265        renderDrawableToBitmap(
1266                icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
1267
1268        Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1269        c.setBitmap(preview);
1270        Paint p = mCachedShortcutPreviewPaint.get();
1271        if (p == null) {
1272            p = new Paint();
1273            ColorMatrix colorMatrix = new ColorMatrix();
1274            colorMatrix.setSaturation(0);
1275            p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
1276            p.setAlpha((int) (255 * 0.06f));
1277            //float density = 1f;
1278            //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
1279            mCachedShortcutPreviewPaint.set(p);
1280        }
1281        c.drawBitmap(tempBitmap, 0, 0, p);
1282        c.setBitmap(null);
1283
1284        renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
1285
1286        return preview;
1287    }
1288
1289    private Bitmap getWidgetPreview(ComponentName provider, int previewImage,
1290            int iconId, int cellHSpan, int cellVSpan, int maxWidth,
1291            int maxHeight) {
1292        // Load the preview image if possible
1293        String packageName = provider.getPackageName();
1294        if (maxWidth < 0) maxWidth = Integer.MAX_VALUE;
1295        if (maxHeight < 0) maxHeight = Integer.MAX_VALUE;
1296
1297        Drawable drawable = null;
1298        if (previewImage != 0) {
1299            drawable = mPackageManager.getDrawable(packageName, previewImage, null);
1300            if (drawable == null) {
1301                Log.w(TAG, "Can't load widget preview drawable 0x" +
1302                        Integer.toHexString(previewImage) + " for provider: " + provider);
1303            }
1304        }
1305
1306        int bitmapWidth;
1307        int bitmapHeight;
1308        Bitmap defaultPreview = null;
1309        boolean widgetPreviewExists = (drawable != null);
1310        if (widgetPreviewExists) {
1311            bitmapWidth = drawable.getIntrinsicWidth();
1312            bitmapHeight = drawable.getIntrinsicHeight();
1313        } else {
1314            // Generate a preview image if we couldn't load one
1315            if (cellHSpan < 1) cellHSpan = 1;
1316            if (cellVSpan < 1) cellVSpan = 1;
1317
1318            BitmapDrawable previewDrawable = (BitmapDrawable) getResources()
1319                    .getDrawable(R.drawable.widget_preview_tile);
1320            final int previewDrawableWidth = previewDrawable
1321                    .getIntrinsicWidth();
1322            final int previewDrawableHeight = previewDrawable
1323                    .getIntrinsicHeight();
1324            bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
1325            bitmapHeight = previewDrawableHeight * cellVSpan;
1326
1327            defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1328                    Config.ARGB_8888);
1329            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1330            c.setBitmap(defaultPreview);
1331            previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
1332            previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
1333                    Shader.TileMode.REPEAT);
1334            previewDrawable.draw(c);
1335            c.setBitmap(null);
1336
1337            // Draw the icon in the top left corner
1338            int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1339            int smallestSide = Math.min(bitmapWidth, bitmapHeight);
1340            float iconScale = Math.min((float) smallestSide
1341                    / (mAppIconSize + 2 * minOffset), 1f);
1342
1343            try {
1344                Drawable icon = null;
1345                int hoffset =
1346                        (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
1347                int yoffset =
1348                        (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
1349                if (iconId > 0)
1350                    icon = mIconCache.getFullResIcon(packageName, iconId);
1351                Resources resources = mLauncher.getResources();
1352                if (icon != null) {
1353                    renderDrawableToBitmap(icon, defaultPreview, hoffset,
1354                            yoffset, (int) (mAppIconSize * iconScale),
1355                            (int) (mAppIconSize * iconScale));
1356                }
1357            } catch (Resources.NotFoundException e) {
1358            }
1359        }
1360
1361        // Scale to fit width only - let the widget preview be clipped in the
1362        // vertical dimension
1363        float scale = 1f;
1364        if (bitmapWidth > maxWidth) {
1365            scale = maxWidth / (float) bitmapWidth;
1366        }
1367        if (scale != 1f) {
1368            bitmapWidth = (int) (scale * bitmapWidth);
1369            bitmapHeight = (int) (scale * bitmapHeight);
1370        }
1371
1372        Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1373                Config.ARGB_8888);
1374
1375        // Draw the scaled preview into the final bitmap
1376        if (widgetPreviewExists) {
1377            renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth,
1378                    bitmapHeight);
1379        } else {
1380            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1381            final Rect src = mCachedAppWidgetPreviewSrcRect.get();
1382            final Rect dest = mCachedAppWidgetPreviewDestRect.get();
1383            c.setBitmap(preview);
1384            src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
1385            dest.set(0, 0, preview.getWidth(), preview.getHeight());
1386
1387            Paint p = mCachedAppWidgetPreviewPaint.get();
1388            if (p == null) {
1389                p = new Paint();
1390                p.setFilterBitmap(true);
1391                mCachedAppWidgetPreviewPaint.set(p);
1392            }
1393            c.drawBitmap(defaultPreview, src, dest, p);
1394            c.setBitmap(null);
1395        }
1396        return preview;
1397    }
1398
1399    public void syncWidgetPageItems(final int page, final boolean immediate) {
1400        int numItemsPerPage = mWidgetCountX * mWidgetCountY;
1401
1402        // Calculate the dimensions of each cell we are giving to each widget
1403        final ArrayList<Object> items = new ArrayList<Object>();
1404        int contentWidth = mWidgetSpacingLayout.getContentWidth();
1405        final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
1406                - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
1407        int contentHeight = mWidgetSpacingLayout.getContentHeight();
1408        final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
1409                - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
1410
1411        // Prepare the set of widgets to load previews for in the background
1412        int offset = (page - mNumAppsPages) * numItemsPerPage;
1413        for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1414            items.add(mWidgets.get(i));
1415        }
1416
1417        // Prepopulate the pages with the other widget info, and fill in the previews later
1418        final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1419        layout.setColumnCount(layout.getCellCountX());
1420        for (int i = 0; i < items.size(); ++i) {
1421            Object rawInfo = items.get(i);
1422            PendingAddItemInfo createItemInfo = null;
1423            PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1424                    R.layout.apps_customize_widget, layout, false);
1425            if (rawInfo instanceof AppWidgetProviderInfo) {
1426                // Fill in the widget information
1427                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1428                createItemInfo = new PendingAddWidgetInfo(info, null, null);
1429
1430                // Determine the widget spans and min resize spans.
1431                int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
1432                createItemInfo.spanX = spanXY[0];
1433                createItemInfo.spanY = spanXY[1];
1434                int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
1435                createItemInfo.minSpanX = minSpanXY[0];
1436                createItemInfo.minSpanY = minSpanXY[1];
1437
1438                widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
1439                widget.setTag(createItemInfo);
1440                widget.setShortPressListener(this);
1441            } else if (rawInfo instanceof ResolveInfo) {
1442                // Fill in the shortcuts information
1443                ResolveInfo info = (ResolveInfo) rawInfo;
1444                createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
1445                createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1446                createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1447                        info.activityInfo.name);
1448                widget.applyFromResolveInfo(mPackageManager, info);
1449                widget.setTag(createItemInfo);
1450            }
1451            widget.setOnClickListener(this);
1452            widget.setOnLongClickListener(this);
1453            widget.setOnTouchListener(this);
1454            widget.setOnKeyListener(this);
1455
1456            // Layout each widget
1457            int ix = i % mWidgetCountX;
1458            int iy = i / mWidgetCountX;
1459            GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1460                    GridLayout.spec(iy, GridLayout.LEFT),
1461                    GridLayout.spec(ix, GridLayout.TOP));
1462            lp.width = cellWidth;
1463            lp.height = cellHeight;
1464            lp.setGravity(Gravity.TOP | Gravity.LEFT);
1465            if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1466            if (iy > 0) lp.topMargin = mWidgetHeightGap;
1467            layout.addView(widget, lp);
1468        }
1469
1470        // wait until a call on onLayout to start loading, because
1471        // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
1472        // TODO: can we do a measure/layout immediately?
1473        layout.setOnLayoutListener(new Runnable() {
1474            public void run() {
1475                // Load the widget previews
1476                int maxPreviewWidth = cellWidth;
1477                int maxPreviewHeight = cellHeight;
1478                if (layout.getChildCount() > 0) {
1479                    PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
1480                    int[] maxSize = w.getPreviewSize();
1481                    maxPreviewWidth = maxSize[0];
1482                    maxPreviewHeight = maxSize[1];
1483                }
1484                if (immediate) {
1485                    AsyncTaskPageData data = new AsyncTaskPageData(page, items,
1486                            maxPreviewWidth, maxPreviewHeight, null, null);
1487                    loadWidgetPreviewsInBackground(null, data);
1488                    onSyncWidgetPageItems(data);
1489                } else {
1490                    prepareLoadWidgetPreviewsTask(page, items,
1491                            maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
1492                }
1493            }
1494        });
1495    }
1496    private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1497            AsyncTaskPageData data) {
1498        // loadWidgetPreviewsInBackground can be called without a task to load a set of widget
1499        // previews synchronously
1500        if (task != null) {
1501            // Ensure that this task starts running at the correct priority
1502            task.syncThreadPriority();
1503        }
1504
1505        // Load each of the widget/shortcut previews
1506        ArrayList<Object> items = data.items;
1507        ArrayList<Bitmap> images = data.generatedImages;
1508        int count = items.size();
1509        for (int i = 0; i < count; ++i) {
1510            if (task != null) {
1511                // Ensure we haven't been cancelled yet
1512                if (task.isCancelled()) break;
1513                // Before work on each item, ensure that this task is running at the correct
1514                // priority
1515                task.syncThreadPriority();
1516            }
1517
1518            Object rawInfo = items.get(i);
1519            if (rawInfo instanceof AppWidgetProviderInfo) {
1520                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1521                int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
1522
1523                int maxWidth = Math.min(data.maxImageWidth,
1524                        mWidgetSpacingLayout.estimateCellWidth(cellSpans[0]));
1525                int maxHeight = Math.min(data.maxImageHeight,
1526                        mWidgetSpacingLayout.estimateCellHeight(cellSpans[1]));
1527                Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon,
1528                        cellSpans[0], cellSpans[1], maxWidth, maxHeight);
1529                images.add(b);
1530            } else if (rawInfo instanceof ResolveInfo) {
1531                // Fill in the shortcuts information
1532                ResolveInfo info = (ResolveInfo) rawInfo;
1533                images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight));
1534            }
1535        }
1536    }
1537
1538    private void onSyncWidgetPageItems(AsyncTaskPageData data) {
1539        if (mInTransition) {
1540            mDeferredSyncWidgetPageItems.add(data);
1541            return;
1542        }
1543        try {
1544            int page = data.page;
1545            PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1546
1547            ArrayList<Object> items = data.items;
1548            int count = items.size();
1549            for (int i = 0; i < count; ++i) {
1550                PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1551                if (widget != null) {
1552                    Bitmap preview = data.generatedImages.get(i);
1553                    widget.applyPreview(new FastBitmapDrawable(preview), i);
1554                }
1555            }
1556
1557            layout.createHardwareLayer();
1558            invalidate();
1559
1560            // Update all thread priorities
1561            Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1562            while (iter.hasNext()) {
1563                AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1564                int pageIndex = task.page;
1565                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1566            }
1567        } finally {
1568            data.cleanup(false);
1569        }
1570    }
1571
1572    @Override
1573    public void syncPages() {
1574        removeAllViews();
1575        cancelAllTasks();
1576
1577        Context context = getContext();
1578        for (int j = 0; j < mNumWidgetPages; ++j) {
1579            PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1580                    mWidgetCountY);
1581            setupPage(layout);
1582            addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
1583                    LayoutParams.MATCH_PARENT));
1584        }
1585
1586        for (int i = 0; i < mNumAppsPages; ++i) {
1587            PagedViewCellLayout layout = new PagedViewCellLayout(context);
1588            setupPage(layout);
1589            addView(layout);
1590        }
1591    }
1592
1593    @Override
1594    public void syncPageItems(int page, boolean immediate) {
1595        if (page < mNumAppsPages) {
1596            syncAppsPageItems(page, immediate);
1597        } else {
1598            syncWidgetPageItems(page, immediate);
1599        }
1600    }
1601
1602    // We want our pages to be z-ordered such that the further a page is to the left, the higher
1603    // it is in the z-order. This is important to insure touch events are handled correctly.
1604    View getPageAt(int index) {
1605        return getChildAt(indexToPage(index));
1606    }
1607
1608    @Override
1609    protected int indexToPage(int index) {
1610        return getChildCount() - index - 1;
1611    }
1612
1613    // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1614    @Override
1615    protected void screenScrolled(int screenCenter) {
1616        super.screenScrolled(screenCenter);
1617
1618        for (int i = 0; i < getChildCount(); i++) {
1619            View v = getPageAt(i);
1620            if (v != null) {
1621                float scrollProgress = getScrollProgress(screenCenter, v, i);
1622
1623                float interpolatedProgress =
1624                        mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1625                float scale = (1 - interpolatedProgress) +
1626                        interpolatedProgress * TRANSITION_SCALE_FACTOR;
1627                float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
1628
1629                float alpha;
1630
1631                if (scrollProgress < 0) {
1632                    alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
1633                        1 - Math.abs(scrollProgress)) : 1.0f;
1634                } else {
1635                    // On large screens we need to fade the page as it nears its leftmost position
1636                    alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1637                }
1638
1639                v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1640                int pageWidth = v.getMeasuredWidth();
1641                int pageHeight = v.getMeasuredHeight();
1642
1643                if (PERFORM_OVERSCROLL_ROTATION) {
1644                    if (i == 0 && scrollProgress < 0) {
1645                        // Overscroll to the left
1646                        v.setPivotX(TRANSITION_PIVOT * pageWidth);
1647                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1648                        scale = 1.0f;
1649                        alpha = 1.0f;
1650                        // On the first page, we don't want the page to have any lateral motion
1651                        translationX = 0;
1652                    } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1653                        // Overscroll to the right
1654                        v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1655                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1656                        scale = 1.0f;
1657                        alpha = 1.0f;
1658                        // On the last page, we don't want the page to have any lateral motion.
1659                        translationX = 0;
1660                    } else {
1661                        v.setPivotY(pageHeight / 2.0f);
1662                        v.setPivotX(pageWidth / 2.0f);
1663                        v.setRotationY(0f);
1664                    }
1665                }
1666
1667                v.setTranslationX(translationX);
1668                v.setScaleX(scale);
1669                v.setScaleY(scale);
1670                v.setAlpha(alpha);
1671
1672                // If the view has 0 alpha, we set it to be invisible so as to prevent
1673                // it from accepting touches
1674                if (alpha == 0) {
1675                    v.setVisibility(INVISIBLE);
1676                } else if (v.getVisibility() != VISIBLE) {
1677                    v.setVisibility(VISIBLE);
1678                }
1679            }
1680        }
1681    }
1682
1683    protected void overScroll(float amount) {
1684        acceleratedOverScroll(amount);
1685    }
1686
1687    /**
1688     * Used by the parent to get the content width to set the tab bar to
1689     * @return
1690     */
1691    public int getPageContentWidth() {
1692        return mContentWidth;
1693    }
1694
1695    @Override
1696    protected void onPageEndMoving() {
1697        super.onPageEndMoving();
1698        mForceDrawAllChildrenNextFrame = true;
1699        // We reset the save index when we change pages so that it will be recalculated on next
1700        // rotation
1701        mSaveInstanceStateItemIndex = -1;
1702    }
1703
1704    /*
1705     * AllAppsView implementation
1706     */
1707    @Override
1708    public void setup(Launcher launcher, DragController dragController) {
1709        mLauncher = launcher;
1710        mDragController = dragController;
1711    }
1712    @Override
1713    public void zoom(float zoom, boolean animate) {
1714        // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1715    }
1716    @Override
1717    public boolean isVisible() {
1718        return (getVisibility() == VISIBLE);
1719    }
1720    @Override
1721    public boolean isAnimating() {
1722        return false;
1723    }
1724    @Override
1725    public void setApps(ArrayList<ApplicationInfo> list) {
1726        mApps = list;
1727        Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
1728        updatePageCounts();
1729
1730        // The next layout pass will trigger data-ready if both widgets and apps are set, so
1731        // request a layout to do this test and invalidate the page data when ready.
1732        if (testDataReady()) requestLayout();
1733    }
1734    private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1735        // We add it in place, in alphabetical order
1736        int count = list.size();
1737        for (int i = 0; i < count; ++i) {
1738            ApplicationInfo info = list.get(i);
1739            int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1740            if (index < 0) {
1741                mApps.add(-(index + 1), info);
1742            }
1743        }
1744    }
1745    @Override
1746    public void addApps(ArrayList<ApplicationInfo> list) {
1747        addAppsWithoutInvalidate(list);
1748        updatePageCounts();
1749        invalidatePageData();
1750    }
1751    private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1752        ComponentName removeComponent = item.intent.getComponent();
1753        int length = list.size();
1754        for (int i = 0; i < length; ++i) {
1755            ApplicationInfo info = list.get(i);
1756            if (info.intent.getComponent().equals(removeComponent)) {
1757                return i;
1758            }
1759        }
1760        return -1;
1761    }
1762    private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1763        // loop through all the apps and remove apps that have the same component
1764        int length = list.size();
1765        for (int i = 0; i < length; ++i) {
1766            ApplicationInfo info = list.get(i);
1767            int removeIndex = findAppByComponent(mApps, info);
1768            if (removeIndex > -1) {
1769                mApps.remove(removeIndex);
1770            }
1771        }
1772    }
1773    @Override
1774    public void removeApps(ArrayList<ApplicationInfo> list) {
1775        removeAppsWithoutInvalidate(list);
1776        updatePageCounts();
1777        invalidatePageData();
1778    }
1779    @Override
1780    public void updateApps(ArrayList<ApplicationInfo> list) {
1781        // We remove and re-add the updated applications list because it's properties may have
1782        // changed (ie. the title), and this will ensure that the items will be in their proper
1783        // place in the list.
1784        removeAppsWithoutInvalidate(list);
1785        addAppsWithoutInvalidate(list);
1786        updatePageCounts();
1787
1788        invalidatePageData();
1789    }
1790
1791    @Override
1792    public void reset() {
1793        // If we have reset, then we should not continue to restore the previous state
1794        mSaveInstanceStateItemIndex = -1;
1795
1796        AppsCustomizeTabHost tabHost = getTabHost();
1797        String tag = tabHost.getCurrentTabTag();
1798        if (tag != null) {
1799            if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1800                tabHost.setCurrentTabFromContent(ContentType.Applications);
1801            }
1802        }
1803
1804        if (mCurrentPage != 0) {
1805            invalidatePageData(0);
1806        }
1807    }
1808
1809    private AppsCustomizeTabHost getTabHost() {
1810        return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1811    }
1812
1813    @Override
1814    public void dumpState() {
1815        // TODO: Dump information related to current list of Applications, Widgets, etc.
1816        ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
1817        dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
1818    }
1819
1820    private void dumpAppWidgetProviderInfoList(String tag, String label,
1821            ArrayList<Object> list) {
1822        Log.d(tag, label + " size=" + list.size());
1823        for (Object i: list) {
1824            if (i instanceof AppWidgetProviderInfo) {
1825                AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1826                Log.d(tag, "   label=\"" + info.label + "\" previewImage=" + info.previewImage
1827                        + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1828                        + " initialLayout=" + info.initialLayout
1829                        + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1830            } else if (i instanceof ResolveInfo) {
1831                ResolveInfo info = (ResolveInfo) i;
1832                Log.d(tag, "   label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1833                        + info.icon);
1834            }
1835        }
1836    }
1837
1838    @Override
1839    public void surrender() {
1840        // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1841        // should stop this now.
1842
1843        // Stop all background tasks
1844        cancelAllTasks();
1845    }
1846
1847    @Override
1848    public void iconPressed(PagedViewIcon icon) {
1849        // Reset the previously pressed icon and store a reference to the pressed icon so that
1850        // we can reset it on return to Launcher (in Launcher.onResume())
1851        if (mPressedIcon != null) {
1852            mPressedIcon.resetDrawableState();
1853        }
1854        mPressedIcon = icon;
1855    }
1856
1857    public void resetDrawableState() {
1858        if (mPressedIcon != null) {
1859            mPressedIcon.resetDrawableState();
1860            mPressedIcon = null;
1861        }
1862    }
1863
1864    /*
1865     * We load an extra page on each side to prevent flashes from scrolling and loading of the
1866     * widget previews in the background with the AsyncTasks.
1867     */
1868    final static int sLookBehindPageCount = 2;
1869    final static int sLookAheadPageCount = 2;
1870    protected int getAssociatedLowerPageBound(int page) {
1871        final int count = getChildCount();
1872        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1873        int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
1874        return windowMinIndex;
1875    }
1876    protected int getAssociatedUpperPageBound(int page) {
1877        final int count = getChildCount();
1878        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1879        int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
1880                count - 1);
1881        return windowMaxIndex;
1882    }
1883
1884    @Override
1885    protected String getCurrentPageDescription() {
1886        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1887        int stringId = R.string.default_scroll_format;
1888        int count = 0;
1889
1890        if (page < mNumAppsPages) {
1891            stringId = R.string.apps_customize_apps_scroll_format;
1892            count = mNumAppsPages;
1893        } else {
1894            page -= mNumAppsPages;
1895            stringId = R.string.apps_customize_widgets_scroll_format;
1896            count = mNumWidgetPages;
1897        }
1898
1899        return String.format(getContext().getString(stringId), page + 1, count);
1900    }
1901}
1902