AppsCustomizePagedView.java revision fd39d8ee9512d873aaaa205839ca233c2be4d9d3
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. This is a
551        // workaround until we add a callback from AppWidgetService to AppWidgetHost when widget
552        // packages are added, updated or removed.
553        postDelayed(new Runnable() {
554           public void run() {
555               updatePackages();
556           }
557        }, 1500);
558    }
559
560    public void updatePackages() {
561        // Get the list of widgets and shortcuts
562        boolean wasEmpty = mWidgets.isEmpty();
563        mWidgets.clear();
564        List<AppWidgetProviderInfo> widgets =
565            AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
566        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
567        List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
568        for (AppWidgetProviderInfo widget : widgets) {
569            if (widget.minWidth > 0 && widget.minHeight > 0) {
570                // Ensure that all widgets we show can be added on a workspace of this size
571                int[] spanXY = Launcher.getSpanForWidget(mLauncher, widget);
572                int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, widget);
573                int minSpanX = Math.min(spanXY[0], minSpanXY[0]);
574                int minSpanY = Math.min(spanXY[1], minSpanXY[1]);
575                if (minSpanX <= LauncherModel.getCellCountX() &&
576                        minSpanY <= LauncherModel.getCellCountY()) {
577                    mWidgets.add(widget);
578                } else {
579                    Log.e(TAG, "Widget " + widget.provider + " can not fit on this device (" +
580                            widget.minWidth + ", " + widget.minHeight + ")");
581                }
582            } else {
583                Log.e(TAG, "Widget " + widget.provider + " has invalid dimensions (" +
584                        widget.minWidth + ", " + widget.minHeight + ")");
585            }
586        }
587        mWidgets.addAll(shortcuts);
588        Collections.sort(mWidgets,
589                new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
590        Log.d(TAG, "6549598 updatePackages mWidgets.size(): " + mWidgets.size() + " wasEmpty: " + wasEmpty);
591        updatePageCounts();
592
593        if (wasEmpty) {
594            // The next layout pass will trigger data-ready if both widgets and apps are set, so request
595            // a layout to do this test and invalidate the page data when ready.
596            if (testDataReady()) requestLayout();
597        } else {
598            cancelAllTasks();
599            invalidatePageData();
600        }
601    }
602
603    @Override
604    public void onClick(View v) {
605        // When we have exited all apps or are in transition, disregard clicks
606        if (!mLauncher.isAllAppsCustomizeOpen() ||
607                mLauncher.getWorkspace().isSwitchingState()) return;
608
609        if (v instanceof PagedViewIcon) {
610            // Animate some feedback to the click
611            final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
612
613            // Lock the drawable state to pressed until we return to Launcher
614            if (mPressedIcon != null) {
615                mPressedIcon.lockDrawableState();
616            }
617
618            // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
619            // to be consistent.  So re-enable the flag here, and we will re-disable it as necessary
620            // when Launcher resumes and we are still in AllApps.
621            mLauncher.updateWallpaperVisibility(true);
622            mLauncher.startActivitySafely(v, appInfo.intent, appInfo);
623
624        } else if (v instanceof PagedViewWidget) {
625            // Let the user know that they have to long press to add a widget
626            Toast.makeText(getContext(), R.string.long_press_widget_to_add,
627                    Toast.LENGTH_SHORT).show();
628
629            // Create a little animation to show that the widget can move
630            float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
631            final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
632            AnimatorSet bounce = new AnimatorSet();
633            ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
634            tyuAnim.setDuration(125);
635            ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
636            tydAnim.setDuration(100);
637            bounce.play(tyuAnim).before(tydAnim);
638            bounce.setInterpolator(new AccelerateInterpolator());
639            bounce.start();
640        }
641    }
642
643    public boolean onKey(View v, int keyCode, KeyEvent event) {
644        return FocusHelper.handleAppsCustomizeKeyEvent(v,  keyCode, event);
645    }
646
647    /*
648     * PagedViewWithDraggableItems implementation
649     */
650    @Override
651    protected void determineDraggingStart(android.view.MotionEvent ev) {
652        // Disable dragging by pulling an app down for now.
653    }
654
655    private void beginDraggingApplication(View v) {
656        mLauncher.getWorkspace().onDragStartedWithItem(v);
657        mLauncher.getWorkspace().beginDragShared(v, this);
658    }
659
660    private void preloadWidget(final PendingAddWidgetInfo info) {
661        Log.d(TAG, "6557954 Preload widget: " + info.info);
662        final AppWidgetProviderInfo pInfo = info.info;
663        if (pInfo.configure != null) {
664            return;
665        }
666
667        mWidgetCleanupState = WIDGET_PRELOAD_PENDING;
668        mBindWidgetRunnable = new Runnable() {
669            @Override
670            public void run() {
671                Log.d(TAG, "    6557954 Preload, bind widget: " + info.info);
672                mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId();
673                if (AppWidgetManager.getInstance(mLauncher)
674                            .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) {
675                    mWidgetCleanupState = WIDGET_BOUND;
676                }
677            }
678        };
679        post(mBindWidgetRunnable);
680
681        mInflateWidgetRunnable = new Runnable() {
682            @Override
683            public void run() {
684                AppWidgetHostView hostView = mLauncher.
685                        getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo);
686                info.boundWidget = hostView;
687                Log.d(TAG, "    6557954 Preload, inflate widget: " + info.info);
688                mWidgetCleanupState = WIDGET_INFLATED;
689                hostView.setVisibility(INVISIBLE);
690                int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX,
691                        info.spanY, info, false);
692
693                // We want the first widget layout to be the correct size. This will be important
694                // for width size reporting to the AppWidgetManager.
695                DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0],
696                        unScaledSize[1]);
697                lp.x = lp.y = 0;
698                lp.customPosition = true;
699                hostView.setLayoutParams(lp);
700                mLauncher.getDragLayer().addView(hostView);
701            }
702        };
703        post(mInflateWidgetRunnable);
704    }
705
706    @Override
707    public void onShortPress(View v) {
708        // We are anticipating a long press, and we use this time to load bind and instantiate
709        // the widget. This will need to be cleaned up if it turns out no long press occurs.
710        if (mCreateWidgetInfo != null) {
711            // Just in case the cleanup process wasn't properly executed. This shouldn't happen.
712            Log.d(TAG, "**** 6557954 Previous shortpress not cleaned up, cleaning up now: " + mCreateWidgetInfo.info);
713            cleanupWidgetPreloading(false);
714        }
715        mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag());
716        Log.d(TAG, "6557954 Short press triggered for view: " + v + ", widget info: " + mCreateWidgetInfo.info);
717        preloadWidget(mCreateWidgetInfo);
718    }
719
720    private void cleanupWidgetPreloading(boolean widgetWasAdded) {
721        Log.d(TAG, "6557954 Cleaning up widget, was added: " + widgetWasAdded);
722        if (mCreateWidgetInfo != null) {
723            Log.d(TAG, "    6557954 Cleaning up widget, widget info: " + mCreateWidgetInfo.info);
724        }
725
726        if (!widgetWasAdded) {
727            // If the widget was not added, we may need to do further cleanup.
728            PendingAddWidgetInfo info = mCreateWidgetInfo;
729            mCreateWidgetInfo = null;
730
731            if (mWidgetCleanupState == WIDGET_PRELOAD_PENDING) {
732                Log.d(TAG, "    6557954 Cleaning up widget, remove preload callbacks");
733                // We never did any preloading, so just remove pending callbacks to do so
734                removeCallbacks(mBindWidgetRunnable);
735                removeCallbacks(mInflateWidgetRunnable);
736            } else if (mWidgetCleanupState == WIDGET_BOUND) {
737                 // Delete the widget id which was allocated
738                if (mWidgetLoadingId != -1) {
739                    Log.d(TAG, "    6557954 Cleaning up widget, delete widget id");
740                    mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
741                }
742
743                // We never got around to inflating the widget, so remove the callback to do so.
744                Log.d(TAG, "    6557954 Cleaning up widget, remove callbacks");
745                removeCallbacks(mInflateWidgetRunnable);
746            } else if (mWidgetCleanupState == WIDGET_INFLATED) {
747                // Delete the widget id which was allocated
748                if (mWidgetLoadingId != -1) {
749                    Log.d(TAG, "    6557954 Cleaning up widget, delete widget id");
750                    mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
751                }
752
753                // The widget was inflated and added to the DragLayer -- remove it.
754                Log.d(TAG, "    6557954 Cleaning up widget, remove inflated widget from draglayer");
755                AppWidgetHostView widget = info.boundWidget;
756                mLauncher.getDragLayer().removeView(widget);
757            }
758        }
759        mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
760        mWidgetLoadingId = -1;
761        mCreateWidgetInfo = null;
762        PagedViewWidget.resetShortPressTarget();
763    }
764
765    @Override
766    public void cleanUpShortPress(View v) {
767        Log.d(TAG, "6557954 Cleanup shortpress");
768        if (!mDraggingWidget) {
769            Log.d(TAG, "    6557954 Cleanup shortpress, cleanup cleanup preloading");
770            cleanupWidgetPreloading(false);
771        }
772    }
773
774    private boolean beginDraggingWidget(View v) {
775        mDraggingWidget = true;
776        // Get the widget preview as the drag representation
777        ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
778        PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
779
780        if (createItemInfo instanceof PendingAddWidgetInfo) {
781            PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
782            Log.d(TAG, "6557954 Begin dragging widget, view: " + v + ", widget info: " + createWidgetInfo.info);
783        }
784
785        // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
786        // we abort the drag.
787        if (image.getDrawable() == null) {
788            Log.d(TAG, "    6557954 Begin dragging widget, abort, no drawable set");
789            mDraggingWidget = false;
790            return false;
791        }
792
793        // Compose the drag image
794        Bitmap preview;
795        Bitmap outline;
796        float scale = 1f;
797        if (createItemInfo instanceof PendingAddWidgetInfo) {
798            // This can happen in some weird cases involving multi-touch. We can't start dragging
799            // the widget if this is null, so we break out.
800            if (mCreateWidgetInfo == null) {
801                return false;
802            }
803
804            PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
805            createItemInfo = createWidgetInfo;
806            int spanX = createItemInfo.spanX;
807            int spanY = createItemInfo.spanY;
808            int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY,
809                    createWidgetInfo, true);
810
811            FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
812            float minScale = 1.25f;
813            int maxWidth, maxHeight;
814            maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
815            maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
816            preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
817                    createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight);
818
819            // Determine the image view drawable scale relative to the preview
820            float[] mv = new float[9];
821            Matrix m = new Matrix();
822            m.setRectToRect(
823                    new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
824                    new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
825                            (float) previewDrawable.getIntrinsicHeight()),
826                    Matrix.ScaleToFit.START);
827            m.getValues(mv);
828            scale = (float) mv[0];
829        } else {
830            PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
831            Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
832            preview = Bitmap.createBitmap(icon.getIntrinsicWidth(),
833                    icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
834
835            mCanvas.setBitmap(preview);
836            mCanvas.save();
837            renderDrawableToBitmap(icon, preview, 0, 0,
838                    icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
839            mCanvas.restore();
840            mCanvas.setBitmap(null);
841            createItemInfo.spanX = createItemInfo.spanY = 1;
842        }
843
844        // We use a custom alpha clip table for the default widget previews
845        Paint alphaClipPaint = null;
846        if (createItemInfo instanceof PendingAddWidgetInfo) {
847            if (((PendingAddWidgetInfo) createItemInfo).previewImage != 0) {
848                MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255);
849                alphaClipPaint = new Paint();
850                alphaClipPaint.setMaskFilter(alphaClipTable);
851            }
852        }
853
854        // Save the preview for the outline generation, then dim the preview
855        outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(),
856                false);
857
858        // Start the drag
859        alphaClipPaint = null;
860        mLauncher.lockScreenOrientation();
861        mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, alphaClipPaint);
862        mDragController.startDrag(image, preview, this, createItemInfo,
863                DragController.DRAG_ACTION_COPY, null, scale);
864        outline.recycle();
865        preview.recycle();
866        return true;
867    }
868
869    @Override
870    protected boolean beginDragging(final View v) {
871        if (!super.beginDragging(v)) return false;
872
873        if (v instanceof PagedViewIcon) {
874            beginDraggingApplication(v);
875        } else if (v instanceof PagedViewWidget) {
876            if (!beginDraggingWidget(v)) {
877                return false;
878            }
879        }
880
881        // We delay entering spring-loaded mode slightly to make sure the UI
882        // thready is free of any work.
883        postDelayed(new Runnable() {
884            @Override
885            public void run() {
886                // We don't enter spring-loaded mode if the drag has been cancelled
887                if (mLauncher.getDragController().isDragging()) {
888                    // Dismiss the cling
889                    mLauncher.dismissAllAppsCling(null);
890
891                    // Reset the alpha on the dragged icon before we drag
892                    resetDrawableState();
893
894                    // Go into spring loaded mode (must happen before we startDrag())
895                    mLauncher.enterSpringLoadedDragMode();
896                }
897            }
898        }, 150);
899
900        return true;
901    }
902
903    /**
904     * Clean up after dragging.
905     *
906     * @param target where the item was dragged to (can be null if the item was flung)
907     */
908    private void endDragging(View target, boolean isFlingToDelete, boolean success) {
909        if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() &&
910                !(target instanceof DeleteDropTarget))) {
911            // Exit spring loaded mode if we have not successfully dropped or have not handled the
912            // drop in Workspace
913            mLauncher.exitSpringLoadedDragMode();
914        }
915        mLauncher.unlockScreenOrientation(false);
916    }
917
918    @Override
919    public View getContent() {
920        return null;
921    }
922
923    @Override
924    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
925        mInTransition = true;
926        if (toWorkspace) {
927            cancelAllTasks();
928        }
929    }
930
931    @Override
932    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
933    }
934
935    @Override
936    public void onLauncherTransitionStep(Launcher l, float t) {
937    }
938
939    @Override
940    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
941        Log.d(TAG, "6549598 onLauncherTransitionEnd");
942        mInTransition = false;
943        for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
944            onSyncWidgetPageItems(d);
945        }
946        mDeferredSyncWidgetPageItems.clear();
947        mForceDrawAllChildrenNextFrame = !toWorkspace;
948    }
949
950    @Override
951    public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
952            boolean success) {
953        // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
954        if (isFlingToDelete) return;
955
956        endDragging(target, false, success);
957
958        // Display an error message if the drag failed due to there not being enough space on the
959        // target layout we were dropping on.
960        if (!success) {
961            boolean showOutOfSpaceMessage = false;
962            if (target instanceof Workspace) {
963                int currentScreen = mLauncher.getCurrentWorkspaceScreen();
964                Workspace workspace = (Workspace) target;
965                CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
966                ItemInfo itemInfo = (ItemInfo) d.dragInfo;
967                if (layout != null) {
968                    layout.calculateSpans(itemInfo);
969                    showOutOfSpaceMessage =
970                            !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
971                }
972            }
973            if (showOutOfSpaceMessage) {
974                mLauncher.showOutOfSpaceMessage(false);
975            }
976
977            d.deferDragViewCleanupPostAnimation = false;
978        }
979        cleanupWidgetPreloading(success);
980        mDraggingWidget = false;
981    }
982
983    @Override
984    public void onFlingToDeleteCompleted() {
985        // We just dismiss the drag when we fling, so cleanup here
986        endDragging(null, true, true);
987        cleanupWidgetPreloading(false);
988        mDraggingWidget = false;
989    }
990
991    @Override
992    public boolean supportsFlingToDelete() {
993        return true;
994    }
995
996    @Override
997    protected void onDetachedFromWindow() {
998        super.onDetachedFromWindow();
999        cancelAllTasks();
1000    }
1001
1002    public void clearAllWidgetPages() {
1003        cancelAllTasks();
1004        int count = getChildCount();
1005        for (int i = 0; i < count; i++) {
1006            View v = getPageAt(i);
1007            if (v instanceof PagedViewGridLayout) {
1008                ((PagedViewGridLayout) v).removeAllViewsOnPage();
1009                mDirtyPageContent.set(i, true);
1010            }
1011        }
1012    }
1013
1014    private void cancelAllTasks() {
1015        // Clean up all the async tasks
1016        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1017        while (iter.hasNext()) {
1018            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1019            task.cancel(false);
1020            iter.remove();
1021            mDirtyPageContent.set(task.page, true);
1022
1023            // We've already preallocated the views for the data to load into, so clear them as well
1024            View v = getPageAt(task.page);
1025            if (v instanceof PagedViewGridLayout) {
1026                ((PagedViewGridLayout) v).removeAllViewsOnPage();
1027            }
1028        }
1029        mDeferredSyncWidgetPageItems.clear();
1030    }
1031
1032    public void setContentType(ContentType type) {
1033        Log.d(TAG, "6549598 setContentType mNumAppsPages: " + mNumAppsPages);
1034        if (type == ContentType.Widgets) {
1035            invalidatePageData(mNumAppsPages, true);
1036        } else if (type == ContentType.Applications) {
1037            invalidatePageData(0, true);
1038        }
1039    }
1040
1041    protected void snapToPage(int whichPage, int delta, int duration) {
1042        super.snapToPage(whichPage, delta, duration);
1043        updateCurrentTab(whichPage);
1044
1045        // Update the thread priorities given the direction lookahead
1046        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1047        while (iter.hasNext()) {
1048            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1049            int pageIndex = task.page;
1050            if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
1051                (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
1052                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1053            } else {
1054                task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
1055            }
1056        }
1057    }
1058
1059    private void updateCurrentTab(int currentPage) {
1060        Log.d(TAG, "6549598 updateCurrentTab mNumAppsPages: " + mNumAppsPages);
1061        AppsCustomizeTabHost tabHost = getTabHost();
1062        if (tabHost != null) {
1063            String tag = tabHost.getCurrentTabTag();
1064            if (tag != null) {
1065                if (currentPage >= mNumAppsPages &&
1066                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
1067                    tabHost.setCurrentTabFromContent(ContentType.Widgets);
1068                } else if (currentPage < mNumAppsPages &&
1069                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1070                    tabHost.setCurrentTabFromContent(ContentType.Applications);
1071                }
1072            }
1073        }
1074    }
1075
1076    /*
1077     * Apps PagedView implementation
1078     */
1079    private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
1080        int childCount = layout.getChildCount();
1081        for (int i = 0; i < childCount; ++i) {
1082            layout.getChildAt(i).setVisibility(visibility);
1083        }
1084    }
1085    private void setupPage(PagedViewCellLayout layout) {
1086        layout.setCellCount(mCellCountX, mCellCountY);
1087        layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
1088        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1089                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1090
1091        // Note: We force a measure here to get around the fact that when we do layout calculations
1092        // immediately after syncing, we don't have a proper width.  That said, we already know the
1093        // expected page width, so we can actually optimize by hiding all the TextView-based
1094        // children that are expensive to measure, and let that happen naturally later.
1095        setVisibilityOnChildren(layout, View.GONE);
1096        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1097        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
1098        layout.setMinimumWidth(getPageContentWidth());
1099        layout.measure(widthSpec, heightSpec);
1100        setVisibilityOnChildren(layout, View.VISIBLE);
1101    }
1102
1103    public void syncAppsPageItems(int page, boolean immediate) {
1104        Log.d(TAG, "6549598 syncAppsPageItems page: " + page);
1105        // ensure that we have the right number of items on the pages
1106        int numCells = mCellCountX * mCellCountY;
1107        int startIndex = page * numCells;
1108        int endIndex = Math.min(startIndex + numCells, mApps.size());
1109        PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
1110
1111        layout.removeAllViewsOnPage();
1112        ArrayList<Object> items = new ArrayList<Object>();
1113        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
1114        for (int i = startIndex; i < endIndex; ++i) {
1115            ApplicationInfo info = mApps.get(i);
1116            PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
1117                    R.layout.apps_customize_application, layout, false);
1118            icon.applyFromApplicationInfo(info, true, this);
1119            icon.setOnClickListener(this);
1120            icon.setOnLongClickListener(this);
1121            icon.setOnTouchListener(this);
1122            icon.setOnKeyListener(this);
1123
1124            int index = i - startIndex;
1125            int x = index % mCellCountX;
1126            int y = index / mCellCountX;
1127            layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
1128
1129            items.add(info);
1130            images.add(info.iconBitmap);
1131        }
1132
1133        layout.createHardwareLayers();
1134    }
1135
1136    /**
1137     * A helper to return the priority for loading of the specified widget page.
1138     */
1139    private int getWidgetPageLoadPriority(int page) {
1140        // If we are snapping to another page, use that index as the target page index
1141        int toPage = mCurrentPage;
1142        if (mNextPage > -1) {
1143            toPage = mNextPage;
1144        }
1145
1146        // We use the distance from the target page as an initial guess of priority, but if there
1147        // are no pages of higher priority than the page specified, then bump up the priority of
1148        // the specified page.
1149        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1150        int minPageDiff = Integer.MAX_VALUE;
1151        while (iter.hasNext()) {
1152            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1153            minPageDiff = Math.abs(task.page - toPage);
1154        }
1155
1156        int rawPageDiff = Math.abs(page - toPage);
1157        return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
1158    }
1159    /**
1160     * Return the appropriate thread priority for loading for a given page (we give the current
1161     * page much higher priority)
1162     */
1163    private int getThreadPriorityForPage(int page) {
1164        // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
1165        int pageDiff = getWidgetPageLoadPriority(page);
1166        if (pageDiff <= 0) {
1167            return Process.THREAD_PRIORITY_LESS_FAVORABLE;
1168        } else if (pageDiff <= 1) {
1169            return Process.THREAD_PRIORITY_LOWEST;
1170        } else {
1171            return Process.THREAD_PRIORITY_LOWEST;
1172        }
1173    }
1174    private int getSleepForPage(int page) {
1175        int pageDiff = getWidgetPageLoadPriority(page);
1176        return Math.max(0, pageDiff * sPageSleepDelay);
1177    }
1178    /**
1179     * Creates and executes a new AsyncTask to load a page of widget previews.
1180     */
1181    private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
1182            int cellWidth, int cellHeight, int cellCountX) {
1183
1184        // Prune all tasks that are no longer needed
1185        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1186        while (iter.hasNext()) {
1187            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1188            int taskPage = task.page;
1189            if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
1190                    taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
1191                task.cancel(false);
1192                iter.remove();
1193            } else {
1194                task.setThreadPriority(getThreadPriorityForPage(taskPage));
1195            }
1196        }
1197
1198        // We introduce a slight delay to order the loading of side pages so that we don't thrash
1199        final int sleepMs = getSleepForPage(page);
1200        AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
1201            new AsyncTaskCallback() {
1202                @Override
1203                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1204                    try {
1205                        try {
1206                            Thread.sleep(sleepMs);
1207                        } catch (Exception e) {}
1208                        loadWidgetPreviewsInBackground(task, data);
1209                    } finally {
1210                        if (task.isCancelled()) {
1211                            data.cleanup(true);
1212                        }
1213                    }
1214                }
1215            },
1216            new AsyncTaskCallback() {
1217                @Override
1218                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1219                    mRunningTasks.remove(task);
1220                    if (task.isCancelled()) return;
1221                    // do cleanup inside onSyncWidgetPageItems
1222                    onSyncWidgetPageItems(data);
1223                }
1224            });
1225
1226        // Ensure that the task is appropriately prioritized and runs in parallel
1227        AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
1228                AsyncTaskPageData.Type.LoadWidgetPreviewData);
1229        t.setThreadPriority(getThreadPriorityForPage(page));
1230        t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
1231        mRunningTasks.add(t);
1232    }
1233
1234    /*
1235     * Widgets PagedView implementation
1236     */
1237    private void setupPage(PagedViewGridLayout layout) {
1238        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1239                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1240
1241        // Note: We force a measure here to get around the fact that when we do layout calculations
1242        // immediately after syncing, we don't have a proper width.
1243        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1244        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
1245        layout.setMinimumWidth(getPageContentWidth());
1246        layout.measure(widthSpec, heightSpec);
1247    }
1248
1249    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
1250        renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
1251    }
1252
1253    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
1254            float scale) {
1255        if (bitmap != null) {
1256            Canvas c = new Canvas(bitmap);
1257            c.scale(scale, scale);
1258            Rect oldBounds = d.copyBounds();
1259            d.setBounds(x, y, x + w, y + h);
1260            d.draw(c);
1261            d.setBounds(oldBounds); // Restore the bounds
1262            c.setBitmap(null);
1263        }
1264    }
1265
1266    private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
1267        Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
1268        final Canvas c = mCachedShortcutPreviewCanvas.get();
1269        if (tempBitmap == null ||
1270                tempBitmap.getWidth() != maxWidth ||
1271                tempBitmap.getHeight() != maxHeight) {
1272            tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1273            mCachedShortcutPreviewBitmap.set(tempBitmap);
1274        } else {
1275            c.setBitmap(tempBitmap);
1276            c.drawColor(0, PorterDuff.Mode.CLEAR);
1277            c.setBitmap(null);
1278        }
1279        // Render the icon
1280        Drawable icon = mIconCache.getFullResIcon(info);
1281
1282        int paddingTop =
1283                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
1284        int paddingLeft =
1285                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
1286        int paddingRight =
1287                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
1288
1289        int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
1290        float scaleSize = scaledIconWidth / (float) mAppIconSize;
1291
1292        renderDrawableToBitmap(
1293                icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
1294
1295        Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1296        c.setBitmap(preview);
1297        Paint p = mCachedShortcutPreviewPaint.get();
1298        if (p == null) {
1299            p = new Paint();
1300            ColorMatrix colorMatrix = new ColorMatrix();
1301            colorMatrix.setSaturation(0);
1302            p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
1303            p.setAlpha((int) (255 * 0.06f));
1304            //float density = 1f;
1305            //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
1306            mCachedShortcutPreviewPaint.set(p);
1307        }
1308        c.drawBitmap(tempBitmap, 0, 0, p);
1309        c.setBitmap(null);
1310
1311        renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
1312
1313        return preview;
1314    }
1315
1316    private Bitmap getWidgetPreview(ComponentName provider, int previewImage,
1317            int iconId, int cellHSpan, int cellVSpan, int maxWidth,
1318            int maxHeight) {
1319        // Load the preview image if possible
1320        String packageName = provider.getPackageName();
1321        if (maxWidth < 0) maxWidth = Integer.MAX_VALUE;
1322        if (maxHeight < 0) maxHeight = Integer.MAX_VALUE;
1323
1324        Drawable drawable = null;
1325        if (previewImage != 0) {
1326            drawable = mPackageManager.getDrawable(packageName, previewImage, null);
1327            if (drawable == null) {
1328                Log.w(TAG, "Can't load widget preview drawable 0x" +
1329                        Integer.toHexString(previewImage) + " for provider: " + provider);
1330            }
1331        }
1332
1333        int bitmapWidth;
1334        int bitmapHeight;
1335        Bitmap defaultPreview = null;
1336        boolean widgetPreviewExists = (drawable != null);
1337        if (widgetPreviewExists) {
1338            bitmapWidth = drawable.getIntrinsicWidth();
1339            bitmapHeight = drawable.getIntrinsicHeight();
1340        } else {
1341            // Generate a preview image if we couldn't load one
1342            if (cellHSpan < 1) cellHSpan = 1;
1343            if (cellVSpan < 1) cellVSpan = 1;
1344
1345            BitmapDrawable previewDrawable = (BitmapDrawable) getResources()
1346                    .getDrawable(R.drawable.widget_preview_tile);
1347            final int previewDrawableWidth = previewDrawable
1348                    .getIntrinsicWidth();
1349            final int previewDrawableHeight = previewDrawable
1350                    .getIntrinsicHeight();
1351            bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
1352            bitmapHeight = previewDrawableHeight * cellVSpan;
1353
1354            defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1355                    Config.ARGB_8888);
1356            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1357            c.setBitmap(defaultPreview);
1358            previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
1359            previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
1360                    Shader.TileMode.REPEAT);
1361            previewDrawable.draw(c);
1362            c.setBitmap(null);
1363
1364            // Draw the icon in the top left corner
1365            int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1366            int smallestSide = Math.min(bitmapWidth, bitmapHeight);
1367            float iconScale = Math.min((float) smallestSide
1368                    / (mAppIconSize + 2 * minOffset), 1f);
1369
1370            try {
1371                Drawable icon = null;
1372                int hoffset =
1373                        (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
1374                int yoffset =
1375                        (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
1376                if (iconId > 0)
1377                    icon = mIconCache.getFullResIcon(packageName, iconId);
1378                Resources resources = mLauncher.getResources();
1379                if (icon != null) {
1380                    renderDrawableToBitmap(icon, defaultPreview, hoffset,
1381                            yoffset, (int) (mAppIconSize * iconScale),
1382                            (int) (mAppIconSize * iconScale));
1383                }
1384            } catch (Resources.NotFoundException e) {
1385            }
1386        }
1387
1388        // Scale to fit width only - let the widget preview be clipped in the
1389        // vertical dimension
1390        float scale = 1f;
1391        if (bitmapWidth > maxWidth) {
1392            scale = maxWidth / (float) bitmapWidth;
1393        }
1394        if (scale != 1f) {
1395            bitmapWidth = (int) (scale * bitmapWidth);
1396            bitmapHeight = (int) (scale * bitmapHeight);
1397        }
1398
1399        Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1400                Config.ARGB_8888);
1401
1402        // Draw the scaled preview into the final bitmap
1403        if (widgetPreviewExists) {
1404            renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth,
1405                    bitmapHeight);
1406        } else {
1407            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1408            final Rect src = mCachedAppWidgetPreviewSrcRect.get();
1409            final Rect dest = mCachedAppWidgetPreviewDestRect.get();
1410            c.setBitmap(preview);
1411            src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
1412            dest.set(0, 0, preview.getWidth(), preview.getHeight());
1413
1414            Paint p = mCachedAppWidgetPreviewPaint.get();
1415            if (p == null) {
1416                p = new Paint();
1417                p.setFilterBitmap(true);
1418                mCachedAppWidgetPreviewPaint.set(p);
1419            }
1420            c.drawBitmap(defaultPreview, src, dest, p);
1421            c.setBitmap(null);
1422        }
1423        return preview;
1424    }
1425
1426    public void syncWidgetPageItems(final int page, final boolean immediate) {
1427        Log.d(TAG, "6549598 syncWidgetPageItems page: " + page);
1428        int numItemsPerPage = mWidgetCountX * mWidgetCountY;
1429
1430        // Calculate the dimensions of each cell we are giving to each widget
1431        final ArrayList<Object> items = new ArrayList<Object>();
1432        int contentWidth = mWidgetSpacingLayout.getContentWidth();
1433        final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
1434                - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
1435        int contentHeight = mWidgetSpacingLayout.getContentHeight();
1436        final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
1437                - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
1438
1439        // Prepare the set of widgets to load previews for in the background
1440        int offset = (page - mNumAppsPages) * numItemsPerPage;
1441        for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1442            items.add(mWidgets.get(i));
1443        }
1444
1445        // Prepopulate the pages with the other widget info, and fill in the previews later
1446        final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1447        layout.setColumnCount(layout.getCellCountX());
1448        for (int i = 0; i < items.size(); ++i) {
1449            Object rawInfo = items.get(i);
1450            PendingAddItemInfo createItemInfo = null;
1451            PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1452                    R.layout.apps_customize_widget, layout, false);
1453            if (rawInfo instanceof AppWidgetProviderInfo) {
1454                // Fill in the widget information
1455                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1456                createItemInfo = new PendingAddWidgetInfo(info, null, null);
1457
1458                // Determine the widget spans and min resize spans.
1459                int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
1460                createItemInfo.spanX = spanXY[0];
1461                createItemInfo.spanY = spanXY[1];
1462                int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
1463                createItemInfo.minSpanX = minSpanXY[0];
1464                createItemInfo.minSpanY = minSpanXY[1];
1465
1466                widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
1467                widget.setTag(createItemInfo);
1468                widget.setShortPressListener(this);
1469            } else if (rawInfo instanceof ResolveInfo) {
1470                // Fill in the shortcuts information
1471                ResolveInfo info = (ResolveInfo) rawInfo;
1472                createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
1473                createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1474                createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1475                        info.activityInfo.name);
1476                widget.applyFromResolveInfo(mPackageManager, info);
1477                widget.setTag(createItemInfo);
1478            }
1479            widget.setOnClickListener(this);
1480            widget.setOnLongClickListener(this);
1481            widget.setOnTouchListener(this);
1482            widget.setOnKeyListener(this);
1483
1484            // Layout each widget
1485            int ix = i % mWidgetCountX;
1486            int iy = i / mWidgetCountX;
1487            GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1488                    GridLayout.spec(iy, GridLayout.LEFT),
1489                    GridLayout.spec(ix, GridLayout.TOP));
1490            lp.width = cellWidth;
1491            lp.height = cellHeight;
1492            lp.setGravity(Gravity.TOP | Gravity.LEFT);
1493            if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1494            if (iy > 0) lp.topMargin = mWidgetHeightGap;
1495            layout.addView(widget, lp);
1496        }
1497
1498        // wait until a call on onLayout to start loading, because
1499        // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
1500        // TODO: can we do a measure/layout immediately?
1501        layout.setOnLayoutListener(new Runnable() {
1502            public void run() {
1503                // Load the widget previews
1504                int maxPreviewWidth = cellWidth;
1505                int maxPreviewHeight = cellHeight;
1506                if (layout.getChildCount() > 0) {
1507                    PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
1508                    int[] maxSize = w.getPreviewSize();
1509                    maxPreviewWidth = maxSize[0];
1510                    maxPreviewHeight = maxSize[1];
1511                }
1512                if (immediate) {
1513                    AsyncTaskPageData data = new AsyncTaskPageData(page, items,
1514                            maxPreviewWidth, maxPreviewHeight, null, null);
1515                    loadWidgetPreviewsInBackground(null, data);
1516                    onSyncWidgetPageItems(data);
1517                } else {
1518                    prepareLoadWidgetPreviewsTask(page, items,
1519                            maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
1520                }
1521            }
1522        });
1523    }
1524    private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1525            AsyncTaskPageData data) {
1526        // loadWidgetPreviewsInBackground can be called without a task to load a set of widget
1527        // previews synchronously
1528        if (task != null) {
1529            // Ensure that this task starts running at the correct priority
1530            task.syncThreadPriority();
1531        }
1532
1533        // Load each of the widget/shortcut previews
1534        ArrayList<Object> items = data.items;
1535        ArrayList<Bitmap> images = data.generatedImages;
1536        int count = items.size();
1537        for (int i = 0; i < count; ++i) {
1538            if (task != null) {
1539                // Ensure we haven't been cancelled yet
1540                if (task.isCancelled()) break;
1541                // Before work on each item, ensure that this task is running at the correct
1542                // priority
1543                task.syncThreadPriority();
1544            }
1545
1546            Object rawInfo = items.get(i);
1547            if (rawInfo instanceof AppWidgetProviderInfo) {
1548                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1549                int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
1550
1551                int maxWidth = Math.min(data.maxImageWidth,
1552                        mWidgetSpacingLayout.estimateCellWidth(cellSpans[0]));
1553                int maxHeight = Math.min(data.maxImageHeight,
1554                        mWidgetSpacingLayout.estimateCellHeight(cellSpans[1]));
1555                Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon,
1556                        cellSpans[0], cellSpans[1], maxWidth, maxHeight);
1557                images.add(b);
1558            } else if (rawInfo instanceof ResolveInfo) {
1559                // Fill in the shortcuts information
1560                ResolveInfo info = (ResolveInfo) rawInfo;
1561                images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight));
1562            }
1563        }
1564    }
1565
1566    private void onSyncWidgetPageItems(AsyncTaskPageData data) {
1567        if (mInTransition) {
1568            mDeferredSyncWidgetPageItems.add(data);
1569            return;
1570        }
1571        try {
1572            int page = data.page;
1573            PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1574
1575            ArrayList<Object> items = data.items;
1576            int count = items.size();
1577            for (int i = 0; i < count; ++i) {
1578                PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1579                if (widget != null) {
1580                    Bitmap preview = data.generatedImages.get(i);
1581                    widget.applyPreview(new FastBitmapDrawable(preview), i);
1582                }
1583            }
1584
1585            layout.createHardwareLayer();
1586            invalidate();
1587
1588            // Update all thread priorities
1589            Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1590            while (iter.hasNext()) {
1591                AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1592                int pageIndex = task.page;
1593                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1594            }
1595        } finally {
1596            data.cleanup(false);
1597        }
1598    }
1599
1600    @Override
1601    public void syncPages() {
1602        removeAllViews();
1603        cancelAllTasks();
1604
1605        Context context = getContext();
1606        for (int j = 0; j < mNumWidgetPages; ++j) {
1607            PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1608                    mWidgetCountY);
1609            setupPage(layout);
1610            addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
1611                    LayoutParams.MATCH_PARENT));
1612        }
1613
1614        for (int i = 0; i < mNumAppsPages; ++i) {
1615            PagedViewCellLayout layout = new PagedViewCellLayout(context);
1616            setupPage(layout);
1617            addView(layout);
1618        }
1619
1620        Log.d(TAG, "6549598 syncPages mNumAppsPages: " + mNumAppsPages + " mNumWidgetPages: " + mNumWidgetPages);
1621    }
1622
1623    @Override
1624    public void syncPageItems(int page, boolean immediate) {
1625        Log.d(TAG, "6549598 syncPageItems page: " + page + " immediate: " + immediate);
1626        if (page < mNumAppsPages) {
1627            syncAppsPageItems(page, immediate);
1628        } else {
1629            syncWidgetPageItems(page, immediate);
1630        }
1631    }
1632
1633    // We want our pages to be z-ordered such that the further a page is to the left, the higher
1634    // it is in the z-order. This is important to insure touch events are handled correctly.
1635    View getPageAt(int index) {
1636        return getChildAt(indexToPage(index));
1637    }
1638
1639    @Override
1640    protected int indexToPage(int index) {
1641        return getChildCount() - index - 1;
1642    }
1643
1644    // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1645    @Override
1646    protected void screenScrolled(int screenCenter) {
1647        super.screenScrolled(screenCenter);
1648
1649        for (int i = 0; i < getChildCount(); i++) {
1650            View v = getPageAt(i);
1651            if (v != null) {
1652                float scrollProgress = getScrollProgress(screenCenter, v, i);
1653
1654                float interpolatedProgress =
1655                        mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1656                float scale = (1 - interpolatedProgress) +
1657                        interpolatedProgress * TRANSITION_SCALE_FACTOR;
1658                float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
1659
1660                float alpha;
1661
1662                if (scrollProgress < 0) {
1663                    alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
1664                        1 - Math.abs(scrollProgress)) : 1.0f;
1665                } else {
1666                    // On large screens we need to fade the page as it nears its leftmost position
1667                    alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1668                }
1669
1670                v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1671                int pageWidth = v.getMeasuredWidth();
1672                int pageHeight = v.getMeasuredHeight();
1673
1674                if (PERFORM_OVERSCROLL_ROTATION) {
1675                    if (i == 0 && scrollProgress < 0) {
1676                        // Overscroll to the left
1677                        v.setPivotX(TRANSITION_PIVOT * pageWidth);
1678                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1679                        scale = 1.0f;
1680                        alpha = 1.0f;
1681                        // On the first page, we don't want the page to have any lateral motion
1682                        translationX = 0;
1683                    } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1684                        // Overscroll to the right
1685                        v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1686                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1687                        scale = 1.0f;
1688                        alpha = 1.0f;
1689                        // On the last page, we don't want the page to have any lateral motion.
1690                        translationX = 0;
1691                    } else {
1692                        v.setPivotY(pageHeight / 2.0f);
1693                        v.setPivotX(pageWidth / 2.0f);
1694                        v.setRotationY(0f);
1695                    }
1696                }
1697
1698                v.setTranslationX(translationX);
1699                v.setScaleX(scale);
1700                v.setScaleY(scale);
1701                v.setAlpha(alpha);
1702
1703                // If the view has 0 alpha, we set it to be invisible so as to prevent
1704                // it from accepting touches
1705                if (alpha == 0) {
1706                    v.setVisibility(INVISIBLE);
1707                } else if (v.getVisibility() != VISIBLE) {
1708                    v.setVisibility(VISIBLE);
1709                }
1710            }
1711        }
1712    }
1713
1714    protected void overScroll(float amount) {
1715        acceleratedOverScroll(amount);
1716    }
1717
1718    /**
1719     * Used by the parent to get the content width to set the tab bar to
1720     * @return
1721     */
1722    public int getPageContentWidth() {
1723        return mContentWidth;
1724    }
1725
1726    @Override
1727    protected void onPageEndMoving() {
1728        super.onPageEndMoving();
1729        mForceDrawAllChildrenNextFrame = true;
1730        // We reset the save index when we change pages so that it will be recalculated on next
1731        // rotation
1732        mSaveInstanceStateItemIndex = -1;
1733    }
1734
1735    /*
1736     * AllAppsView implementation
1737     */
1738    @Override
1739    public void setup(Launcher launcher, DragController dragController) {
1740        mLauncher = launcher;
1741        mDragController = dragController;
1742    }
1743    @Override
1744    public void zoom(float zoom, boolean animate) {
1745        // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1746    }
1747    @Override
1748    public boolean isVisible() {
1749        return (getVisibility() == VISIBLE);
1750    }
1751    @Override
1752    public boolean isAnimating() {
1753        return false;
1754    }
1755    @Override
1756    public void setApps(ArrayList<ApplicationInfo> list) {
1757        mApps = list;
1758        Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
1759        Log.d(TAG, "6549598 setApps mApps.size(): " + mApps.size());
1760        updatePageCounts();
1761
1762        // The next layout pass will trigger data-ready if both widgets and apps are set, so
1763        // request a layout to do this test and invalidate the page data when ready.
1764        if (testDataReady()) requestLayout();
1765    }
1766    private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1767        // We add it in place, in alphabetical order
1768        int count = list.size();
1769        for (int i = 0; i < count; ++i) {
1770            ApplicationInfo info = list.get(i);
1771            int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1772            if (index < 0) {
1773                mApps.add(-(index + 1), info);
1774            }
1775        }
1776    }
1777    @Override
1778    public void addApps(ArrayList<ApplicationInfo> list) {
1779        addAppsWithoutInvalidate(list);
1780        Log.d(TAG, "6549598 addApps mApps.size(): " + mApps.size() + " list.size(): " + list.size());
1781        updatePageCounts();
1782        invalidatePageData();
1783        Log.d(TAG, "6549598 addApps mNumAppsPages: " + mNumAppsPages);
1784    }
1785    private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1786        ComponentName removeComponent = item.intent.getComponent();
1787        int length = list.size();
1788        for (int i = 0; i < length; ++i) {
1789            ApplicationInfo info = list.get(i);
1790            if (info.intent.getComponent().equals(removeComponent)) {
1791                return i;
1792            }
1793        }
1794        return -1;
1795    }
1796    private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1797        // loop through all the apps and remove apps that have the same component
1798        int length = list.size();
1799        for (int i = 0; i < length; ++i) {
1800            ApplicationInfo info = list.get(i);
1801            int removeIndex = findAppByComponent(mApps, info);
1802            if (removeIndex > -1) {
1803                mApps.remove(removeIndex);
1804            }
1805        }
1806    }
1807    @Override
1808    public void removeApps(ArrayList<ApplicationInfo> list) {
1809        removeAppsWithoutInvalidate(list);
1810        Log.d(TAG, "6549598 removeApps mApps.size(): " + mApps.size() + " list.size(): " + list.size());
1811        updatePageCounts();
1812        invalidatePageData();
1813        Log.d(TAG, "6549598 removeApps mNumAppsPages: " + mNumAppsPages);
1814    }
1815    @Override
1816    public void updateApps(ArrayList<ApplicationInfo> list) {
1817        // We remove and re-add the updated applications list because it's properties may have
1818        // changed (ie. the title), and this will ensure that the items will be in their proper
1819        // place in the list.
1820        removeAppsWithoutInvalidate(list);
1821        addAppsWithoutInvalidate(list);
1822        Log.d(TAG, "6549598 updateApps mApps.size(): " + mApps.size() + " list.size(): " + list.size());
1823        updatePageCounts();
1824        invalidatePageData();
1825        Log.d(TAG, "6549598 updateApps mNumAppsPages: " + mNumAppsPages);
1826    }
1827
1828    @Override
1829    public void reset() {
1830        Log.d(TAG, "6549598 reset");
1831        // If we have reset, then we should not continue to restore the previous state
1832        mSaveInstanceStateItemIndex = -1;
1833
1834        AppsCustomizeTabHost tabHost = getTabHost();
1835        String tag = tabHost.getCurrentTabTag();
1836        if (tag != null) {
1837            if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1838                tabHost.setCurrentTabFromContent(ContentType.Applications);
1839            }
1840        }
1841
1842        if (mCurrentPage != 0) {
1843            invalidatePageData(0);
1844        }
1845    }
1846
1847    private AppsCustomizeTabHost getTabHost() {
1848        return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1849    }
1850
1851    @Override
1852    public void dumpState() {
1853        // TODO: Dump information related to current list of Applications, Widgets, etc.
1854        ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
1855        dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
1856    }
1857
1858    private void dumpAppWidgetProviderInfoList(String tag, String label,
1859            ArrayList<Object> list) {
1860        Log.d(tag, label + " size=" + list.size());
1861        for (Object i: list) {
1862            if (i instanceof AppWidgetProviderInfo) {
1863                AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1864                Log.d(tag, "   label=\"" + info.label + "\" previewImage=" + info.previewImage
1865                        + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1866                        + " initialLayout=" + info.initialLayout
1867                        + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1868            } else if (i instanceof ResolveInfo) {
1869                ResolveInfo info = (ResolveInfo) i;
1870                Log.d(tag, "   label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1871                        + info.icon);
1872            }
1873        }
1874    }
1875
1876    @Override
1877    public void surrender() {
1878        // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1879        // should stop this now.
1880
1881        // Stop all background tasks
1882        cancelAllTasks();
1883    }
1884
1885    @Override
1886    public void iconPressed(PagedViewIcon icon) {
1887        // Reset the previously pressed icon and store a reference to the pressed icon so that
1888        // we can reset it on return to Launcher (in Launcher.onResume())
1889        if (mPressedIcon != null) {
1890            mPressedIcon.resetDrawableState();
1891        }
1892        mPressedIcon = icon;
1893    }
1894
1895    public void resetDrawableState() {
1896        if (mPressedIcon != null) {
1897            mPressedIcon.resetDrawableState();
1898            mPressedIcon = null;
1899        }
1900    }
1901
1902    /*
1903     * We load an extra page on each side to prevent flashes from scrolling and loading of the
1904     * widget previews in the background with the AsyncTasks.
1905     */
1906    final static int sLookBehindPageCount = 2;
1907    final static int sLookAheadPageCount = 2;
1908    protected int getAssociatedLowerPageBound(int page) {
1909        final int count = getChildCount();
1910        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1911        int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
1912        return windowMinIndex;
1913    }
1914    protected int getAssociatedUpperPageBound(int page) {
1915        final int count = getChildCount();
1916        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1917        int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
1918                count - 1);
1919        return windowMaxIndex;
1920    }
1921
1922    @Override
1923    protected String getCurrentPageDescription() {
1924        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1925        int stringId = R.string.default_scroll_format;
1926        int count = 0;
1927
1928        if (page < mNumAppsPages) {
1929            stringId = R.string.apps_customize_apps_scroll_format;
1930            count = mNumAppsPages;
1931        } else {
1932            page -= mNumAppsPages;
1933            stringId = R.string.apps_customize_widgets_scroll_format;
1934            count = mNumWidgetPages;
1935        }
1936
1937        return String.format(getContext().getString(stringId), page + 1, count);
1938    }
1939}
1940