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