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