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