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