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