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