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