AppsCustomizePagedView.java revision 6a877403542c71c1b6228c429bc060755f5f847b
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.Canvas;
35import android.graphics.PorterDuff;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Bitmap.Config;
39import android.graphics.drawable.Drawable;
40import android.os.AsyncTask;
41import android.os.Process;
42import android.util.AttributeSet;
43import android.util.Log;
44import android.view.Gravity;
45import android.view.LayoutInflater;
46import android.view.MotionEvent;
47import android.view.View;
48import android.view.ViewGroup;
49import android.view.animation.AccelerateInterpolator;
50import android.view.animation.DecelerateInterpolator;
51import android.view.animation.Interpolator;
52import android.widget.GridLayout;
53import android.widget.ImageView;
54import android.widget.Toast;
55
56import com.android.launcher.R;
57import com.android.launcher2.DropTarget.DragObject;
58
59import java.util.ArrayList;
60import java.util.Collections;
61import java.util.Iterator;
62import java.util.List;
63
64/**
65 * A simple callback interface which also provides the results of the task.
66 */
67interface AsyncTaskCallback {
68    void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
69}
70
71/**
72 * The data needed to perform either of the custom AsyncTasks.
73 */
74class AsyncTaskPageData {
75    enum Type {
76        LoadWidgetPreviewData,
77        LoadHolographicIconsData
78    }
79
80    AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
81            AsyncTaskCallback postR) {
82        page = p;
83        items = l;
84        sourceImages = si;
85        generatedImages = new ArrayList<Bitmap>();
86        cellWidth = cellHeight = -1;
87        doInBackgroundCallback = bgR;
88        postExecuteCallback = postR;
89    }
90    AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR,
91            AsyncTaskCallback postR) {
92        page = p;
93        items = l;
94        generatedImages = new ArrayList<Bitmap>();
95        cellWidth = cw;
96        cellHeight = ch;
97        cellCountX = ccx;
98        doInBackgroundCallback = bgR;
99        postExecuteCallback = postR;
100    }
101    void cleanup(boolean cancelled) {
102        // Clean up any references to source/generated bitmaps
103        if (sourceImages != null) {
104            if (cancelled) {
105                for (Bitmap b : sourceImages) {
106                    b.recycle();
107                }
108            }
109            sourceImages.clear();
110        }
111        if (generatedImages != null) {
112            if (cancelled) {
113                for (Bitmap b : generatedImages) {
114                    b.recycle();
115                }
116            }
117            generatedImages.clear();
118        }
119    }
120    int page;
121    ArrayList<Object> items;
122    ArrayList<Bitmap> sourceImages;
123    ArrayList<Bitmap> generatedImages;
124    int cellWidth;
125    int cellHeight;
126    int cellCountX;
127    AsyncTaskCallback doInBackgroundCallback;
128    AsyncTaskCallback postExecuteCallback;
129}
130
131/**
132 * A generic template for an async task used in AppsCustomize.
133 */
134class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
135    AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) {
136        page = p;
137        threadPriority = Process.THREAD_PRIORITY_DEFAULT;
138        dataType = ty;
139    }
140    @Override
141    protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
142        if (params.length != 1) return null;
143        // Load each of the widget previews in the background
144        params[0].doInBackgroundCallback.run(this, params[0]);
145        return params[0];
146    }
147    @Override
148    protected void onPostExecute(AsyncTaskPageData result) {
149        // All the widget previews are loaded, so we can just callback to inflate the page
150        result.postExecuteCallback.run(this, result);
151    }
152
153    void setThreadPriority(int p) {
154        threadPriority = p;
155    }
156    void syncThreadPriority() {
157        Process.setThreadPriority(threadPriority);
158    }
159
160    // The page that this async task is associated with
161    AsyncTaskPageData.Type dataType;
162    int page;
163    int threadPriority;
164}
165
166/**
167 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
168 */
169public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
170        AllAppsView, View.OnClickListener, DragSource {
171    static final String LOG_TAG = "AppsCustomizePagedView";
172
173    /**
174     * The different content types that this paged view can show.
175     */
176    public enum ContentType {
177        Applications,
178        Widgets
179    }
180
181    // Refs
182    private Launcher mLauncher;
183    private DragController mDragController;
184    private final LayoutInflater mLayoutInflater;
185    private final PackageManager mPackageManager;
186
187    // Save and Restore
188    private int mSaveInstanceStateItemIndex = -1;
189
190    // Content
191    private ArrayList<ApplicationInfo> mApps;
192    private ArrayList<Object> mWidgets;
193
194    // Cling
195    private int mClingFocusedX;
196    private int mClingFocusedY;
197
198    // Caching
199    private Canvas mCanvas;
200    private Drawable mDefaultWidgetBackground;
201    private IconCache mIconCache;
202    private int mDragViewMultiplyColor;
203
204    // Dimens
205    private int mContentWidth;
206    private int mAppIconSize;
207    private int mWidgetCountX, mWidgetCountY;
208    private int mWidgetWidthGap, mWidgetHeightGap;
209    private final int mWidgetPreviewIconPaddedDimension;
210    private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
211    private PagedViewCellLayout mWidgetSpacingLayout;
212    private int mNumAppsPages;
213    private int mNumWidgetPages;
214
215    // Relating to the scroll and overscroll effects
216    Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f);
217    private static float CAMERA_DISTANCE = 6500;
218    private static float TRANSITION_SCALE_FACTOR = 0.74f;
219    private static float TRANSITION_PIVOT = 0.65f;
220    private static float TRANSITION_MAX_ROTATION = 22;
221    private static final boolean PERFORM_OVERSCROLL_ROTATION = true;
222    private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f);
223    private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4);
224
225    // Previews & outlines
226    ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
227    private HolographicOutlineHelper mHolographicOutlineHelper;
228    private static final int sPageSleepDelay = 150;
229
230    public AppsCustomizePagedView(Context context, AttributeSet attrs) {
231        super(context, attrs);
232        mLayoutInflater = LayoutInflater.from(context);
233        mPackageManager = context.getPackageManager();
234        mApps = new ArrayList<ApplicationInfo>();
235        mWidgets = new ArrayList<Object>();
236        mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
237        mHolographicOutlineHelper = new HolographicOutlineHelper();
238        mCanvas = new Canvas();
239        mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
240
241        // Save the default widget preview background
242        Resources resources = context.getResources();
243        mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo);
244        mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
245        mDragViewMultiplyColor = resources.getColor(R.color.drag_view_multiply_color);
246
247        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0);
248        // TODO-APPS_CUSTOMIZE: remove these unnecessary attrs after
249        mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6);
250        mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4);
251        a.recycle();
252        a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
253        mWidgetWidthGap =
254            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
255        mWidgetHeightGap =
256            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
257        mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
258        mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
259        mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0);
260        mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0);
261        a.recycle();
262        mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
263
264        // The padding on the non-matched dimension for the default widget preview icons
265        // (top + bottom)
266        mWidgetPreviewIconPaddedDimension =
267            (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage)));
268        mFadeInAdjacentScreens = false;
269    }
270
271    @Override
272    protected void init() {
273        super.init();
274        mCenterPagesVertically = false;
275
276        Context context = getContext();
277        Resources r = context.getResources();
278        setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
279    }
280
281    @Override
282    protected void onUnhandledTap(MotionEvent ev) {
283        if (LauncherApplication.isScreenLarge()) {
284            // Dismiss AppsCustomize if we tap
285            mLauncher.showWorkspace(true);
286        }
287    }
288
289    /** Returns the item index of the center item on this page so that we can restore to this
290     *  item index when we rotate. */
291    private int getMiddleComponentIndexOnCurrentPage() {
292        int i = -1;
293        if (getPageCount() > 0) {
294            int currentPage = getCurrentPage();
295            if (currentPage < mNumAppsPages) {
296                PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage);
297                PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout();
298                int numItemsPerPage = mCellCountX * mCellCountY;
299                int childCount = childrenLayout.getChildCount();
300                if (childCount > 0) {
301                    i = (currentPage * numItemsPerPage) + (childCount / 2);
302                }
303            } else {
304                int numApps = mApps.size();
305                PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage);
306                int numItemsPerPage = mWidgetCountX * mWidgetCountY;
307                int childCount = layout.getChildCount();
308                if (childCount > 0) {
309                    i = numApps +
310                        ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2);
311                }
312            }
313        }
314        return i;
315    }
316
317    /** Get the index of the item to restore to if we need to restore the current page. */
318    int getSaveInstanceStateIndex() {
319        if (mSaveInstanceStateItemIndex == -1) {
320            mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage();
321        }
322        return mSaveInstanceStateItemIndex;
323    }
324
325    /** Returns the page in the current orientation which is expected to contain the specified
326     *  item index. */
327    int getPageForComponent(int index) {
328        if (index < 0) return 0;
329
330        if (index < mApps.size()) {
331            int numItemsPerPage = mCellCountX * mCellCountY;
332            return (index / numItemsPerPage);
333        } else {
334            int numItemsPerPage = mWidgetCountX * mWidgetCountY;
335            return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage);
336        }
337    }
338
339    /**
340     * This differs from isDataReady as this is the test done if isDataReady is not set.
341     */
342    private boolean testDataReady() {
343        // We only do this test once, and we default to the Applications page, so we only really
344        // have to wait for there to be apps.
345        // TODO: What if one of them is validly empty
346        return !mApps.isEmpty() && !mWidgets.isEmpty();
347    }
348
349    /** Restores the page for an item at the specified index */
350    void restorePageForIndex(int index) {
351        if (index < 0) return;
352        mSaveInstanceStateItemIndex = index;
353    }
354
355    private void updatePageCounts() {
356        mNumWidgetPages = (int) Math.ceil(mWidgets.size() /
357                (float) (mWidgetCountX * mWidgetCountY));
358        mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
359    }
360
361    protected void onDataReady(int width, int height) {
362        // Note that we transpose the counts in portrait so that we get a similar layout
363        boolean isLandscape = getResources().getConfiguration().orientation ==
364            Configuration.ORIENTATION_LANDSCAPE;
365        int maxCellCountX = Integer.MAX_VALUE;
366        int maxCellCountY = Integer.MAX_VALUE;
367        if (LauncherApplication.isScreenLarge()) {
368            maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
369                LauncherModel.getCellCountY());
370            maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
371                LauncherModel.getCellCountX());
372        }
373
374        // Now that the data is ready, we can calculate the content width, the number of cells to
375        // use for each page
376        mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
377        mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
378                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
379        mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
380        mCellCountX = mWidgetSpacingLayout.getCellCountX();
381        mCellCountY = mWidgetSpacingLayout.getCellCountY();
382        updatePageCounts();
383
384        // Force a measure to update recalculate the gaps
385        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
386        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
387        mWidgetSpacingLayout.measure(widthSpec, heightSpec);
388        mContentWidth = mWidgetSpacingLayout.getContentWidth();
389
390        // Restore the page
391        int page = getPageForComponent(mSaveInstanceStateItemIndex);
392        invalidatePageData(Math.max(0, page));
393
394        // Calculate the position for the cling punch through
395        int[] offset = new int[2];
396        int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY);
397        mLauncher.getDragLayer().getLocationInDragLayer(this, offset);
398        pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 + offset[0];
399        pos[1] += (getMeasuredHeight() - mWidgetSpacingLayout.getMeasuredHeight()) / 2 + offset[1];
400        mLauncher.showFirstRunAllAppsCling(pos);
401
402    }
403
404    @Override
405    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
406        int width = MeasureSpec.getSize(widthMeasureSpec);
407        int height = MeasureSpec.getSize(heightMeasureSpec);
408        if (!isDataReady()) {
409            if (testDataReady()) {
410                setDataIsReady();
411                setMeasuredDimension(width, height);
412                onDataReady(width, height);
413            }
414        }
415
416        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
417    }
418
419    /** Removes and returns the ResolveInfo with the specified ComponentName */
420    private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list,
421            ComponentName cn) {
422        Iterator<ResolveInfo> iter = list.iterator();
423        while (iter.hasNext()) {
424            ResolveInfo rinfo = iter.next();
425            ActivityInfo info = rinfo.activityInfo;
426            ComponentName c = new ComponentName(info.packageName, info.name);
427            if (c.equals(cn)) {
428                iter.remove();
429                return rinfo;
430            }
431        }
432        return null;
433    }
434
435    public void onPackagesUpdated() {
436        // TODO: this isn't ideal, but we actually need to delay here. This call is triggered
437        // by a broadcast receiver, and in order for it to work correctly, we need to know that
438        // the AppWidgetService has already received and processed the same broadcast. Since there
439        // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally,
440        // we should have a more precise way of ensuring the AppWidgetService is up to date.
441        postDelayed(new Runnable() {
442           public void run() {
443               updatePackages();
444           }
445        }, 500);
446    }
447
448    public void updatePackages() {
449        // Get the list of widgets and shortcuts
450        boolean wasEmpty = mWidgets.isEmpty();
451        mWidgets.clear();
452        List<AppWidgetProviderInfo> widgets =
453            AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
454        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
455        List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
456        mWidgets.addAll(widgets);
457        mWidgets.addAll(shortcuts);
458        Collections.sort(mWidgets,
459                new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
460        updatePageCounts();
461
462        if (wasEmpty) {
463            // The next layout pass will trigger data-ready if both widgets and apps are set, so request
464            // a layout to do this test and invalidate the page data when ready.
465            if (testDataReady()) requestLayout();
466        } else {
467            cancelAllTasks();
468            invalidatePageData();
469        }
470    }
471
472    @Override
473    public void onClick(View v) {
474        // When we have exited all apps or are in transition, disregard clicks
475        if (!mLauncher.isAllAppsCustomizeOpen() ||
476                mLauncher.getWorkspace().isSwitchingState()) return;
477
478        if (v instanceof PagedViewIcon) {
479            // Animate some feedback to the click
480            final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
481            animateClickFeedback(v, new Runnable() {
482                @Override
483                public void run() {
484                    mLauncher.startActivitySafely(appInfo.intent, appInfo);
485                }
486            });
487        } else if (v instanceof PagedViewWidget) {
488            // Let the user know that they have to long press to add a widget
489            Toast.makeText(getContext(), R.string.long_press_widget_to_add,
490                    Toast.LENGTH_SHORT).show();
491
492            // Create a little animation to show that the widget can move
493            float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
494            final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
495            AnimatorSet bounce = new AnimatorSet();
496            ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
497            tyuAnim.setDuration(125);
498            ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
499            tydAnim.setDuration(100);
500            bounce.play(tyuAnim).before(tydAnim);
501            bounce.setInterpolator(new AccelerateInterpolator());
502            bounce.start();
503        }
504    }
505
506    /*
507     * PagedViewWithDraggableItems implementation
508     */
509    @Override
510    protected void determineDraggingStart(android.view.MotionEvent ev) {
511        // Disable dragging by pulling an app down for now.
512    }
513
514    private void beginDraggingApplication(View v) {
515        mLauncher.getWorkspace().onDragStartedWithItem(v);
516        mLauncher.getWorkspace().beginDragShared(v, this);
517    }
518
519    private void beginDraggingWidget(View v) {
520        // Get the widget preview as the drag representation
521        ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
522        PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
523
524        // Compose the drag image
525        Bitmap b;
526        Drawable preview = image.getDrawable();
527        RectF mTmpScaleRect = new RectF(0f,0f,1f,1f);
528        image.getImageMatrix().mapRect(mTmpScaleRect);
529        float scale = mTmpScaleRect.right;
530        int w = (int) (preview.getIntrinsicWidth() * scale);
531        int h = (int) (preview.getIntrinsicHeight() * scale);
532        if (createItemInfo instanceof PendingAddWidgetInfo) {
533            PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo;
534            int[] spanXY = mLauncher.getSpanForWidget(createWidgetInfo, null);
535            createItemInfo.spanX = spanXY[0];
536            createItemInfo.spanY = spanXY[1];
537
538            b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
539            renderDrawableToBitmap(preview, b, 0, 0, w, h, scale, mDragViewMultiplyColor);
540        } else {
541            // Workaround for the fact that we don't keep the original ResolveInfo associated with
542            // the shortcut around.  To get the icon, we just render the preview image (which has
543            // the shortcut icon) to a new drag bitmap that clips the non-icon space.
544            b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension,
545                    mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888);
546            mCanvas.setBitmap(b);
547            mCanvas.save();
548            preview.draw(mCanvas);
549            mCanvas.restore();
550            mCanvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY);
551            mCanvas.setBitmap(null);
552            createItemInfo.spanX = createItemInfo.spanY = 1;
553        }
554
555        // Start the drag
556        mLauncher.lockScreenOrientationOnLargeUI();
557        mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX,
558                createItemInfo.spanY, b);
559        mDragController.startDrag(image, b, this, createItemInfo,
560                DragController.DRAG_ACTION_COPY, null);
561        b.recycle();
562    }
563    @Override
564    protected boolean beginDragging(View v) {
565        // Dismiss the cling
566        mLauncher.dismissAllAppsCling(null);
567
568        if (!super.beginDragging(v)) return false;
569
570        // Go into spring loaded mode (must happen before we startDrag())
571        mLauncher.enterSpringLoadedDragMode();
572
573        if (v instanceof PagedViewIcon) {
574            beginDraggingApplication(v);
575        } else if (v instanceof PagedViewWidget) {
576            beginDraggingWidget(v);
577        }
578        return true;
579    }
580    private void endDragging(View target, boolean success) {
581        mLauncher.getWorkspace().onDragStopped(success);
582        if (!success || (target != mLauncher.getWorkspace() &&
583                !(target instanceof DeleteDropTarget))) {
584            // Exit spring loaded mode if we have not successfully dropped or have not handled the
585            // drop in Workspace
586            mLauncher.exitSpringLoadedDragMode();
587        }
588        mLauncher.unlockScreenOrientationOnLargeUI();
589
590    }
591
592    @Override
593    public void onDropCompleted(View target, DragObject d, boolean success) {
594        endDragging(target, success);
595
596        // Display an error message if the drag failed due to there not being enough space on the
597        // target layout we were dropping on.
598        if (!success) {
599            boolean showOutOfSpaceMessage = false;
600            if (target instanceof Workspace) {
601                int currentScreen = mLauncher.getCurrentWorkspaceScreen();
602                Workspace workspace = (Workspace) target;
603                CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
604                ItemInfo itemInfo = (ItemInfo) d.dragInfo;
605                if (layout != null) {
606                    layout.calculateSpans(itemInfo);
607                    showOutOfSpaceMessage =
608                            !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
609                }
610            }
611            if (showOutOfSpaceMessage) {
612                mLauncher.showOutOfSpaceMessage();
613            }
614        }
615    }
616
617    @Override
618    protected void onDetachedFromWindow() {
619        super.onDetachedFromWindow();
620        cancelAllTasks();
621    }
622
623    private void cancelAllTasks() {
624        // Clean up all the async tasks
625        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
626        while (iter.hasNext()) {
627            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
628            task.cancel(false);
629            iter.remove();
630        }
631    }
632
633    public void setContentType(ContentType type) {
634        if (type == ContentType.Widgets) {
635            invalidatePageData(mNumAppsPages, true);
636        } else if (type == ContentType.Applications) {
637            invalidatePageData(0, true);
638        }
639    }
640
641    protected void snapToPage(int whichPage, int delta, int duration) {
642        super.snapToPage(whichPage, delta, duration);
643        updateCurrentTab(whichPage);
644    }
645
646    private void updateCurrentTab(int currentPage) {
647        AppsCustomizeTabHost tabHost = getTabHost();
648        String tag = tabHost.getCurrentTabTag();
649        if (tag != null) {
650            if (currentPage >= mNumAppsPages &&
651                    !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
652                tabHost.setCurrentTabFromContent(ContentType.Widgets);
653            } else if (currentPage < mNumAppsPages &&
654                    !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
655                tabHost.setCurrentTabFromContent(ContentType.Applications);
656            }
657        }
658    }
659
660    /*
661     * Apps PagedView implementation
662     */
663    private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
664        int childCount = layout.getChildCount();
665        for (int i = 0; i < childCount; ++i) {
666            layout.getChildAt(i).setVisibility(visibility);
667        }
668    }
669    private void setupPage(PagedViewCellLayout layout) {
670        layout.setCellCount(mCellCountX, mCellCountY);
671        layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
672        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
673                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
674
675        // Note: We force a measure here to get around the fact that when we do layout calculations
676        // immediately after syncing, we don't have a proper width.  That said, we already know the
677        // expected page width, so we can actually optimize by hiding all the TextView-based
678        // children that are expensive to measure, and let that happen naturally later.
679        setVisibilityOnChildren(layout, View.GONE);
680        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
681        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
682        layout.setMinimumWidth(getPageContentWidth());
683        layout.measure(widthSpec, heightSpec);
684        setVisibilityOnChildren(layout, View.VISIBLE);
685    }
686
687    public void syncAppsPageItems(int page, boolean immediate) {
688        // ensure that we have the right number of items on the pages
689        int numCells = mCellCountX * mCellCountY;
690        int startIndex = page * numCells;
691        int endIndex = Math.min(startIndex + numCells, mApps.size());
692        PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
693
694        layout.removeAllViewsOnPage();
695        ArrayList<Object> items = new ArrayList<Object>();
696        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
697        for (int i = startIndex; i < endIndex; ++i) {
698            ApplicationInfo info = mApps.get(i);
699            PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
700                    R.layout.apps_customize_application, layout, false);
701            icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper);
702            icon.setOnClickListener(this);
703            icon.setOnLongClickListener(this);
704            icon.setOnTouchListener(this);
705
706            int index = i - startIndex;
707            int x = index % mCellCountX;
708            int y = index / mCellCountX;
709            layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
710
711            items.add(info);
712            images.add(info.iconBitmap);
713        }
714
715        layout.createHardwareLayers();
716
717        /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS
718        if (mFadeInAdjacentScreens) {
719            prepareGenerateHoloOutlinesTask(page, items, images);
720        }
721        */
722    }
723
724    /**
725     * Return the appropriate thread priority for loading for a given page (we give the current
726     * page much higher priority)
727     */
728    private int getThreadPriorityForPage(int page) {
729        // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
730        int pageDiff = Math.abs(page - mCurrentPage);
731        if (pageDiff <= 0) {
732            // return Process.THREAD_PRIORITY_DEFAULT;
733            return Process.THREAD_PRIORITY_MORE_FAVORABLE;
734        } else if (pageDiff <= 1) {
735            // return Process.THREAD_PRIORITY_BACKGROUND;
736            return Process.THREAD_PRIORITY_DEFAULT;
737        } else {
738            // return Process.THREAD_PRIORITY_LOWEST;
739            return Process.THREAD_PRIORITY_DEFAULT;
740        }
741    }
742    private int getSleepForPage(int page) {
743        int pageDiff = Math.abs(page - mCurrentPage) - 1;
744        return Math.max(0, pageDiff * sPageSleepDelay);
745    }
746    /**
747     * Creates and executes a new AsyncTask to load a page of widget previews.
748     */
749    private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
750            int cellWidth, int cellHeight, int cellCountX) {
751        // Prune all tasks that are no longer needed
752        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
753        while (iter.hasNext()) {
754            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
755            int taskPage = task.page;
756            if ((taskPage == page) ||
757                    taskPage < getAssociatedLowerPageBound(mCurrentPage - mNumAppsPages) ||
758                    taskPage > getAssociatedUpperPageBound(mCurrentPage - mNumAppsPages)) {
759                task.cancel(false);
760                iter.remove();
761            } else {
762                task.setThreadPriority(getThreadPriorityForPage(taskPage + mNumAppsPages));
763            }
764        }
765
766        // We introduce a slight delay to order the loading of side pages so that we don't thrash
767        final int sleepMs = getSleepForPage(page + mNumAppsPages);
768        AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
769            cellCountX, new AsyncTaskCallback() {
770                @Override
771                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
772                    try {
773                        try {
774                            Thread.sleep(sleepMs);
775                        } catch (Exception e) {}
776                        loadWidgetPreviewsInBackground(task, data);
777                    } finally {
778                        if (task.isCancelled()) {
779                            data.cleanup(true);
780                        }
781                    }
782                }
783            },
784            new AsyncTaskCallback() {
785                @Override
786                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
787                    try {
788                        mRunningTasks.remove(task);
789                        if (task.isCancelled()) return;
790                        onSyncWidgetPageItems(data);
791                    } finally {
792                        data.cleanup(task.isCancelled());
793                    }
794                }
795            });
796
797        // Ensure that the task is appropriately prioritized and runs in parallel
798        AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
799                AsyncTaskPageData.Type.LoadWidgetPreviewData);
800        t.setThreadPriority(getThreadPriorityForPage(page));
801        t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
802        mRunningTasks.add(t);
803    }
804    /**
805     * Creates and executes a new AsyncTask to load the outlines for a page of content.
806     */
807    private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items,
808            ArrayList<Bitmap> images) {
809        // Prune old tasks for this page
810        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
811        while (iter.hasNext()) {
812            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
813            int taskPage = task.page;
814            if ((taskPage == page) &&
815                    (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) {
816                task.cancel(false);
817                iter.remove();
818            }
819        }
820
821        AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images,
822            new AsyncTaskCallback() {
823                @Override
824                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
825                    try {
826                        // Ensure that this task starts running at the correct priority
827                        task.syncThreadPriority();
828
829                        ArrayList<Bitmap> images = data.generatedImages;
830                        ArrayList<Bitmap> srcImages = data.sourceImages;
831                        int count = srcImages.size();
832                        Canvas c = new Canvas();
833                        for (int i = 0; i < count && !task.isCancelled(); ++i) {
834                            // Before work on each item, ensure that this task is running at the correct
835                            // priority
836                            task.syncThreadPriority();
837
838                            Bitmap b = srcImages.get(i);
839                            Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(),
840                                    Bitmap.Config.ARGB_8888);
841
842                            c.setBitmap(outline);
843                            c.save();
844                            c.drawBitmap(b, 0, 0, null);
845                            c.restore();
846                            c.setBitmap(null);
847
848                            images.add(outline);
849                        }
850                    } finally {
851                        if (task.isCancelled()) {
852                            data.cleanup(true);
853                        }
854                    }
855                }
856            },
857            new AsyncTaskCallback() {
858                @Override
859                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
860                    try {
861                        mRunningTasks.remove(task);
862                        if (task.isCancelled()) return;
863                        onHolographicPageItemsLoaded(data);
864                    } finally {
865                        data.cleanup(task.isCancelled());
866                    }
867                }
868            });
869
870        // Ensure that the outline task always runs in the background, serially
871        AppsCustomizeAsyncTask t =
872            new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadHolographicIconsData);
873        t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
874        t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData);
875        mRunningTasks.add(t);
876    }
877
878    /*
879     * Widgets PagedView implementation
880     */
881    private void setupPage(PagedViewGridLayout layout) {
882        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
883                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
884
885        // Note: We force a measure here to get around the fact that when we do layout calculations
886        // immediately after syncing, we don't have a proper width.
887        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
888        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
889        layout.setMinimumWidth(getPageContentWidth());
890        layout.measure(widthSpec, heightSpec);
891    }
892
893    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
894        renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f, 0xFFFFFFFF);
895    }
896    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
897            float scale) {
898        renderDrawableToBitmap(d, bitmap, x, y, w, h, scale, 0xFFFFFFFF);
899    }
900    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
901            float scale, int multiplyColor) {
902        if (bitmap != null) {
903            Canvas c = new Canvas(bitmap);
904            c.scale(scale, scale);
905            Rect oldBounds = d.copyBounds();
906            d.setBounds(x, y, x + w, y + h);
907            d.draw(c);
908            d.setBounds(oldBounds); // Restore the bounds
909            if (multiplyColor != 0xFFFFFFFF) {
910                c.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY);
911            }
912            c.setBitmap(null);
913        }
914    }
915    private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) {
916        // Render the background
917        int offset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
918        int bitmapSize = mAppIconSize + 2 * offset;
919        Bitmap preview = Bitmap.createBitmap(bitmapSize, bitmapSize, Config.ARGB_8888);
920        renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapSize, bitmapSize);
921
922        // Render the icon
923        Drawable icon = mIconCache.getFullResIcon(info, mPackageManager);
924        renderDrawableToBitmap(icon, preview, offset, offset, mAppIconSize, mAppIconSize);
925        return preview;
926    }
927    private Bitmap getWidgetPreview(AppWidgetProviderInfo info,
928            int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) {
929
930        // Load the preview image if possible
931        String packageName = info.provider.getPackageName();
932        Drawable drawable = null;
933        Bitmap preview = null;
934        if (info.previewImage != 0) {
935            drawable = mPackageManager.getDrawable(packageName, info.previewImage, null);
936            if (drawable == null) {
937                Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon)
938                        + " for provider: " + info.provider);
939            } else {
940                // Scale down the preview to something that is closer to the cellWidth/Height
941                int imageWidth = drawable.getIntrinsicWidth();
942                int imageHeight = drawable.getIntrinsicHeight();
943                int bitmapWidth = imageWidth;
944                int bitmapHeight = imageHeight;
945                if (imageWidth > imageHeight) {
946                    bitmapWidth = cellWidth;
947                    bitmapHeight = (int) (imageHeight * ((float) bitmapWidth / imageWidth));
948                } else {
949                    bitmapHeight = cellHeight;
950                    bitmapWidth = (int) (imageWidth * ((float) bitmapHeight / imageHeight));
951                }
952
953                preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
954                renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight);
955            }
956        }
957
958        // Generate a preview image if we couldn't load one
959        if (drawable == null) {
960            Resources resources = mLauncher.getResources();
961            // TODO: This actually uses the apps customize cell layout params, where as we make want
962            // the Workspace params for more accuracy.
963            int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan);
964            int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan);
965            int bitmapWidth = targetWidth;
966            int bitmapHeight = targetHeight;
967            int offset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
968            float iconScale = 1f;
969
970            // Determine the size of the bitmap we want to draw
971            if (cellHSpan == cellVSpan) {
972                // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1
973                if (cellHSpan <= 1) {
974                    bitmapWidth = bitmapHeight = mAppIconSize + 2 * offset;
975                } else {
976                    bitmapWidth = bitmapHeight = mAppIconSize + 4 * offset;
977                }
978            } else {
979                // Otherwise, ensure that we are properly sized within the cellWidth/Height
980                if (targetWidth > targetHeight) {
981                    bitmapWidth = Math.min(targetWidth, cellWidth);
982                    bitmapHeight = (int) (targetHeight * ((float) bitmapWidth / targetWidth));
983                    iconScale = Math.min((float) bitmapHeight / (mAppIconSize + 2 * offset), 1f);
984                } else {
985                    bitmapHeight = Math.min(targetHeight, cellHeight);
986                    bitmapWidth = (int) (targetWidth * ((float) bitmapHeight / targetHeight));
987                    iconScale = Math.min((float) bitmapWidth / (mAppIconSize + 2 * offset), 1f);
988                }
989            }
990            preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
991            renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth,
992                    bitmapWidth);
993
994            // Draw the icon in the top left corner
995            try {
996                Drawable icon = null;
997                if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null);
998                if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application);
999
1000                renderDrawableToBitmap(icon, preview, (int) (offset * iconScale),
1001                        (int) (offset * iconScale), (int) (mAppIconSize * iconScale),
1002                        (int) (mAppIconSize * iconScale));
1003            } catch (Resources.NotFoundException e) {}
1004        }
1005        return preview;
1006    }
1007
1008    public void syncWidgetPageItems(int page, boolean immediate) {
1009        int numItemsPerPage = mWidgetCountX * mWidgetCountY;
1010        int contentWidth = mWidgetSpacingLayout.getContentWidth();
1011        int contentHeight = mWidgetSpacingLayout.getContentHeight();
1012
1013        // Calculate the dimensions of each cell we are giving to each widget
1014        ArrayList<Object> items = new ArrayList<Object>();
1015        int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
1016                - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
1017        int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
1018                - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
1019
1020        // Prepare the set of widgets to load previews for in the background
1021        int offset = page * numItemsPerPage;
1022        for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1023            items.add(mWidgets.get(i));
1024        }
1025
1026        // Prepopulate the pages with the other widget info, and fill in the previews later
1027        PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages);
1028        layout.setColumnCount(layout.getCellCountX());
1029        for (int i = 0; i < items.size(); ++i) {
1030            Object rawInfo = items.get(i);
1031            PendingAddItemInfo createItemInfo = null;
1032            PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1033                    R.layout.apps_customize_widget, layout, false);
1034            if (rawInfo instanceof AppWidgetProviderInfo) {
1035                // Fill in the widget information
1036                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1037                createItemInfo = new PendingAddWidgetInfo(info, null, null);
1038                int[] cellSpans = mLauncher.getSpanForWidget(info, null);
1039                widget.applyFromAppWidgetProviderInfo(info, -1, cellSpans,
1040                        mHolographicOutlineHelper);
1041                widget.setTag(createItemInfo);
1042            } else if (rawInfo instanceof ResolveInfo) {
1043                // Fill in the shortcuts information
1044                ResolveInfo info = (ResolveInfo) rawInfo;
1045                createItemInfo = new PendingAddItemInfo();
1046                createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1047                createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1048                        info.activityInfo.name);
1049                widget.applyFromResolveInfo(mPackageManager, info, mHolographicOutlineHelper);
1050                widget.setTag(createItemInfo);
1051            }
1052            widget.setOnClickListener(this);
1053            widget.setOnLongClickListener(this);
1054            widget.setOnTouchListener(this);
1055
1056            // Layout each widget
1057            int ix = i % mWidgetCountX;
1058            int iy = i / mWidgetCountX;
1059            GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1060                    GridLayout.spec(iy, GridLayout.LEFT),
1061                    GridLayout.spec(ix, GridLayout.TOP));
1062            lp.width = cellWidth;
1063            lp.height = cellHeight;
1064            lp.setGravity(Gravity.TOP | Gravity.LEFT);
1065            if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1066            if (iy > 0) lp.topMargin = mWidgetHeightGap;
1067            layout.addView(widget, lp);
1068        }
1069
1070        // Load the widget previews
1071        if (immediate) {
1072            AsyncTaskPageData data = new AsyncTaskPageData(page, items, cellWidth, cellHeight,
1073                    mWidgetCountX, null, null);
1074            loadWidgetPreviewsInBackground(null, data);
1075            onSyncWidgetPageItems(data);
1076        } else {
1077            prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, mWidgetCountX);
1078        }
1079    }
1080    private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1081            AsyncTaskPageData data) {
1082        if (task != null) {
1083            // Ensure that this task starts running at the correct priority
1084            task.syncThreadPriority();
1085        }
1086
1087        // Load each of the widget/shortcut previews
1088        ArrayList<Object> items = data.items;
1089        ArrayList<Bitmap> images = data.generatedImages;
1090        int count = items.size();
1091        int cellWidth = data.cellWidth;
1092        int cellHeight = data.cellHeight;
1093        for (int i = 0; i < count; ++i) {
1094            if (task != null) {
1095                // Ensure we haven't been cancelled yet
1096                if (task.isCancelled()) break;
1097                // Before work on each item, ensure that this task is running at the correct
1098                // priority
1099                task.syncThreadPriority();
1100            }
1101
1102            Object rawInfo = items.get(i);
1103            if (rawInfo instanceof AppWidgetProviderInfo) {
1104                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1105                int[] cellSpans = mLauncher.getSpanForWidget(info, null);
1106                images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1],
1107                        cellWidth, cellHeight));
1108            } else if (rawInfo instanceof ResolveInfo) {
1109                // Fill in the shortcuts information
1110                ResolveInfo info = (ResolveInfo) rawInfo;
1111                images.add(getShortcutPreview(info, cellWidth, cellHeight));
1112            }
1113        }
1114    }
1115    private void onSyncWidgetPageItems(AsyncTaskPageData data) {
1116        int page = data.page;
1117        PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages);
1118
1119        ArrayList<Object> items = data.items;
1120        int count = items.size();
1121        for (int i = 0; i < count; ++i) {
1122            PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1123            if (widget != null) {
1124                Bitmap preview = data.generatedImages.get(i);
1125                boolean scale =
1126                    (preview.getWidth() >= data.cellWidth ||
1127                     preview.getHeight() >= data.cellHeight);
1128
1129                widget.applyPreview(new FastBitmapDrawable(preview), i, scale);
1130            }
1131        }
1132        layout.createHardwareLayer();
1133
1134        invalidate();
1135        forceUpdateAdjacentPagesAlpha();
1136
1137        /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS
1138        if (mFadeInAdjacentScreens) {
1139            prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages);
1140        }
1141        */
1142    }
1143    private void onHolographicPageItemsLoaded(AsyncTaskPageData data) {
1144        // Invalidate early to short-circuit children invalidates
1145        invalidate();
1146
1147        int page = data.page;
1148        ViewGroup layout = (ViewGroup) getPageAt(page);
1149        if (layout instanceof PagedViewCellLayout) {
1150            PagedViewCellLayout cl = (PagedViewCellLayout) layout;
1151            int count = cl.getPageChildCount();
1152            if (count != data.generatedImages.size()) return;
1153            for (int i = 0; i < count; ++i) {
1154                PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i);
1155                icon.setHolographicOutline(data.generatedImages.get(i));
1156            }
1157        } else {
1158            int count = layout.getChildCount();
1159            if (count != data.generatedImages.size()) return;
1160            for (int i = 0; i < count; ++i) {
1161                View v = layout.getChildAt(i);
1162                ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i));
1163            }
1164        }
1165    }
1166
1167    @Override
1168    public void syncPages() {
1169        removeAllViews();
1170        cancelAllTasks();
1171
1172        Context context = getContext();
1173        for (int j = 0; j < mNumWidgetPages; ++j) {
1174            PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1175                    mWidgetCountY);
1176            setupPage(layout);
1177            addView(layout, new PagedViewGridLayout.LayoutParams(LayoutParams.MATCH_PARENT,
1178                    LayoutParams.MATCH_PARENT));
1179        }
1180
1181        for (int i = 0; i < mNumAppsPages; ++i) {
1182            PagedViewCellLayout layout = new PagedViewCellLayout(context);
1183            setupPage(layout);
1184            addView(layout);
1185        }
1186    }
1187
1188    @Override
1189    public void syncPageItems(int page, boolean immediate) {
1190        if (page < mNumAppsPages) {
1191            syncAppsPageItems(page, immediate);
1192        } else {
1193            syncWidgetPageItems(page - mNumAppsPages, immediate);
1194        }
1195    }
1196
1197    // We want our pages to be z-ordered such that the further a page is to the left, the higher
1198    // it is in the z-order. This is important to insure touch events are handled correctly.
1199    View getPageAt(int index) {
1200        return getChildAt(getChildCount() - index - 1);
1201    }
1202
1203    @Override
1204    protected int indexToPage(int index) {
1205        return getChildCount() - index - 1;
1206    }
1207
1208    // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1209    @Override
1210    protected void screenScrolled(int screenCenter) {
1211        super.screenScrolled(screenCenter);
1212
1213        for (int i = 0; i < getChildCount(); i++) {
1214            View v = getPageAt(i);
1215            if (v != null) {
1216                float scrollProgress = getScrollProgress(screenCenter, v, i);
1217
1218                float interpolatedProgress =
1219                        mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1220                float scale = (1 - interpolatedProgress) +
1221                        interpolatedProgress * TRANSITION_SCALE_FACTOR;
1222                float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
1223
1224                float alpha;
1225
1226                if (!LauncherApplication.isScreenLarge() || scrollProgress < 0) {
1227                    alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
1228                        1 - Math.abs(scrollProgress)) : 1.0f;
1229                } else {
1230                    // On large screens we need to fade the page as it nears its leftmost position
1231                    alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1232                }
1233
1234                v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1235                int pageWidth = v.getMeasuredWidth();
1236                int pageHeight = v.getMeasuredHeight();
1237
1238                if (PERFORM_OVERSCROLL_ROTATION) {
1239                    if (i == 0 && scrollProgress < 0) {
1240                        // Overscroll to the left
1241                        v.setPivotX(TRANSITION_PIVOT * pageWidth);
1242                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1243                        scale = 1.0f;
1244                        alpha = 1.0f;
1245                        // On the first page, we don't want the page to have any lateral motion
1246                        translationX = getScrollX();
1247                    } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1248                        // Overscroll to the right
1249                        v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1250                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1251                        scale = 1.0f;
1252                        alpha = 1.0f;
1253                        // On the last page, we don't want the page to have any lateral motion.
1254                        translationX =  getScrollX() - mMaxScrollX;
1255                    } else {
1256                        v.setPivotY(pageHeight / 2.0f);
1257                        v.setPivotX(pageWidth / 2.0f);
1258                        v.setRotationY(0f);
1259                    }
1260                }
1261
1262                v.setTranslationX(translationX);
1263                v.setScaleX(scale);
1264                v.setScaleY(scale);
1265                v.setAlpha(alpha);
1266            }
1267        }
1268    }
1269
1270    protected void overScroll(float amount) {
1271        acceleratedOverScroll(amount);
1272    }
1273
1274    /**
1275     * Used by the parent to get the content width to set the tab bar to
1276     * @return
1277     */
1278    public int getPageContentWidth() {
1279        return mContentWidth;
1280    }
1281
1282    @Override
1283    protected void onPageEndMoving() {
1284        super.onPageEndMoving();
1285
1286        // We reset the save index when we change pages so that it will be recalculated on next
1287        // rotation
1288        mSaveInstanceStateItemIndex = -1;
1289    }
1290
1291    /*
1292     * AllAppsView implementation
1293     */
1294    @Override
1295    public void setup(Launcher launcher, DragController dragController) {
1296        mLauncher = launcher;
1297        mDragController = dragController;
1298    }
1299    @Override
1300    public void zoom(float zoom, boolean animate) {
1301        // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1302    }
1303    @Override
1304    public boolean isVisible() {
1305        return (getVisibility() == VISIBLE);
1306    }
1307    @Override
1308    public boolean isAnimating() {
1309        return false;
1310    }
1311    @Override
1312    public void setApps(ArrayList<ApplicationInfo> list) {
1313        mApps = list;
1314        Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
1315        updatePageCounts();
1316
1317        // The next layout pass will trigger data-ready if both widgets and apps are set, so
1318        // request a layout to do this test and invalidate the page data when ready.
1319        if (testDataReady()) requestLayout();
1320    }
1321    private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1322        // We add it in place, in alphabetical order
1323        int count = list.size();
1324        for (int i = 0; i < count; ++i) {
1325            ApplicationInfo info = list.get(i);
1326            int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1327            if (index < 0) {
1328                mApps.add(-(index + 1), info);
1329            }
1330        }
1331    }
1332    @Override
1333    public void addApps(ArrayList<ApplicationInfo> list) {
1334        addAppsWithoutInvalidate(list);
1335        updatePageCounts();
1336        invalidatePageData();
1337    }
1338    private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1339        ComponentName removeComponent = item.intent.getComponent();
1340        int length = list.size();
1341        for (int i = 0; i < length; ++i) {
1342            ApplicationInfo info = list.get(i);
1343            if (info.intent.getComponent().equals(removeComponent)) {
1344                return i;
1345            }
1346        }
1347        return -1;
1348    }
1349    private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1350        // loop through all the apps and remove apps that have the same component
1351        int length = list.size();
1352        for (int i = 0; i < length; ++i) {
1353            ApplicationInfo info = list.get(i);
1354            int removeIndex = findAppByComponent(mApps, info);
1355            if (removeIndex > -1) {
1356                mApps.remove(removeIndex);
1357            }
1358        }
1359    }
1360    @Override
1361    public void removeApps(ArrayList<ApplicationInfo> list) {
1362        removeAppsWithoutInvalidate(list);
1363        updatePageCounts();
1364        invalidatePageData();
1365    }
1366    @Override
1367    public void updateApps(ArrayList<ApplicationInfo> list) {
1368        // We remove and re-add the updated applications list because it's properties may have
1369        // changed (ie. the title), and this will ensure that the items will be in their proper
1370        // place in the list.
1371        removeAppsWithoutInvalidate(list);
1372        addAppsWithoutInvalidate(list);
1373        updatePageCounts();
1374
1375        invalidatePageData();
1376    }
1377
1378    @Override
1379    public void reset() {
1380        AppsCustomizeTabHost tabHost = getTabHost();
1381        String tag = tabHost.getCurrentTabTag();
1382        if (tag != null) {
1383            if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1384                tabHost.setCurrentTabFromContent(ContentType.Applications);
1385            }
1386        }
1387        if (mCurrentPage != 0) {
1388            invalidatePageData(0);
1389        }
1390    }
1391
1392    private AppsCustomizeTabHost getTabHost() {
1393        return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1394    }
1395
1396    @Override
1397    public void dumpState() {
1398        // TODO: Dump information related to current list of Applications, Widgets, etc.
1399        ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps);
1400        dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets);
1401    }
1402    private void dumpAppWidgetProviderInfoList(String tag, String label,
1403            ArrayList<Object> list) {
1404        Log.d(tag, label + " size=" + list.size());
1405        for (Object i: list) {
1406            if (i instanceof AppWidgetProviderInfo) {
1407                AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1408                Log.d(tag, "   label=\"" + info.label + "\" previewImage=" + info.previewImage
1409                        + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1410                        + " initialLayout=" + info.initialLayout
1411                        + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1412            } else if (i instanceof ResolveInfo) {
1413                ResolveInfo info = (ResolveInfo) i;
1414                Log.d(tag, "   label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1415                        + info.icon);
1416            }
1417        }
1418    }
1419    @Override
1420    public void surrender() {
1421        // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1422        // should stop this now.
1423
1424        // Stop all background tasks
1425        cancelAllTasks();
1426    }
1427
1428    /*
1429     * We load an extra page on each side to prevent flashes from scrolling and loading of the
1430     * widget previews in the background with the AsyncTasks.
1431     */
1432    protected int getAssociatedLowerPageBound(int page) {
1433        return Math.max(0, page - 2);
1434    }
1435    protected int getAssociatedUpperPageBound(int page) {
1436        final int count = getChildCount();
1437        return Math.min(page + 2, count - 1);
1438    }
1439
1440    @Override
1441    protected String getCurrentPageDescription() {
1442        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1443        int stringId = R.string.default_scroll_format;
1444        int count = 0;
1445
1446        if (page < mNumAppsPages) {
1447            stringId = R.string.apps_customize_apps_scroll_format;
1448            count = mNumAppsPages;
1449        } else {
1450            page -= mNumAppsPages;
1451            stringId = R.string.apps_customize_widgets_scroll_format;
1452            count = mNumWidgetPages;
1453        }
1454
1455        return String.format(mContext.getString(stringId), page + 1, count);
1456    }
1457}
1458