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