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