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