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