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