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