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