AppsCustomizePagedView.java revision de1af7661548692d370518528ff91c7422b9c8ae
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.Rect;
37import android.graphics.drawable.Drawable;
38import android.os.AsyncTask;
39import android.os.Process;
40import android.util.AttributeSet;
41import android.util.Log;
42import android.view.LayoutInflater;
43import android.view.MotionEvent;
44import android.view.View;
45import android.view.ViewGroup;
46import android.view.animation.AccelerateInterpolator;
47import android.widget.GridLayout;
48import android.widget.ImageView;
49import android.widget.Toast;
50
51import com.android.launcher.R;
52import com.android.launcher2.DropTarget.DragObject;
53
54import java.util.ArrayList;
55import java.util.Collections;
56import java.util.Iterator;
57import java.util.List;
58
59/**
60 * A simple callback interface which also provides the results of the task.
61 */
62interface AsyncTaskCallback {
63    void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
64}
65
66/**
67 * The data needed to perform either of the custom AsyncTasks.
68 */
69class AsyncTaskPageData {
70    enum Type {
71        LoadWidgetPreviewData,
72        LoadHolographicIconsData
73    }
74
75    AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
76            AsyncTaskCallback postR) {
77        page = p;
78        items = l;
79        sourceImages = si;
80        generatedImages = new ArrayList<Bitmap>();
81        cellWidth = cellHeight = -1;
82        doInBackgroundCallback = bgR;
83        postExecuteCallback = postR;
84    }
85    AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR,
86            AsyncTaskCallback postR) {
87        page = p;
88        items = l;
89        generatedImages = new ArrayList<Bitmap>();
90        cellWidth = cw;
91        cellHeight = ch;
92        cellCountX = ccx;
93        doInBackgroundCallback = bgR;
94        postExecuteCallback = postR;
95    }
96    int page;
97    ArrayList<Object> items;
98    ArrayList<Bitmap> sourceImages;
99    ArrayList<Bitmap> generatedImages;
100    int cellWidth;
101    int cellHeight;
102    int cellCountX;
103    AsyncTaskCallback doInBackgroundCallback;
104    AsyncTaskCallback postExecuteCallback;
105}
106
107/**
108 * A generic template for an async task used in AppsCustomize.
109 */
110class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
111    AppsCustomizeAsyncTask(int p, AppsCustomizePagedView.ContentType t, AsyncTaskPageData.Type ty) {
112        page = p;
113        pageContentType = t;
114        threadPriority = Process.THREAD_PRIORITY_DEFAULT;
115        dataType = ty;
116    }
117    @Override
118    protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
119        if (params.length != 1) return null;
120        // Load each of the widget previews in the background
121        params[0].doInBackgroundCallback.run(this, params[0]);
122        return params[0];
123    }
124    @Override
125    protected void onPostExecute(AsyncTaskPageData result) {
126        // All the widget previews are loaded, so we can just callback to inflate the page
127        result.postExecuteCallback.run(this, result);
128    }
129
130    void setThreadPriority(int p) {
131        threadPriority = p;
132    }
133    void syncThreadPriority() {
134        Process.setThreadPriority(threadPriority);
135    }
136
137    // The page that this async task is associated with
138    AsyncTaskPageData.Type dataType;
139    int page;
140    AppsCustomizePagedView.ContentType pageContentType;
141    int threadPriority;
142}
143
144/**
145 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
146 */
147public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
148        AllAppsView, View.OnClickListener, DragSource {
149    static final String LOG_TAG = "AppsCustomizePagedView";
150
151    /**
152     * The different content types that this paged view can show.
153     */
154    public enum ContentType {
155        Applications,
156        Widgets
157    }
158
159    // Refs
160    private Launcher mLauncher;
161    private DragController mDragController;
162    private final LayoutInflater mLayoutInflater;
163    private final PackageManager mPackageManager;
164
165    // Content
166    private ContentType mContentType;
167    private ArrayList<ApplicationInfo> mApps;
168    private ArrayList<Object> mWidgets;
169    private ArrayList<Object> mShortcuts;
170
171    // Caching
172    private Canvas mCanvas;
173    private Drawable mDefaultWidgetBackground;
174    private IconCache mIconCache;
175
176    // Dimens
177    private int mContentWidth;
178    private int mAppIconSize;
179    private int mMaxWidgetSpan, mMinWidgetSpan;
180    private int mWidgetCountX, mWidgetCountY;
181    private int mWidgetWidthGap, mWidgetHeightGap;
182    private int mShortcutCountX, mShortcutCountY;
183    private int mShortcutWidthGap, mShortcutHeightGap;
184    private final int mWidgetPreviewIconPaddedDimension;
185    private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
186    private PagedViewCellLayout mWidgetSpacingLayout;
187
188    // Previews & outlines
189    ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
190    private HolographicOutlineHelper mHolographicOutlineHelper;
191
192    public AppsCustomizePagedView(Context context, AttributeSet attrs) {
193        super(context, attrs);
194        mLayoutInflater = LayoutInflater.from(context);
195        mPackageManager = context.getPackageManager();
196        mContentType = ContentType.Applications;
197        mApps = new ArrayList<ApplicationInfo>();
198        mWidgets = new ArrayList<Object>();
199        mShortcuts = new ArrayList<Object>();
200        mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
201        mHolographicOutlineHelper = new HolographicOutlineHelper();
202        mCanvas = new Canvas();
203        mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
204
205        // Save the default widget preview background
206        Resources resources = context.getResources();
207        mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo);
208        mAppIconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
209
210        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0);
211        // TODO-APPS_CUSTOMIZE: remove these unnecessary attrs after
212        mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6);
213        mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4);
214        a.recycle();
215        a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
216        mWidgetWidthGap =
217            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
218        mWidgetHeightGap =
219            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
220        mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
221        mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
222        a.recycle();
223        mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
224
225        // The max widget span is the length N, such that NxN is the largest bounds that the widget
226        // preview can be before applying the widget scaling
227        mMinWidgetSpan = 1;
228        mMaxWidgetSpan = 3;
229
230        // The padding on the non-matched dimension for the default widget preview icons
231        // (top + bottom)
232        mWidgetPreviewIconPaddedDimension =
233            (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage)));
234    }
235
236    @Override
237    protected void init() {
238        super.init();
239        mCenterPagesVertically = false;
240
241        Context context = getContext();
242        Resources r = context.getResources();
243        setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
244    }
245
246    @Override
247    protected void onWallpaperTap(MotionEvent ev) {
248        int action = ev.getAction();
249        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
250            // Dismiss AppsCustomize if we tap
251            mLauncher.showWorkspace(true);
252        }
253    }
254
255    /**
256     * This differs from isDataReady as this is the test done if isDataReady is not set.
257     */
258    private boolean testDataReady() {
259        // We only do this test once, and we default to the Applications page, so we only really
260        // have to wait for there to be apps.
261        return !mApps.isEmpty();
262    }
263
264    protected void onDataReady(int width, int height) {
265        // Note that we transpose the counts in portrait so that we get a similar layout
266        boolean isLandscape = getResources().getConfiguration().orientation ==
267            Configuration.ORIENTATION_LANDSCAPE;
268        int maxCellCountX = Integer.MAX_VALUE;
269        int maxCellCountY = Integer.MAX_VALUE;
270        if (LauncherApplication.isScreenLarge()) {
271            maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
272                LauncherModel.getCellCountY());
273            maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
274                LauncherModel.getCellCountX());
275        }
276
277        // Now that the data is ready, we can calculate the content width, the number of cells to
278        // use for each page
279        mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
280        mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
281                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
282        mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
283        mCellCountX = mWidgetSpacingLayout.getCellCountX();
284        mCellCountY = mWidgetSpacingLayout.getCellCountY();
285        mWidgetCountX = Math.max(1, (int) Math.round(mCellCountX / 2f));
286        mWidgetCountY = Math.max(1, (int) Math.round(mCellCountY / 3f));
287        mShortcutCountX = Math.max(1, (int) Math.round(mCellCountX / 2f));
288        mShortcutCountY = Math.max(1, (int) Math.round(mCellCountY / 2f));
289
290        // Force a measure to update recalculate the gaps
291        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
292        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
293        mWidgetSpacingLayout.measure(widthSpec, heightSpec);
294        mContentWidth = mWidgetSpacingLayout.getContentWidth();
295
296        invalidatePageData();
297    }
298
299    @Override
300    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
301        int width = MeasureSpec.getSize(widthMeasureSpec);
302        int height = MeasureSpec.getSize(heightMeasureSpec);
303        if (!isDataReady()) {
304            if (testDataReady()) {
305                setDataIsReady();
306                setMeasuredDimension(width, height);
307                onDataReady(width, height);
308            }
309        }
310
311        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
312    }
313
314    /** Removes and returns the ResolveInfo with the specified ComponentName */
315    private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list,
316            ComponentName cn) {
317        Iterator<ResolveInfo> iter = list.iterator();
318        while (iter.hasNext()) {
319            ResolveInfo rinfo = iter.next();
320            ActivityInfo info = rinfo.activityInfo;
321            ComponentName c = new ComponentName(info.packageName, info.name);
322            if (c.equals(cn)) {
323                iter.remove();
324                return rinfo;
325            }
326        }
327        return null;
328    }
329
330    public void onPackagesUpdated() {
331        // Get the list of widgets and shortcuts
332        boolean wasEmpty = mWidgets.isEmpty() && mShortcuts.isEmpty();
333        mWidgets.clear();
334        mShortcuts.clear();
335        List<AppWidgetProviderInfo> widgets =
336            AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
337        Collections.sort(widgets,
338                new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
339        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
340        List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
341        Collections.sort(shortcuts,
342                new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
343        mWidgets.addAll(widgets);
344        mShortcuts.addAll(shortcuts);
345
346        if (wasEmpty) {
347            // The next layout pass will trigger data-ready if both widgets and apps are set, so request
348            // a layout to do this test and invalidate the page data when ready.
349            if (testDataReady()) requestLayout();
350        } else {
351            invalidatePageData();
352        }
353    }
354
355    @Override
356    public void onClick(View v) {
357        // When we have exited all apps or are in transition, disregard clicks
358        if (!mLauncher.isAllAppsCustomizeOpen() ||
359                mLauncher.getWorkspace().isSwitchingState()) return;
360
361        if (v instanceof PagedViewIcon) {
362            // Animate some feedback to the click
363            final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
364            animateClickFeedback(v, new Runnable() {
365                @Override
366                public void run() {
367                    mLauncher.startActivitySafely(appInfo.intent, appInfo);
368                }
369            });
370        } else if (v instanceof PagedViewWidget) {
371            // Let the user know that they have to long press to add a widget
372            Toast.makeText(getContext(), R.string.long_press_widget_to_add,
373                    Toast.LENGTH_SHORT).show();
374
375            // Create a little animation to show that the widget can move
376            float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
377            final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
378            AnimatorSet bounce = new AnimatorSet();
379            ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
380            tyuAnim.setDuration(125);
381            ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
382            tydAnim.setDuration(100);
383            bounce.play(tyuAnim).before(tydAnim);
384            bounce.setInterpolator(new AccelerateInterpolator());
385            bounce.start();
386        }
387    }
388
389    /*
390     * PagedViewWithDraggableItems implementation
391     */
392    @Override
393    protected void determineDraggingStart(android.view.MotionEvent ev) {
394        // Disable dragging by pulling an app down for now.
395    }
396
397    private void beginDraggingApplication(View v) {
398        mLauncher.getWorkspace().onDragStartedWithItem(v);
399        mLauncher.getWorkspace().beginDragShared(v, this);
400    }
401
402    private void beginDraggingWidget(View v) {
403        // Get the widget preview as the drag representation
404        ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
405        PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
406
407        // Compose the drag image
408        Bitmap b;
409        Drawable preview = image.getDrawable();
410        int w = preview.getIntrinsicWidth();
411        int h = preview.getIntrinsicHeight();
412        if (createItemInfo instanceof PendingAddWidgetInfo) {
413            PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo;
414            int[] spanXY = CellLayout.rectToCell(getResources(),
415                    createWidgetInfo.minWidth, createWidgetInfo.minHeight, null);
416            createItemInfo.spanX = spanXY[0];
417            createItemInfo.spanY = spanXY[1];
418
419            b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
420            renderDrawableToBitmap(preview, b, 0, 0, w, h, 1, 1);
421        } else {
422            // Workaround for the fact that we don't keep the original ResolveInfo associated with
423            // the shortcut around.  To get the icon, we just render the preview image (which has
424            // the shortcut icon) to a new drag bitmap that clips the non-icon space.
425            b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension,
426                    mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888);
427            mCanvas.setBitmap(b);
428            mCanvas.save();
429            preview.draw(mCanvas);
430            mCanvas.restore();
431            createItemInfo.spanX = createItemInfo.spanY = 1;
432        }
433
434        // Start the drag
435        mLauncher.lockScreenOrientation();
436        mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX,
437                createItemInfo.spanY, b);
438        mDragController.startDrag(image, b, this, createItemInfo,
439                DragController.DRAG_ACTION_COPY, null);
440        b.recycle();
441    }
442    @Override
443    protected boolean beginDragging(View v) {
444        if (!super.beginDragging(v)) return false;
445
446        // Go into spring loaded mode (must happen before we startDrag())
447        int currentPageIndex = mLauncher.getWorkspace().getCurrentPage();
448        CellLayout currentPage = (CellLayout) mLauncher.getWorkspace().getChildAt(currentPageIndex);
449        mLauncher.enterSpringLoadedDragMode(currentPage);
450
451        if (v instanceof PagedViewIcon) {
452            beginDraggingApplication(v);
453        } else if (v instanceof PagedViewWidget) {
454            beginDraggingWidget(v);
455        }
456        return true;
457    }
458    private void endDragging(View target, boolean success) {
459        mLauncher.getWorkspace().onDragStopped(success);
460        if (!success || (target != mLauncher.getWorkspace() &&
461                !(target instanceof DeleteDropTarget))) {
462            // Exit spring loaded mode if we have not successfully dropped or have not handled the
463            // drop in Workspace
464            mLauncher.exitSpringLoadedDragMode();
465        }
466        mLauncher.unlockScreenOrientation();
467
468    }
469
470    @Override
471    public void onDropCompleted(View target, DragObject d, boolean success) {
472        endDragging(target, success);
473
474        // Display an error message if the drag failed due to there not being enough space on the
475        // target layout we were dropping on.
476        if (!success) {
477            boolean showOutOfSpaceMessage = false;
478            if (target instanceof Workspace) {
479                int currentScreen = mLauncher.getCurrentWorkspaceScreen();
480                Workspace workspace = (Workspace) target;
481                CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
482                ItemInfo itemInfo = (ItemInfo) d.dragInfo;
483                if (layout != null) {
484                    layout.calculateSpans(itemInfo);
485                    showOutOfSpaceMessage =
486                            !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
487                }
488            }
489            // TODO-APPS_CUSTOMIZE: We need to handle this for folders as well later.
490            if (showOutOfSpaceMessage) {
491                mLauncher.showOutOfSpaceMessage();
492            }
493        }
494    }
495
496    public void setContentType(ContentType type) {
497        mContentType = type;
498        setCurrentPage(0);
499        invalidatePageData();
500    }
501
502    public boolean isContentType(ContentType type) {
503        return (mContentType == type);
504    }
505
506    /*
507     * Apps PagedView implementation
508     */
509    private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
510        int childCount = layout.getChildCount();
511        for (int i = 0; i < childCount; ++i) {
512            layout.getChildAt(i).setVisibility(visibility);
513        }
514    }
515    private void setupPage(PagedViewCellLayout layout) {
516        layout.setCellCount(mCellCountX, mCellCountY);
517        layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
518        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
519                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
520
521        // Note: We force a measure here to get around the fact that when we do layout calculations
522        // immediately after syncing, we don't have a proper width.  That said, we already know the
523        // expected page width, so we can actually optimize by hiding all the TextView-based
524        // children that are expensive to measure, and let that happen naturally later.
525        setVisibilityOnChildren(layout, View.GONE);
526        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
527        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
528        layout.setMinimumWidth(getPageContentWidth());
529        layout.measure(widthSpec, heightSpec);
530        setVisibilityOnChildren(layout, View.VISIBLE);
531    }
532    public void syncAppsPages() {
533        // Ensure that we have the right number of pages
534        Context context = getContext();
535        int numPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
536        for (int i = 0; i < numPages; ++i) {
537            PagedViewCellLayout layout = new PagedViewCellLayout(context);
538            setupPage(layout);
539            addView(layout);
540        }
541    }
542    public void syncAppsPageItems(int page) {
543        // ensure that we have the right number of items on the pages
544        int numPages = getPageCount();
545        int numCells = mCellCountX * mCellCountY;
546        int startIndex = page * numCells;
547        int endIndex = Math.min(startIndex + numCells, mApps.size());
548        PagedViewCellLayout layout = (PagedViewCellLayout) getChildAt(page);
549
550        layout.removeAllViewsOnPage();
551        ArrayList<Object> items = new ArrayList<Object>();
552        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
553        for (int i = startIndex; i < endIndex; ++i) {
554            ApplicationInfo info = mApps.get(i);
555            PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
556                    R.layout.apps_customize_application, layout, false);
557            icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper);
558            icon.setOnClickListener(this);
559            icon.setOnLongClickListener(this);
560            icon.setOnTouchListener(this);
561
562            int index = i - startIndex;
563            int x = index % mCellCountX;
564            int y = index / mCellCountX;
565            layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
566
567            items.add(info);
568            images.add(info.iconBitmap);
569        }
570
571        // Create the hardware layers
572        layout.allowHardwareLayerCreation();
573        layout.createHardwareLayers();
574
575        prepareGenerateHoloOutlinesTask(page, items, images);
576    }
577
578    /**
579     * Return the appropriate thread priority for loading for a given page (we give the current
580     * page much higher priority)
581     */
582    private int getThreadPriorityForPage(int page) {
583        // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
584        int pageDiff = Math.abs(page - mCurrentPage);
585        if (pageDiff <= 0) {
586            // return Process.THREAD_PRIORITY_DEFAULT;
587            return Process.THREAD_PRIORITY_MORE_FAVORABLE;
588        } else if (pageDiff <= 1) {
589            // return Process.THREAD_PRIORITY_BACKGROUND;
590            return Process.THREAD_PRIORITY_DEFAULT;
591        } else {
592            // return Process.THREAD_PRIORITY_LOWEST;
593            return Process.THREAD_PRIORITY_DEFAULT;
594        }
595    }
596    /**
597     * Creates and executes a new AsyncTask to load a page of widget previews.
598     */
599    private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
600            int cellWidth, int cellHeight, int cellCountX) {
601        // Prune all tasks that are no longer needed
602        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
603        while (iter.hasNext()) {
604            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
605            int taskPage = task.page;
606            if ((taskPage == page) ||
607                    taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
608                    taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
609                task.cancel(false);
610                iter.remove();
611            } else {
612                task.setThreadPriority(getThreadPriorityForPage(taskPage));
613            }
614        }
615
616        AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
617            cellCountX, new AsyncTaskCallback() {
618                @Override
619                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
620                    // Ensure that this task starts running at the correct priority
621                    task.syncThreadPriority();
622
623                    // Load each of the widget/shortcut previews
624                    ArrayList<Object> items = data.items;
625                    ArrayList<Bitmap> images = data.generatedImages;
626                    int count = items.size();
627                    int cellWidth = data.cellWidth;
628                    int cellHeight = data.cellHeight;
629                    for (int i = 0; i < count && !task.isCancelled(); ++i) {
630                        // Before work on each item, ensure that this task is running at the correct
631                        // priority
632                        task.syncThreadPriority();
633
634                        Object rawInfo = items.get(i);
635                        if (rawInfo instanceof AppWidgetProviderInfo) {
636                            AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
637                            int[] cellSpans = CellLayout.rectToCell(getResources(),
638                                    info.minWidth, info.minHeight, null);
639                            images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1],
640                                    cellWidth, cellHeight));
641                        } else if (rawInfo instanceof ResolveInfo) {
642                            // Fill in the shortcuts information
643                            ResolveInfo info = (ResolveInfo) rawInfo;
644                            images.add(getShortcutPreview(info, cellWidth, cellHeight));
645                        }
646                    }
647                }
648            },
649            new AsyncTaskCallback() {
650                @Override
651                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
652                    mRunningTasks.remove(task);
653                    if (task.isCancelled()) return;
654                    if (task.page > getPageCount()) return;
655                    if (task.pageContentType != mContentType) return;
656                    onSyncWidgetPageItems(data);
657                }
658        });
659
660        // Ensure that the task is appropriately prioritized and runs in parallel
661        AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, mContentType,
662                AsyncTaskPageData.Type.LoadWidgetPreviewData);
663        t.setThreadPriority(getThreadPriorityForPage(page));
664        t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
665        mRunningTasks.add(t);
666    }
667    /**
668     * Creates and executes a new AsyncTask to load the outlines for a page of content.
669     */
670    private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items,
671            ArrayList<Bitmap> images) {
672        // Prune old tasks for this page
673        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
674        while (iter.hasNext()) {
675            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
676            int taskPage = task.page;
677            if ((taskPage == page) &&
678                    (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) {
679                task.cancel(false);
680                iter.remove();
681            }
682        }
683
684        AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images,
685            new AsyncTaskCallback() {
686                @Override
687                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
688                    // Ensure that this task starts running at the correct priority
689                    task.syncThreadPriority();
690
691                    ArrayList<Bitmap> images = data.generatedImages;
692                    ArrayList<Bitmap> srcImages = data.sourceImages;
693                    int count = srcImages.size();
694                    Canvas c = new Canvas();
695                    for (int i = 0; i < count && !task.isCancelled(); ++i) {
696                        // Before work on each item, ensure that this task is running at the correct
697                        // priority
698                        task.syncThreadPriority();
699
700                        Bitmap b = srcImages.get(i);
701                        Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(),
702                                Bitmap.Config.ARGB_8888);
703
704                        c.setBitmap(outline);
705                        c.save();
706                        c.drawBitmap(b, 0, 0, null);
707                        c.restore();
708
709                        images.add(outline);
710                    }
711                }
712            },
713            new AsyncTaskCallback() {
714                @Override
715                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
716                    mRunningTasks.remove(task);
717                    if (task.isCancelled()) return;
718                    if (task.page > getPageCount()) return;
719                    if (task.pageContentType != mContentType) return;
720                    onHolographicPageItemsLoaded(data);
721                }
722            });
723
724        // Ensure that the outline task always runs in the background, serially
725        AppsCustomizeAsyncTask t =
726            new AppsCustomizeAsyncTask(page, mContentType,
727                    AsyncTaskPageData.Type.LoadHolographicIconsData);
728        t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
729        t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData);
730        mRunningTasks.add(t);
731    }
732
733    /*
734     * Widgets PagedView implementation
735     */
736    private void setupPage(PagedViewGridLayout layout) {
737        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
738                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
739
740        // Note: We force a measure here to get around the fact that when we do layout calculations
741        // immediately after syncing, we don't have a proper width.
742        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
743        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
744        layout.setMinimumWidth(getPageContentWidth());
745        layout.measure(widthSpec, heightSpec);
746    }
747    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
748            float scaleX, float scaleY) {
749        if (bitmap != null) {
750            Canvas c = new Canvas(bitmap);
751            c.scale(scaleX, scaleY);
752            Rect oldBounds = d.copyBounds();
753            d.setBounds(x, y, x + w, y + h);
754            d.draw(c);
755            d.setBounds(oldBounds); // Restore the bounds
756        }
757    }
758    private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) {
759        // Render the icon
760        Bitmap preview = Bitmap.createBitmap(cellWidth, mAppIconSize, Config.ARGB_8888);
761        Drawable icon = mIconCache.getFullResIcon(info, mPackageManager);
762        renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize, 1f, 1f);
763        return preview;
764    }
765    private Bitmap getWidgetPreview(AppWidgetProviderInfo info,
766            int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) {
767
768        // Calculate the size of the drawable
769        cellHSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellHSpan));
770        cellVSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellVSpan));
771        int expectedWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan);
772        int expectedHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan);
773
774        // Scale down the bitmap to fit the space
775        float widgetPreviewScale = (float) cellWidth / expectedWidth;
776        expectedWidth = (int) (widgetPreviewScale * expectedWidth);
777        expectedHeight = (int) (widgetPreviewScale * expectedHeight);
778
779        // Load the preview image if possible
780        String packageName = info.provider.getPackageName();
781        Drawable drawable = null;
782        Bitmap preview = null;
783        if (info.previewImage != 0) {
784            drawable = mPackageManager.getDrawable(packageName, info.previewImage, null);
785            if (drawable == null) {
786                Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon)
787                        + " for provider: " + info.provider);
788            } else {
789                // Scale down the preview to the dimensions we want
790                int imageWidth = drawable.getIntrinsicWidth();
791                int imageHeight = drawable.getIntrinsicHeight();
792                float aspect = (float) imageWidth / imageHeight;
793                int newWidth = imageWidth;
794                int newHeight = imageHeight;
795                if (aspect > 1f) {
796                    newWidth = expectedWidth;
797                    newHeight = (int) (imageHeight * ((float) expectedWidth / imageWidth));
798                } else {
799                    newHeight = expectedHeight;
800                    newWidth = (int) (imageWidth * ((float) expectedHeight / imageHeight));
801                }
802
803                preview = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
804                renderDrawableToBitmap(drawable, preview, 0, 0, newWidth, newHeight, 1f, 1f);
805            }
806        }
807
808        // Generate a preview image if we couldn't load one
809        if (drawable == null) {
810            Resources resources = mLauncher.getResources();
811            int bitmapWidth;
812            int bitmapHeight;
813
814            // Specify the dimensions of the bitmap (since we are using a default preview bg with
815            // the full icon, we only imply the aspect ratio of the widget)
816            if (cellHSpan == cellVSpan) {
817                bitmapWidth = bitmapHeight = cellWidth;
818                expectedWidth = expectedHeight = mWidgetPreviewIconPaddedDimension;
819            } else if (cellHSpan >= cellVSpan) {
820                bitmapWidth = expectedWidth = cellWidth;
821                bitmapHeight = expectedHeight = mWidgetPreviewIconPaddedDimension;
822            } else {
823                // Note that in vertical widgets, we might not have enough space due to the text
824                // label, so be conservative and use the width as a height bound
825                bitmapWidth = expectedWidth = mWidgetPreviewIconPaddedDimension;
826                bitmapHeight = expectedHeight = cellWidth;
827            }
828
829            preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
830            renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, expectedWidth,
831                    expectedHeight, 1f,1f);
832
833            // Draw the icon in the top left corner
834            try {
835                Drawable icon = null;
836                if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null);
837                if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application);
838
839                int offset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
840                renderDrawableToBitmap(icon, preview, offset, offset,
841                        mAppIconSize, mAppIconSize, 1f, 1f);
842            } catch (Resources.NotFoundException e) {}
843        }
844        return preview;
845    }
846    public void syncWidgetPages() {
847        // Ensure that we have the right number of pages
848        Context context = getContext();
849        int[] countX = { mWidgetCountX, mShortcutCountX };
850        int[] countY = { mWidgetCountY, mShortcutCountY };
851        Object[] collection = { mWidgets, mShortcuts };
852        for (int i = 0; i < 2; ++i) {
853            ArrayList<Object> list = (ArrayList<Object>) collection[i];
854            int numItemsPerPage = countX[i] * countY[i];
855            int numItemPages = (int) Math.ceil(list.size() / (float) numItemsPerPage);
856            for (int j = 0; j < numItemPages; ++j) {
857                PagedViewGridLayout layout = new PagedViewGridLayout(context, countX[i],
858                        countY[i]);
859                setupPage(layout);
860                addView(layout);
861            }
862        }
863    }
864    public void syncWidgetPageItems(int page) {
865        int[] countX = { mWidgetCountX, mShortcutCountX };
866        int[] countY = { mWidgetCountY, mShortcutCountY };
867        int[] widthGap = { mWidgetWidthGap, mWidgetWidthGap };
868        int[] heightGap = { mWidgetHeightGap, mWidgetHeightGap };
869        int[] numItemsPerPage = { mWidgetCountX * mWidgetCountY,
870                mShortcutCountX * mShortcutCountY };
871        Object[] collection = { mWidgets, mShortcuts };
872        int contentWidth = mWidgetSpacingLayout.getContentWidth();
873        int contentHeight = mWidgetSpacingLayout.getContentHeight();
874        int numWidgetPages = (int) Math.ceil(mWidgets.size() / (float) numItemsPerPage[0]);
875        int[] offsets = { page * numItemsPerPage[0], (page - numWidgetPages) * numItemsPerPage[1] };
876        int index = (page < numWidgetPages ? 0 : 1);
877
878        // Calculate the dimensions of each cell we are giving to each widget
879        ArrayList<Object> list = (ArrayList<Object>) collection[index];
880        ArrayList<Object> items = new ArrayList<Object>();
881        int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
882                - ((countX[index] - 1) * widthGap[index])) / countX[index]);
883        int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
884                - ((countY[index] - 1) * heightGap[index])) / countY[index]);
885
886        int offset = offsets[index];
887        for (int i = offset; i < Math.min(offset + numItemsPerPage[index], list.size()); ++i) {
888            items.add(list.get(i));
889        }
890
891        prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, countX[index]);
892    }
893    private void onSyncWidgetPageItems(AsyncTaskPageData data) {
894        int page = data.page;
895        PagedViewGridLayout layout = (PagedViewGridLayout) getChildAt(page);
896        // Only set the column count once we have items
897        layout.setColumnCount(layout.getCellCountX());
898
899        ArrayList<Object> items = data.items;
900        int count = items.size();
901        int cellWidth = data.cellWidth;
902        int cellHeight = data.cellHeight;
903        int cellCountX = data.cellCountX;
904        for (int i = 0; i < count; ++i) {
905            Object rawInfo = items.get(i);
906            PendingAddItemInfo createItemInfo = null;
907            PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
908                    R.layout.apps_customize_widget, layout, false);
909            if (rawInfo instanceof AppWidgetProviderInfo) {
910                // Fill in the widget information
911                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
912                createItemInfo = new PendingAddWidgetInfo(info, null, null);
913                int[] cellSpans = CellLayout.rectToCell(getResources(),
914                        info.minWidth, info.minHeight, null);
915                FastBitmapDrawable preview = new FastBitmapDrawable(data.generatedImages.get(i));
916                widget.applyFromAppWidgetProviderInfo(info, preview, -1, cellSpans,
917                        mHolographicOutlineHelper);
918                widget.setTag(createItemInfo);
919            } else if (rawInfo instanceof ResolveInfo) {
920                // Fill in the shortcuts information
921                ResolveInfo info = (ResolveInfo) rawInfo;
922                createItemInfo = new PendingAddItemInfo();
923                createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
924                createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
925                        info.activityInfo.name);
926                FastBitmapDrawable preview = new FastBitmapDrawable(data.generatedImages.get(i));
927                widget.applyFromResolveInfo(mPackageManager, info, preview,
928                        mHolographicOutlineHelper);
929                widget.setTag(createItemInfo);
930            }
931            widget.setOnClickListener(this);
932            widget.setOnLongClickListener(this);
933            widget.setOnTouchListener(this);
934
935            // Layout each widget
936            int ix = i % cellCountX;
937            int iy = i / cellCountX;
938            GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
939                    GridLayout.spec(iy, GridLayout.LEFT, GridLayout.CAN_STRETCH),
940                    GridLayout.spec(ix, GridLayout.TOP, GridLayout.CAN_STRETCH));
941            lp.width = cellWidth;
942            lp.height = cellHeight;
943            if (ix > 0) lp.leftMargin = mWidgetWidthGap;
944            if (iy > 0) lp.topMargin = mWidgetHeightGap;
945            layout.addView(widget, lp);
946        }
947
948        invalidate();
949        forceUpdateAdjacentPagesAlpha();
950        prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages);
951    }
952    private void onHolographicPageItemsLoaded(AsyncTaskPageData data) {
953        // Invalidate early to short-circuit children invalidates
954        invalidate();
955
956        int page = data.page;
957        ViewGroup layout = (ViewGroup) getChildAt(page);
958        if (layout instanceof PagedViewCellLayout) {
959            PagedViewCellLayout cl = (PagedViewCellLayout) layout;
960            int count = cl.getPageChildCount();
961            if (count != data.generatedImages.size()) return;
962            for (int i = 0; i < count; ++i) {
963                PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i);
964                icon.setHolographicOutline(data.generatedImages.get(i));
965            }
966        } else {
967            int count = layout.getChildCount();
968            if (count != data.generatedImages.size()) return;
969            for (int i = 0; i < count; ++i) {
970                View v = layout.getChildAt(i);
971                ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i));
972            }
973        }
974    }
975
976    @Override
977    public void syncPages() {
978        removeAllViews();
979
980        // Remove all background asyc tasks if we are loading content anew
981        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
982        while (iter.hasNext()) {
983            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
984            task.cancel(false);
985            iter.remove();
986        }
987
988        switch (mContentType) {
989        case Applications:
990            syncAppsPages();
991            break;
992        case Widgets:
993            syncWidgetPages();
994            break;
995        }
996    }
997    @Override
998    public void syncPageItems(int page) {
999        switch (mContentType) {
1000        case Applications:
1001            syncAppsPageItems(page);
1002            break;
1003        case Widgets:
1004            syncWidgetPageItems(page);
1005            break;
1006        }
1007    }
1008
1009    /**
1010     * Used by the parent to get the content width to set the tab bar to
1011     * @return
1012     */
1013    public int getPageContentWidth() {
1014        return mContentWidth;
1015    }
1016
1017    @Override
1018    protected void onPageBeginMoving() {
1019        /* TO BE ENABLED LATER
1020        setChildrenDrawnWithCacheEnabled(true);
1021        for (int i = 0; i < getChildCount(); ++i) {
1022            View v = getChildAt(i);
1023            if (v instanceof PagedViewCellLayout) {
1024                ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(true);
1025            }
1026        }
1027        */
1028        super.onPageBeginMoving();
1029    }
1030
1031    @Override
1032    protected void onPageEndMoving() {
1033        /* TO BE ENABLED LATER
1034        for (int i = 0; i < getChildCount(); ++i) {
1035            View v = getChildAt(i);
1036            if (v instanceof PagedViewCellLayout) {
1037                ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(false);
1038            }
1039        }
1040        setChildrenDrawnWithCacheEnabled(false);
1041        */
1042        super.onPageEndMoving();
1043    }
1044
1045    /*
1046     * AllAppsView implementation
1047     */
1048    @Override
1049    public void setup(Launcher launcher, DragController dragController) {
1050        mLauncher = launcher;
1051        mDragController = dragController;
1052    }
1053    @Override
1054    public void zoom(float zoom, boolean animate) {
1055        // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1056    }
1057    @Override
1058    public boolean isVisible() {
1059        return (getVisibility() == VISIBLE);
1060    }
1061    @Override
1062    public boolean isAnimating() {
1063        return false;
1064    }
1065    @Override
1066    public void setApps(ArrayList<ApplicationInfo> list) {
1067        mApps = list;
1068        Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
1069
1070        // The next layout pass will trigger data-ready if both widgets and apps are set, so
1071        // request a layout to do this test and invalidate the page data when ready.
1072        if (testDataReady()) requestLayout();
1073    }
1074    private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1075        // We add it in place, in alphabetical order
1076        int count = list.size();
1077        for (int i = 0; i < count; ++i) {
1078            ApplicationInfo info = list.get(i);
1079            int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1080            if (index < 0) {
1081                mApps.add(-(index + 1), info);
1082            }
1083        }
1084    }
1085    @Override
1086    public void addApps(ArrayList<ApplicationInfo> list) {
1087        addAppsWithoutInvalidate(list);
1088        invalidatePageData();
1089    }
1090    private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1091        ComponentName removeComponent = item.intent.getComponent();
1092        int length = list.size();
1093        for (int i = 0; i < length; ++i) {
1094            ApplicationInfo info = list.get(i);
1095            if (info.intent.getComponent().equals(removeComponent)) {
1096                return i;
1097            }
1098        }
1099        return -1;
1100    }
1101    private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1102        // loop through all the apps and remove apps that have the same component
1103        int length = list.size();
1104        for (int i = 0; i < length; ++i) {
1105            ApplicationInfo info = list.get(i);
1106            int removeIndex = findAppByComponent(mApps, info);
1107            if (removeIndex > -1) {
1108                mApps.remove(removeIndex);
1109            }
1110        }
1111    }
1112    @Override
1113    public void removeApps(ArrayList<ApplicationInfo> list) {
1114        removeAppsWithoutInvalidate(list);
1115        invalidatePageData();
1116    }
1117    @Override
1118    public void updateApps(ArrayList<ApplicationInfo> list) {
1119        // We remove and re-add the updated applications list because it's properties may have
1120        // changed (ie. the title), and this will ensure that the items will be in their proper
1121        // place in the list.
1122        removeAppsWithoutInvalidate(list);
1123        addAppsWithoutInvalidate(list);
1124        invalidatePageData();
1125    }
1126
1127    @Override
1128    public void reset() {
1129        if (mContentType != ContentType.Applications) {
1130            // Reset to the first page of the Apps pane
1131            AppsCustomizeTabHost tabs = (AppsCustomizeTabHost)
1132                    mLauncher.findViewById(R.id.apps_customize_pane);
1133            tabs.setCurrentTabByTag(tabs.getTabTagForContentType(ContentType.Applications));
1134        } else if (getCurrentPage() != 0) {
1135            setCurrentPage(0);
1136            invalidatePageData();
1137        }
1138    }
1139    @Override
1140    public void dumpState() {
1141        // TODO: Dump information related to current list of Applications, Widgets, etc.
1142        ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps);
1143        dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets);
1144        dumpAppWidgetProviderInfoList(LOG_TAG, "mShortcuts", mShortcuts);
1145    }
1146    private void dumpAppWidgetProviderInfoList(String tag, String label,
1147            ArrayList<Object> list) {
1148        Log.d(tag, label + " size=" + list.size());
1149        for (Object i: list) {
1150            if (i instanceof AppWidgetProviderInfo) {
1151                AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1152                Log.d(tag, "   label=\"" + info.label + "\" previewImage=" + info.previewImage
1153                        + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1154                        + " initialLayout=" + info.initialLayout
1155                        + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1156            } else if (i instanceof ResolveInfo) {
1157                ResolveInfo info = (ResolveInfo) i;
1158                Log.d(tag, "   label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1159                        + info.icon);
1160            }
1161        }
1162    }
1163    @Override
1164    public void surrender() {
1165        // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1166        // should stop this now.
1167    }
1168
1169    /*
1170     * We load an extra page on each side to prevent flashes from scrolling and loading of the
1171     * widget previews in the background with the AsyncTasks.
1172     */
1173    protected int getAssociatedLowerPageBound(int page) {
1174        return Math.max(0, page - 2);
1175    }
1176    protected int getAssociatedUpperPageBound(int page) {
1177        final int count = getChildCount();
1178        return Math.min(page + 2, count - 1);
1179    }
1180
1181    @Override
1182    protected String getCurrentPageDescription() {
1183        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1184        int stringId = R.string.default_scroll_format;
1185        switch (mContentType) {
1186        case Applications:
1187            stringId = R.string.apps_customize_apps_scroll_format;
1188            break;
1189        case Widgets:
1190            stringId = R.string.apps_customize_widgets_scroll_format;
1191            break;
1192        }
1193        return String.format(mContext.getString(stringId), page + 1, getChildCount());
1194    }
1195}
1196