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