AppsCustomizePagedView.java revision 4d173e93f077bdbc855cd1ef388dea4e21a234d5
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        // This can happen in some weird cases involving multi-touch. We can't start dragging the
673        // widget if this is null, so we break out.
674        if (mCreateWidgetInfo == null) {
675            return false;
676        }
677
678        // Compose the drag image
679        Bitmap preview;
680        Bitmap outline;
681        float scale = 1f;
682        if (createItemInfo instanceof PendingAddWidgetInfo) {
683            PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
684            createItemInfo = createWidgetInfo;
685            int spanX = createItemInfo.spanX;
686            int spanY = createItemInfo.spanY;
687            int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY,
688                    createWidgetInfo, true);
689
690            FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
691            float minScale = 1.25f;
692            int minWidth, minHeight;
693            minWidth = Math.max((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
694            minHeight = Math.max((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
695            preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
696                    createWidgetInfo.icon, spanX, spanY, minWidth, minHeight);
697
698            // Determine the image view drawable scale relative to the preview
699            float[] mv = new float[9];
700            Matrix m = new Matrix();
701            m.setRectToRect(
702                    new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
703                    new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
704                            (float) previewDrawable.getIntrinsicHeight()),
705                    Matrix.ScaleToFit.START);
706            m.getValues(mv);
707            scale = (float) mv[0];
708        } else {
709            // Workaround for the fact that we don't keep the original ResolveInfo associated with
710            // the shortcut around.  To get the icon, we just render the preview image (which has
711            // the shortcut icon) to a new drag bitmap that clips the non-icon space.
712            preview = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension,
713                    mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888);
714            Drawable d = image.getDrawable();
715            mCanvas.setBitmap(preview);
716            mCanvas.save();
717            mCanvas.translate((mWidgetPreviewIconPaddedDimension - d.getIntrinsicWidth()) / 2,
718                    (mWidgetPreviewIconPaddedDimension - d.getIntrinsicHeight()) / 2);
719            d.draw(mCanvas);
720            mCanvas.restore();
721            mCanvas.setBitmap(null);
722            createItemInfo.spanX = createItemInfo.spanY = 1;
723        }
724
725        // We use a custom alpha clip table for the default widget previews
726        Paint alphaClipPaint = null;
727        if (createItemInfo instanceof PendingAddWidgetInfo) {
728            if (((PendingAddWidgetInfo) createItemInfo).previewImage != 0) {
729                MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255);
730                alphaClipPaint = new Paint();
731                alphaClipPaint.setMaskFilter(alphaClipTable);
732            }
733        }
734
735        // Save the preview for the outline generation, then dim the preview
736        outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(),
737                false);
738
739        // Start the drag
740        alphaClipPaint = null;
741        mLauncher.lockScreenOrientation();
742        mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, alphaClipPaint);
743        mDragController.startDrag(image, preview, this, createItemInfo,
744                DragController.DRAG_ACTION_COPY, null, scale);
745        outline.recycle();
746        preview.recycle();
747        return true;
748    }
749
750    @Override
751    protected boolean beginDragging(final View v) {
752        if (!super.beginDragging(v)) return false;
753
754        if (v instanceof PagedViewIcon) {
755            beginDraggingApplication(v);
756        } else if (v instanceof PagedViewWidget) {
757            if (!beginDraggingWidget(v)) {
758                return false;
759            }
760        }
761
762        // We delay entering spring-loaded mode slightly to make sure the UI
763        // thready is free of any work.
764        postDelayed(new Runnable() {
765            @Override
766            public void run() {
767                // We don't enter spring-loaded mode if the drag has been cancelled
768                if (mLauncher.getDragController().isDragging()) {
769                    // Dismiss the cling
770                    mLauncher.dismissAllAppsCling(null);
771
772                    // Reset the alpha on the dragged icon before we drag
773                    resetDrawableState();
774
775                    // Go into spring loaded mode (must happen before we startDrag())
776                    mLauncher.enterSpringLoadedDragMode();
777                }
778            }
779        }, 150);
780
781        return true;
782    }
783
784    /**
785     * Clean up after dragging.
786     *
787     * @param target where the item was dragged to (can be null if the item was flung)
788     */
789    private void endDragging(View target, boolean isFlingToDelete, boolean success) {
790        if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() &&
791                !(target instanceof DeleteDropTarget))) {
792            // Exit spring loaded mode if we have not successfully dropped or have not handled the
793            // drop in Workspace
794            mLauncher.exitSpringLoadedDragMode();
795        }
796        mLauncher.unlockScreenOrientation(false);
797    }
798
799    @Override
800    public View getContent() {
801        return null;
802    }
803
804    @Override
805    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
806        mInTransition = true;
807        if (toWorkspace) {
808            cancelAllTasks();
809        }
810    }
811
812    @Override
813    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
814    }
815
816    @Override
817    public void onLauncherTransitionStep(Launcher l, float t) {
818    }
819
820    @Override
821    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
822        mInTransition = false;
823        for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
824            onSyncWidgetPageItems(d);
825        }
826        mDeferredSyncWidgetPageItems.clear();
827        mForceDrawAllChildrenNextFrame = !toWorkspace;
828    }
829
830    @Override
831    public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
832            boolean success) {
833        // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
834        if (isFlingToDelete) return;
835
836        endDragging(target, false, success);
837
838        // Display an error message if the drag failed due to there not being enough space on the
839        // target layout we were dropping on.
840        if (!success) {
841            boolean showOutOfSpaceMessage = false;
842            if (target instanceof Workspace) {
843                int currentScreen = mLauncher.getCurrentWorkspaceScreen();
844                Workspace workspace = (Workspace) target;
845                CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
846                ItemInfo itemInfo = (ItemInfo) d.dragInfo;
847                if (layout != null) {
848                    layout.calculateSpans(itemInfo);
849                    showOutOfSpaceMessage =
850                            !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
851                }
852            }
853            if (showOutOfSpaceMessage) {
854                mLauncher.showOutOfSpaceMessage(false);
855            }
856
857            d.deferDragViewCleanupPostAnimation = false;
858        }
859        cleanupWidgetPreloading(success);
860        mDraggingWidget = false;
861    }
862
863    @Override
864    public void onFlingToDeleteCompleted() {
865        // We just dismiss the drag when we fling, so cleanup here
866        endDragging(null, true, true);
867        cleanupWidgetPreloading(false);
868        mDraggingWidget = false;
869    }
870
871    @Override
872    public boolean supportsFlingToDelete() {
873        return true;
874    }
875
876    @Override
877    protected void onDetachedFromWindow() {
878        super.onDetachedFromWindow();
879        cancelAllTasks();
880    }
881
882    public void clearAllWidgetPages() {
883        cancelAllTasks();
884        int count = getChildCount();
885        for (int i = 0; i < count; i++) {
886            View v = getPageAt(i);
887            if (v instanceof PagedViewGridLayout) {
888                ((PagedViewGridLayout) v).removeAllViewsOnPage();
889                mDirtyPageContent.set(i, true);
890            }
891        }
892    }
893
894    private void cancelAllTasks() {
895        // Clean up all the async tasks
896        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
897        while (iter.hasNext()) {
898            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
899            task.cancel(false);
900            iter.remove();
901            mDirtyPageContent.set(task.page, true);
902        }
903        mDeferredSyncWidgetPageItems.clear();
904    }
905
906    public void setContentType(ContentType type) {
907        if (type == ContentType.Widgets) {
908            invalidatePageData(mNumAppsPages, true);
909        } else if (type == ContentType.Applications) {
910            invalidatePageData(0, true);
911        }
912    }
913
914    protected void snapToPage(int whichPage, int delta, int duration) {
915        super.snapToPage(whichPage, delta, duration);
916        updateCurrentTab(whichPage);
917
918        // Update the thread priorities given the direction lookahead
919        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
920        while (iter.hasNext()) {
921            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
922            int pageIndex = task.page;
923            if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
924                (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
925                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
926            } else {
927                task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
928            }
929        }
930    }
931
932    private void updateCurrentTab(int currentPage) {
933        AppsCustomizeTabHost tabHost = getTabHost();
934        if (tabHost != null) {
935            String tag = tabHost.getCurrentTabTag();
936            if (tag != null) {
937                if (currentPage >= mNumAppsPages &&
938                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
939                    tabHost.setCurrentTabFromContent(ContentType.Widgets);
940                } else if (currentPage < mNumAppsPages &&
941                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
942                    tabHost.setCurrentTabFromContent(ContentType.Applications);
943                }
944            }
945        }
946    }
947
948    /*
949     * Apps PagedView implementation
950     */
951    private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
952        int childCount = layout.getChildCount();
953        for (int i = 0; i < childCount; ++i) {
954            layout.getChildAt(i).setVisibility(visibility);
955        }
956    }
957    private void setupPage(PagedViewCellLayout layout) {
958        layout.setCellCount(mCellCountX, mCellCountY);
959        layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
960        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
961                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
962
963        // Note: We force a measure here to get around the fact that when we do layout calculations
964        // immediately after syncing, we don't have a proper width.  That said, we already know the
965        // expected page width, so we can actually optimize by hiding all the TextView-based
966        // children that are expensive to measure, and let that happen naturally later.
967        setVisibilityOnChildren(layout, View.GONE);
968        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
969        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
970        layout.setMinimumWidth(getPageContentWidth());
971        layout.measure(widthSpec, heightSpec);
972        setVisibilityOnChildren(layout, View.VISIBLE);
973    }
974
975    public void syncAppsPageItems(int page, boolean immediate) {
976        // ensure that we have the right number of items on the pages
977        int numCells = mCellCountX * mCellCountY;
978        int startIndex = page * numCells;
979        int endIndex = Math.min(startIndex + numCells, mApps.size());
980        PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
981
982        layout.removeAllViewsOnPage();
983        ArrayList<Object> items = new ArrayList<Object>();
984        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
985        for (int i = startIndex; i < endIndex; ++i) {
986            ApplicationInfo info = mApps.get(i);
987            PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
988                    R.layout.apps_customize_application, layout, false);
989            icon.applyFromApplicationInfo(info, true, this);
990            icon.setOnClickListener(this);
991            icon.setOnLongClickListener(this);
992            icon.setOnTouchListener(this);
993            icon.setOnKeyListener(this);
994
995            int index = i - startIndex;
996            int x = index % mCellCountX;
997            int y = index / mCellCountX;
998            layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
999
1000            items.add(info);
1001            images.add(info.iconBitmap);
1002        }
1003
1004        layout.createHardwareLayers();
1005    }
1006
1007    /**
1008     * A helper to return the priority for loading of the specified widget page.
1009     */
1010    private int getWidgetPageLoadPriority(int page) {
1011        // If we are snapping to another page, use that index as the target page index
1012        int toPage = mCurrentPage;
1013        if (mNextPage > -1) {
1014            toPage = mNextPage;
1015        }
1016
1017        // We use the distance from the target page as an initial guess of priority, but if there
1018        // are no pages of higher priority than the page specified, then bump up the priority of
1019        // the specified page.
1020        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1021        int minPageDiff = Integer.MAX_VALUE;
1022        while (iter.hasNext()) {
1023            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1024            minPageDiff = Math.abs(task.page - toPage);
1025        }
1026
1027        int rawPageDiff = Math.abs(page - toPage);
1028        return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
1029    }
1030    /**
1031     * Return the appropriate thread priority for loading for a given page (we give the current
1032     * page much higher priority)
1033     */
1034    private int getThreadPriorityForPage(int page) {
1035        // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
1036        int pageDiff = getWidgetPageLoadPriority(page);
1037        if (pageDiff <= 0) {
1038            return Process.THREAD_PRIORITY_LESS_FAVORABLE;
1039        } else if (pageDiff <= 1) {
1040            return Process.THREAD_PRIORITY_LOWEST;
1041        } else {
1042            return Process.THREAD_PRIORITY_LOWEST;
1043        }
1044    }
1045    private int getSleepForPage(int page) {
1046        int pageDiff = getWidgetPageLoadPriority(page);
1047        return Math.max(0, pageDiff * sPageSleepDelay);
1048    }
1049    /**
1050     * Creates and executes a new AsyncTask to load a page of widget previews.
1051     */
1052    private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
1053            int cellWidth, int cellHeight, int cellCountX) {
1054
1055        // Prune all tasks that are no longer needed
1056        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1057        while (iter.hasNext()) {
1058            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1059            int taskPage = task.page;
1060            if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
1061                    taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
1062                task.cancel(false);
1063                iter.remove();
1064            } else {
1065                task.setThreadPriority(getThreadPriorityForPage(taskPage));
1066            }
1067        }
1068
1069        // We introduce a slight delay to order the loading of side pages so that we don't thrash
1070        final int sleepMs = getSleepForPage(page);
1071        AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
1072            new AsyncTaskCallback() {
1073                @Override
1074                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1075                    try {
1076                        try {
1077                            Thread.sleep(sleepMs);
1078                        } catch (Exception e) {}
1079                        loadWidgetPreviewsInBackground(task, data);
1080                    } finally {
1081                        if (task.isCancelled()) {
1082                            data.cleanup(true);
1083                        }
1084                    }
1085                }
1086            },
1087            new AsyncTaskCallback() {
1088                @Override
1089                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1090                    mRunningTasks.remove(task);
1091                    if (task.isCancelled()) return;
1092                    // do cleanup inside onSyncWidgetPageItems
1093                    onSyncWidgetPageItems(data);
1094                }
1095            });
1096
1097        // Ensure that the task is appropriately prioritized and runs in parallel
1098        AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
1099                AsyncTaskPageData.Type.LoadWidgetPreviewData);
1100        t.setThreadPriority(getThreadPriorityForPage(page));
1101        t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
1102        mRunningTasks.add(t);
1103    }
1104
1105    /*
1106     * Widgets PagedView implementation
1107     */
1108    private void setupPage(PagedViewGridLayout layout) {
1109        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1110                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1111
1112        // Note: We force a measure here to get around the fact that when we do layout calculations
1113        // immediately after syncing, we don't have a proper width.
1114        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1115        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
1116        layout.setMinimumWidth(getPageContentWidth());
1117        layout.measure(widthSpec, heightSpec);
1118    }
1119
1120    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
1121        renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f, 0xFFFFFFFF);
1122    }
1123
1124    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
1125            float scale, int multiplyColor) {
1126        if (bitmap != null) {
1127            Canvas c = new Canvas(bitmap);
1128            c.scale(scale, scale);
1129            Rect oldBounds = d.copyBounds();
1130            d.setBounds(x, y, x + w, y + h);
1131            d.draw(c);
1132            d.setBounds(oldBounds); // Restore the bounds
1133            c.setBitmap(null);
1134        }
1135    }
1136    private Bitmap getShortcutPreview(ResolveInfo info) {
1137        // Render the background
1138        int offset = 0;
1139        int bitmapSize = mAppIconSize;
1140        Bitmap preview = Bitmap.createBitmap(bitmapSize, bitmapSize, Config.ARGB_8888);
1141
1142        // Render the icon
1143        Drawable icon = mIconCache.getFullResIcon(info);
1144        renderDrawableToBitmap(icon, preview, offset, offset, mAppIconSize, mAppIconSize);
1145        return preview;
1146    }
1147
1148    private Bitmap getWidgetPreview(ComponentName provider, int previewImage, int iconId,
1149            int cellHSpan, int cellVSpan, int maxWidth, int maxHeight) {
1150        // Load the preview image if possible
1151        String packageName = provider.getPackageName();
1152        if (maxWidth < 0) maxWidth = Integer.MAX_VALUE;
1153        if (maxHeight < 0) maxHeight = Integer.MAX_VALUE;
1154
1155        Drawable drawable = null;
1156        if (previewImage != 0) {
1157            drawable = mPackageManager.getDrawable(packageName, previewImage, null);
1158            if (drawable == null) {
1159                Log.w(TAG, "Can't load widget preview drawable 0x" +
1160                        Integer.toHexString(previewImage) + " for provider: " + provider);
1161            }
1162        }
1163
1164        int bitmapWidth;
1165        int bitmapHeight;
1166        boolean widgetPreviewExists = (drawable != null);
1167        if (widgetPreviewExists) {
1168            bitmapWidth = drawable.getIntrinsicWidth();
1169            bitmapHeight = drawable.getIntrinsicHeight();
1170        } else {
1171            if (cellHSpan < 1) cellHSpan = 1;
1172            if (cellVSpan < 1) cellVSpan = 1;
1173            // Determine the size of the bitmap for the preview image we will generate
1174            // TODO: This actually uses the apps customize cell layout params, where as we make want
1175            // the Workspace params for more accuracy.
1176            bitmapWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan);
1177            bitmapHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan);
1178            if (cellHSpan == cellVSpan) {
1179                // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1
1180                int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1181                if (cellHSpan <= 1) {
1182                    bitmapWidth = bitmapHeight = mAppIconSize + 2 * minOffset;
1183                } else {
1184                    bitmapWidth = bitmapHeight = mAppIconSize + 4 * minOffset;
1185                }
1186            }
1187        }
1188
1189        float scale = 1f;
1190        if (bitmapWidth > maxWidth) {
1191            scale = maxWidth / (float) bitmapWidth;
1192        }
1193        if (bitmapHeight * scale > maxHeight) {
1194            scale = maxHeight / (float) bitmapHeight;
1195        }
1196        if (scale != 1f) {
1197            bitmapWidth = (int) (scale * bitmapWidth);
1198            bitmapHeight = (int) (scale * bitmapHeight);
1199        }
1200
1201        Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
1202
1203        if (widgetPreviewExists) {
1204            renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight);
1205        } else {
1206            // Generate a preview image if we couldn't load one
1207            int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1208            int smallestSide = Math.min(bitmapWidth, bitmapHeight);
1209            float iconScale = Math.min((float) smallestSide / (mAppIconSize + 2 * minOffset), 1f);
1210            if (cellHSpan != 1 || cellVSpan != 1) {
1211                renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth,
1212                        bitmapHeight);
1213            }
1214
1215            // Draw the icon in the top left corner
1216            try {
1217                Drawable icon = null;
1218                int hoffset = (int) (bitmapWidth / 2 - mAppIconSize * iconScale / 2);
1219                int yoffset = (int) (bitmapHeight / 2 - mAppIconSize * iconScale / 2);
1220                if (iconId > 0) icon = mIconCache.getFullResIcon(packageName, iconId);
1221                Resources resources = mLauncher.getResources();
1222                if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application);
1223
1224                renderDrawableToBitmap(icon, preview, hoffset, yoffset,
1225                        (int) (mAppIconSize * iconScale),
1226                        (int) (mAppIconSize * iconScale));
1227            } catch (Resources.NotFoundException e) {}
1228        }
1229        return preview;
1230    }
1231
1232    public void syncWidgetPageItems(final int page, final boolean immediate) {
1233        int numItemsPerPage = mWidgetCountX * mWidgetCountY;
1234
1235        // Calculate the dimensions of each cell we are giving to each widget
1236        final ArrayList<Object> items = new ArrayList<Object>();
1237        int contentWidth = mWidgetSpacingLayout.getContentWidth();
1238        final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
1239                - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
1240        int contentHeight = mWidgetSpacingLayout.getContentHeight();
1241        final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
1242                - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
1243
1244        // Prepare the set of widgets to load previews for in the background
1245        int offset = (page - mNumAppsPages) * numItemsPerPage;
1246        for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1247            items.add(mWidgets.get(i));
1248        }
1249
1250        // Prepopulate the pages with the other widget info, and fill in the previews later
1251        final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1252        layout.setColumnCount(layout.getCellCountX());
1253        for (int i = 0; i < items.size(); ++i) {
1254            Object rawInfo = items.get(i);
1255            PendingAddItemInfo createItemInfo = null;
1256            PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1257                    R.layout.apps_customize_widget, layout, false);
1258            if (rawInfo instanceof AppWidgetProviderInfo) {
1259                // Fill in the widget information
1260                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1261                createItemInfo = new PendingAddWidgetInfo(info, null, null);
1262
1263                // Determine the widget spans and min resize spans.
1264                int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
1265                createItemInfo.spanX = spanXY[0];
1266                createItemInfo.spanY = spanXY[1];
1267                int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
1268                createItemInfo.minSpanX = minSpanXY[0];
1269                createItemInfo.minSpanY = minSpanXY[1];
1270
1271                widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
1272                widget.setTag(createItemInfo);
1273                widget.setShortPressListener(this);
1274            } else if (rawInfo instanceof ResolveInfo) {
1275                // Fill in the shortcuts information
1276                ResolveInfo info = (ResolveInfo) rawInfo;
1277                createItemInfo = new PendingAddItemInfo();
1278                createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1279                createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1280                        info.activityInfo.name);
1281                widget.applyFromResolveInfo(mPackageManager, info);
1282                widget.setTag(createItemInfo);
1283            }
1284            widget.setOnClickListener(this);
1285            widget.setOnLongClickListener(this);
1286            widget.setOnTouchListener(this);
1287            widget.setOnKeyListener(this);
1288
1289            // Layout each widget
1290            int ix = i % mWidgetCountX;
1291            int iy = i / mWidgetCountX;
1292            GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1293                    GridLayout.spec(iy, GridLayout.LEFT),
1294                    GridLayout.spec(ix, GridLayout.TOP));
1295            lp.width = cellWidth;
1296            lp.height = cellHeight;
1297            lp.setGravity(Gravity.TOP | Gravity.LEFT);
1298            if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1299            if (iy > 0) lp.topMargin = mWidgetHeightGap;
1300            layout.addView(widget, lp);
1301        }
1302
1303        // wait until a call on onLayout to start loading, because
1304        // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
1305        // TODO: can we do a measure/layout immediately?
1306        layout.setOnLayoutListener(new Runnable() {
1307            public void run() {
1308                // Load the widget previews
1309                int maxPreviewWidth = cellWidth;
1310                int maxPreviewHeight = cellHeight;
1311                if (layout.getChildCount() > 0) {
1312                    PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
1313                    int[] maxSize = w.getPreviewSize();
1314                    maxPreviewWidth = maxSize[0];
1315                    maxPreviewHeight = maxSize[1];
1316                }
1317                if (immediate) {
1318                    AsyncTaskPageData data = new AsyncTaskPageData(page, items,
1319                            maxPreviewWidth, maxPreviewHeight, null, null);
1320                    loadWidgetPreviewsInBackground(null, data);
1321                    onSyncWidgetPageItems(data);
1322                } else {
1323                    prepareLoadWidgetPreviewsTask(page, items,
1324                            maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
1325                }
1326            }
1327        });
1328    }
1329    private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1330            AsyncTaskPageData data) {
1331        // loadWidgetPreviewsInBackground can be called without a task to load a set of widget
1332        // previews synchronously
1333        if (task != null) {
1334            // Ensure that this task starts running at the correct priority
1335            task.syncThreadPriority();
1336        }
1337
1338        // Load each of the widget/shortcut previews
1339        ArrayList<Object> items = data.items;
1340        ArrayList<Bitmap> images = data.generatedImages;
1341        int count = items.size();
1342        for (int i = 0; i < count; ++i) {
1343            if (task != null) {
1344                // Ensure we haven't been cancelled yet
1345                if (task.isCancelled()) break;
1346                // Before work on each item, ensure that this task is running at the correct
1347                // priority
1348                task.syncThreadPriority();
1349            }
1350
1351            Object rawInfo = items.get(i);
1352            if (rawInfo instanceof AppWidgetProviderInfo) {
1353                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1354                int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
1355
1356                int maxWidth = Math.min(data.maxImageWidth,
1357                        mWidgetSpacingLayout.estimateCellWidth(cellSpans[0]));
1358                int maxHeight = Math.min(data.maxImageHeight,
1359                        mWidgetSpacingLayout.estimateCellHeight(cellSpans[1]));
1360                Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon,
1361                        cellSpans[0], cellSpans[1], maxWidth, maxHeight);
1362                images.add(b);
1363            } else if (rawInfo instanceof ResolveInfo) {
1364                // Fill in the shortcuts information
1365                ResolveInfo info = (ResolveInfo) rawInfo;
1366                images.add(getShortcutPreview(info));
1367            }
1368        }
1369    }
1370
1371    private void onSyncWidgetPageItems(AsyncTaskPageData data) {
1372        if (mInTransition) {
1373            mDeferredSyncWidgetPageItems.add(data);
1374            return;
1375        }
1376        try {
1377            int page = data.page;
1378            PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1379
1380            ArrayList<Object> items = data.items;
1381            int count = items.size();
1382            for (int i = 0; i < count; ++i) {
1383                PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1384                if (widget != null) {
1385                    Bitmap preview = data.generatedImages.get(i);
1386                    widget.applyPreview(new FastBitmapDrawable(preview), i);
1387                }
1388            }
1389
1390            layout.createHardwareLayer();
1391            invalidate();
1392
1393            // Update all thread priorities
1394            Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1395            while (iter.hasNext()) {
1396                AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1397                int pageIndex = task.page;
1398                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1399            }
1400        } finally {
1401            data.cleanup(false);
1402        }
1403    }
1404
1405    @Override
1406    public void syncPages() {
1407        removeAllViews();
1408        cancelAllTasks();
1409
1410        Context context = getContext();
1411        for (int j = 0; j < mNumWidgetPages; ++j) {
1412            PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1413                    mWidgetCountY);
1414            setupPage(layout);
1415            addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
1416                    LayoutParams.MATCH_PARENT));
1417        }
1418
1419        for (int i = 0; i < mNumAppsPages; ++i) {
1420            PagedViewCellLayout layout = new PagedViewCellLayout(context);
1421            setupPage(layout);
1422            addView(layout);
1423        }
1424    }
1425
1426    @Override
1427    public void syncPageItems(int page, boolean immediate) {
1428        if (page < mNumAppsPages) {
1429            syncAppsPageItems(page, immediate);
1430        } else {
1431            syncWidgetPageItems(page, immediate);
1432        }
1433    }
1434
1435    // We want our pages to be z-ordered such that the further a page is to the left, the higher
1436    // it is in the z-order. This is important to insure touch events are handled correctly.
1437    View getPageAt(int index) {
1438        return getChildAt(indexToPage(index));
1439    }
1440
1441    @Override
1442    protected int indexToPage(int index) {
1443        return getChildCount() - index - 1;
1444    }
1445
1446    // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1447    @Override
1448    protected void screenScrolled(int screenCenter) {
1449        super.screenScrolled(screenCenter);
1450
1451        for (int i = 0; i < getChildCount(); i++) {
1452            View v = getPageAt(i);
1453            if (v != null) {
1454                float scrollProgress = getScrollProgress(screenCenter, v, i);
1455
1456                float interpolatedProgress =
1457                        mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1458                float scale = (1 - interpolatedProgress) +
1459                        interpolatedProgress * TRANSITION_SCALE_FACTOR;
1460                float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
1461
1462                float alpha;
1463
1464                if (scrollProgress < 0) {
1465                    alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
1466                        1 - Math.abs(scrollProgress)) : 1.0f;
1467                } else {
1468                    // On large screens we need to fade the page as it nears its leftmost position
1469                    alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1470                }
1471
1472                v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1473                int pageWidth = v.getMeasuredWidth();
1474                int pageHeight = v.getMeasuredHeight();
1475
1476                if (PERFORM_OVERSCROLL_ROTATION) {
1477                    if (i == 0 && scrollProgress < 0) {
1478                        // Overscroll to the left
1479                        v.setPivotX(TRANSITION_PIVOT * pageWidth);
1480                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1481                        scale = 1.0f;
1482                        alpha = 1.0f;
1483                        // On the first page, we don't want the page to have any lateral motion
1484                        translationX = 0;
1485                    } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1486                        // Overscroll to the right
1487                        v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1488                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1489                        scale = 1.0f;
1490                        alpha = 1.0f;
1491                        // On the last page, we don't want the page to have any lateral motion.
1492                        translationX = 0;
1493                    } else {
1494                        v.setPivotY(pageHeight / 2.0f);
1495                        v.setPivotX(pageWidth / 2.0f);
1496                        v.setRotationY(0f);
1497                    }
1498                }
1499
1500                v.setTranslationX(translationX);
1501                v.setScaleX(scale);
1502                v.setScaleY(scale);
1503                v.setAlpha(alpha);
1504
1505                // If the view has 0 alpha, we set it to be invisible so as to prevent
1506                // it from accepting touches
1507                if (alpha == 0) {
1508                    v.setVisibility(INVISIBLE);
1509                } else if (v.getVisibility() != VISIBLE) {
1510                    v.setVisibility(VISIBLE);
1511                }
1512            }
1513        }
1514    }
1515
1516    protected void overScroll(float amount) {
1517        acceleratedOverScroll(amount);
1518    }
1519
1520    /**
1521     * Used by the parent to get the content width to set the tab bar to
1522     * @return
1523     */
1524    public int getPageContentWidth() {
1525        return mContentWidth;
1526    }
1527
1528    @Override
1529    protected void onPageEndMoving() {
1530        super.onPageEndMoving();
1531        mForceDrawAllChildrenNextFrame = true;
1532        // We reset the save index when we change pages so that it will be recalculated on next
1533        // rotation
1534        mSaveInstanceStateItemIndex = -1;
1535    }
1536
1537    /*
1538     * AllAppsView implementation
1539     */
1540    @Override
1541    public void setup(Launcher launcher, DragController dragController) {
1542        mLauncher = launcher;
1543        mDragController = dragController;
1544    }
1545    @Override
1546    public void zoom(float zoom, boolean animate) {
1547        // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1548    }
1549    @Override
1550    public boolean isVisible() {
1551        return (getVisibility() == VISIBLE);
1552    }
1553    @Override
1554    public boolean isAnimating() {
1555        return false;
1556    }
1557    @Override
1558    public void setApps(ArrayList<ApplicationInfo> list) {
1559        mApps = list;
1560        Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
1561        updatePageCounts();
1562
1563        // The next layout pass will trigger data-ready if both widgets and apps are set, so
1564        // request a layout to do this test and invalidate the page data when ready.
1565        if (testDataReady()) requestLayout();
1566    }
1567    private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1568        // We add it in place, in alphabetical order
1569        int count = list.size();
1570        for (int i = 0; i < count; ++i) {
1571            ApplicationInfo info = list.get(i);
1572            int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1573            if (index < 0) {
1574                mApps.add(-(index + 1), info);
1575            }
1576        }
1577    }
1578    @Override
1579    public void addApps(ArrayList<ApplicationInfo> list) {
1580        addAppsWithoutInvalidate(list);
1581        updatePageCounts();
1582        invalidatePageData();
1583    }
1584    private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1585        ComponentName removeComponent = item.intent.getComponent();
1586        int length = list.size();
1587        for (int i = 0; i < length; ++i) {
1588            ApplicationInfo info = list.get(i);
1589            if (info.intent.getComponent().equals(removeComponent)) {
1590                return i;
1591            }
1592        }
1593        return -1;
1594    }
1595    private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1596        // loop through all the apps and remove apps that have the same component
1597        int length = list.size();
1598        for (int i = 0; i < length; ++i) {
1599            ApplicationInfo info = list.get(i);
1600            int removeIndex = findAppByComponent(mApps, info);
1601            if (removeIndex > -1) {
1602                mApps.remove(removeIndex);
1603            }
1604        }
1605    }
1606    @Override
1607    public void removeApps(ArrayList<ApplicationInfo> list) {
1608        removeAppsWithoutInvalidate(list);
1609        updatePageCounts();
1610        invalidatePageData();
1611    }
1612    @Override
1613    public void updateApps(ArrayList<ApplicationInfo> list) {
1614        // We remove and re-add the updated applications list because it's properties may have
1615        // changed (ie. the title), and this will ensure that the items will be in their proper
1616        // place in the list.
1617        removeAppsWithoutInvalidate(list);
1618        addAppsWithoutInvalidate(list);
1619        updatePageCounts();
1620
1621        invalidatePageData();
1622    }
1623
1624    @Override
1625    public void reset() {
1626        // If we have reset, then we should not continue to restore the previous state
1627        mSaveInstanceStateItemIndex = -1;
1628
1629        AppsCustomizeTabHost tabHost = getTabHost();
1630        String tag = tabHost.getCurrentTabTag();
1631        if (tag != null) {
1632            if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1633                tabHost.setCurrentTabFromContent(ContentType.Applications);
1634            }
1635        }
1636
1637        if (mCurrentPage != 0) {
1638            invalidatePageData(0);
1639        }
1640    }
1641
1642    private AppsCustomizeTabHost getTabHost() {
1643        return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1644    }
1645
1646    @Override
1647    public void dumpState() {
1648        // TODO: Dump information related to current list of Applications, Widgets, etc.
1649        ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
1650        dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
1651    }
1652
1653    private void dumpAppWidgetProviderInfoList(String tag, String label,
1654            ArrayList<Object> list) {
1655        Log.d(tag, label + " size=" + list.size());
1656        for (Object i: list) {
1657            if (i instanceof AppWidgetProviderInfo) {
1658                AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1659                Log.d(tag, "   label=\"" + info.label + "\" previewImage=" + info.previewImage
1660                        + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1661                        + " initialLayout=" + info.initialLayout
1662                        + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1663            } else if (i instanceof ResolveInfo) {
1664                ResolveInfo info = (ResolveInfo) i;
1665                Log.d(tag, "   label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1666                        + info.icon);
1667            }
1668        }
1669    }
1670
1671    @Override
1672    public void surrender() {
1673        // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1674        // should stop this now.
1675
1676        // Stop all background tasks
1677        cancelAllTasks();
1678    }
1679
1680    @Override
1681    public void iconPressed(PagedViewIcon icon) {
1682        // Reset the previously pressed icon and store a reference to the pressed icon so that
1683        // we can reset it on return to Launcher (in Launcher.onResume())
1684        if (mPressedIcon != null) {
1685            mPressedIcon.resetDrawableState();
1686        }
1687        mPressedIcon = icon;
1688    }
1689
1690    public void resetDrawableState() {
1691        if (mPressedIcon != null) {
1692            mPressedIcon.resetDrawableState();
1693            mPressedIcon = null;
1694        }
1695    }
1696
1697    /*
1698     * We load an extra page on each side to prevent flashes from scrolling and loading of the
1699     * widget previews in the background with the AsyncTasks.
1700     */
1701    final static int sLookBehindPageCount = 2;
1702    final static int sLookAheadPageCount = 2;
1703    protected int getAssociatedLowerPageBound(int page) {
1704        final int count = getChildCount();
1705        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1706        int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
1707        return windowMinIndex;
1708    }
1709    protected int getAssociatedUpperPageBound(int page) {
1710        final int count = getChildCount();
1711        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1712        int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
1713                count - 1);
1714        return windowMaxIndex;
1715    }
1716
1717    @Override
1718    protected String getCurrentPageDescription() {
1719        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1720        int stringId = R.string.default_scroll_format;
1721        int count = 0;
1722
1723        if (page < mNumAppsPages) {
1724            stringId = R.string.apps_customize_apps_scroll_format;
1725            count = mNumAppsPages;
1726        } else {
1727            page -= mNumAppsPages;
1728            stringId = R.string.apps_customize_widgets_scroll_format;
1729            count = mNumWidgetPages;
1730        }
1731
1732        return String.format(getContext().getString(stringId), page + 1, count);
1733    }
1734}
1735