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