AppsCustomizePagedView.java revision 7ce9985d37e253a93617404d5991017e1ea81907
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 int mWidgetPreviewIconPaddedDimension;
280    private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
281    private PagedViewCellLayout mWidgetSpacingLayout;
282    private int mNumAppsPages;
283    private int mNumWidgetPages;
284
285    // Relating to the scroll and overscroll effects
286    Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f);
287    private static float CAMERA_DISTANCE = 6500;
288    private static float TRANSITION_SCALE_FACTOR = 0.74f;
289    private static float TRANSITION_PIVOT = 0.65f;
290    private static float TRANSITION_MAX_ROTATION = 22;
291    private static final boolean PERFORM_OVERSCROLL_ROTATION = true;
292    private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f);
293    private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4);
294
295    // Previews & outlines
296    ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
297    private static final int sPageSleepDelay = 200;
298
299    private Runnable mInflateWidgetRunnable = null;
300    private Runnable mBindWidgetRunnable = null;
301    static final int WIDGET_NO_CLEANUP_REQUIRED = -1;
302    static final int WIDGET_BOUND = 0;
303    static final int WIDGET_INFLATED = 1;
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        mWidgetPreviewIconPaddedDimension =
357            (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage)));
358        mFadeInAdjacentScreens = false;
359
360        // Unless otherwise specified this view is important for accessibility.
361        if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
362            setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
363        }
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    }
375
376    @Override
377    protected void onUnhandledTap(MotionEvent ev) {
378        if (LauncherApplication.isScreenLarge()) {
379            // Dismiss AppsCustomize if we tap
380            mLauncher.showWorkspace(true);
381        }
382    }
383
384    /** Returns the item index of the center item on this page so that we can restore to this
385     *  item index when we rotate. */
386    private int getMiddleComponentIndexOnCurrentPage() {
387        int i = -1;
388        if (getPageCount() > 0) {
389            int currentPage = getCurrentPage();
390            if (currentPage < mNumAppsPages) {
391                PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage);
392                PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout();
393                int numItemsPerPage = mCellCountX * mCellCountY;
394                int childCount = childrenLayout.getChildCount();
395                if (childCount > 0) {
396                    i = (currentPage * numItemsPerPage) + (childCount / 2);
397                }
398            } else {
399                int numApps = mApps.size();
400                PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage);
401                int numItemsPerPage = mWidgetCountX * mWidgetCountY;
402                int childCount = layout.getChildCount();
403                if (childCount > 0) {
404                    i = numApps +
405                        ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2);
406                }
407            }
408        }
409        return i;
410    }
411
412    /** Get the index of the item to restore to if we need to restore the current page. */
413    int getSaveInstanceStateIndex() {
414        if (mSaveInstanceStateItemIndex == -1) {
415            mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage();
416        }
417        return mSaveInstanceStateItemIndex;
418    }
419
420    /** Returns the page in the current orientation which is expected to contain the specified
421     *  item index. */
422    int getPageForComponent(int index) {
423        if (index < 0) return 0;
424
425        if (index < mApps.size()) {
426            int numItemsPerPage = mCellCountX * mCellCountY;
427            return (index / numItemsPerPage);
428        } else {
429            int numItemsPerPage = mWidgetCountX * mWidgetCountY;
430            return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage);
431        }
432    }
433
434    /**
435     * This differs from isDataReady as this is the test done if isDataReady is not set.
436     */
437    private boolean testDataReady() {
438        // We only do this test once, and we default to the Applications page, so we only really
439        // have to wait for there to be apps.
440        // TODO: What if one of them is validly empty
441        return !mApps.isEmpty() && !mWidgets.isEmpty();
442    }
443
444    /** Restores the page for an item at the specified index */
445    void restorePageForIndex(int index) {
446        if (index < 0) return;
447        mSaveInstanceStateItemIndex = index;
448    }
449
450    private void updatePageCounts() {
451        mNumWidgetPages = (int) Math.ceil(mWidgets.size() /
452                (float) (mWidgetCountX * mWidgetCountY));
453        mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
454    }
455
456    protected void onDataReady(int width, int height) {
457        // Note that we transpose the counts in portrait so that we get a similar layout
458        boolean isLandscape = getResources().getConfiguration().orientation ==
459            Configuration.ORIENTATION_LANDSCAPE;
460        int maxCellCountX = Integer.MAX_VALUE;
461        int maxCellCountY = Integer.MAX_VALUE;
462        if (LauncherApplication.isScreenLarge()) {
463            maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
464                LauncherModel.getCellCountY());
465            maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
466                LauncherModel.getCellCountX());
467        }
468        if (mMaxAppCellCountX > -1) {
469            maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX);
470        }
471        if (mMaxAppCellCountY > -1) {
472            maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY);
473        }
474
475        // Now that the data is ready, we can calculate the content width, the number of cells to
476        // use for each page
477        mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
478        mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
479                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
480        mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
481        mCellCountX = mWidgetSpacingLayout.getCellCountX();
482        mCellCountY = mWidgetSpacingLayout.getCellCountY();
483        updatePageCounts();
484
485        // Force a measure to update recalculate the gaps
486        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
487        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
488        mWidgetSpacingLayout.measure(widthSpec, heightSpec);
489        mContentWidth = mWidgetSpacingLayout.getContentWidth();
490
491        AppsCustomizeTabHost host = (AppsCustomizeTabHost) getTabHost();
492        final boolean hostIsTransitioning = host.isTransitioning();
493
494        // Restore the page
495        int page = getPageForComponent(mSaveInstanceStateItemIndex);
496        invalidatePageData(Math.max(0, page), hostIsTransitioning);
497
498        // Show All Apps cling if we are finished transitioning, otherwise, we will try again when
499        // the transition completes in AppsCustomizeTabHost (otherwise the wrong offsets will be
500        // returned while animating)
501        if (!hostIsTransitioning) {
502            post(new Runnable() {
503                @Override
504                public void run() {
505                    showAllAppsCling();
506                }
507            });
508        }
509    }
510
511    void showAllAppsCling() {
512        if (!mHasShownAllAppsCling && isDataReady() && testDataReady()) {
513            mHasShownAllAppsCling = true;
514            // Calculate the position for the cling punch through
515            int[] offset = new int[2];
516            int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY);
517            mLauncher.getDragLayer().getLocationInDragLayer(this, offset);
518            // PagedViews are centered horizontally but top aligned
519            pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 +
520                    offset[0];
521            pos[1] += offset[1];
522            mLauncher.showFirstRunAllAppsCling(pos);
523        }
524    }
525
526    @Override
527    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
528        int width = MeasureSpec.getSize(widthMeasureSpec);
529        int height = MeasureSpec.getSize(heightMeasureSpec);
530        if (!isDataReady()) {
531            if (testDataReady()) {
532                setDataIsReady();
533                setMeasuredDimension(width, height);
534                onDataReady(width, height);
535            }
536        }
537
538        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
539    }
540
541    public void onPackagesUpdated() {
542        // TODO: this isn't ideal, but we actually need to delay here. This call is triggered
543        // by a broadcast receiver, and in order for it to work correctly, we need to know that
544        // the AppWidgetService has already received and processed the same broadcast. Since there
545        // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally,
546        // we should have a more precise way of ensuring the AppWidgetService is up to date.
547        postDelayed(new Runnable() {
548           public void run() {
549               updatePackages();
550           }
551        }, 500);
552    }
553
554    public void updatePackages() {
555        // Get the list of widgets and shortcuts
556        boolean wasEmpty = mWidgets.isEmpty();
557        mWidgets.clear();
558        List<AppWidgetProviderInfo> widgets =
559            AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
560        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
561        List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
562        for (AppWidgetProviderInfo widget : widgets) {
563            if (widget.minWidth > 0 && widget.minHeight > 0) {
564                // Ensure that all widgets we show can be added on a workspace of this size
565                int[] spanXY = Launcher.getSpanForWidget(mLauncher, widget);
566                int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, widget);
567                int minSpanX = Math.min(spanXY[0], minSpanXY[0]);
568                int minSpanY = Math.min(spanXY[1], minSpanXY[1]);
569                if (minSpanX <= LauncherModel.getCellCountX() &&
570                        minSpanY <= LauncherModel.getCellCountY()) {
571                    mWidgets.add(widget);
572                }
573            } else {
574                Log.e(TAG, "Widget " + widget.provider + " has invalid dimensions (" +
575                        widget.minWidth + ", " + widget.minHeight + ")");
576            }
577        }
578        mWidgets.addAll(shortcuts);
579        Collections.sort(mWidgets,
580                new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
581        updatePageCounts();
582
583        if (wasEmpty) {
584            // The next layout pass will trigger data-ready if both widgets and apps are set, so request
585            // a layout to do this test and invalidate the page data when ready.
586            if (testDataReady()) requestLayout();
587        } else {
588            cancelAllTasks();
589            invalidatePageData();
590        }
591    }
592
593    @Override
594    public void onClick(View v) {
595        // When we have exited all apps or are in transition, disregard clicks
596        if (!mLauncher.isAllAppsCustomizeOpen() ||
597                mLauncher.getWorkspace().isSwitchingState()) return;
598
599        if (v instanceof PagedViewIcon) {
600            // Animate some feedback to the click
601            final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
602
603            // Lock the drawable state to pressed until we return to Launcher
604            if (mPressedIcon != null) {
605                mPressedIcon.lockDrawableState();
606            }
607
608            // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
609            // to be consistent.  So re-enable the flag here, and we will re-disable it as necessary
610            // when Launcher resumes and we are still in AllApps.
611            mLauncher.updateWallpaperVisibility(true);
612            mLauncher.startActivitySafely(v, appInfo.intent, appInfo);
613
614        } else if (v instanceof PagedViewWidget) {
615            // Let the user know that they have to long press to add a widget
616            Toast.makeText(getContext(), R.string.long_press_widget_to_add,
617                    Toast.LENGTH_SHORT).show();
618
619            // Create a little animation to show that the widget can move
620            float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
621            final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
622            AnimatorSet bounce = new AnimatorSet();
623            ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
624            tyuAnim.setDuration(125);
625            ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
626            tydAnim.setDuration(100);
627            bounce.play(tyuAnim).before(tydAnim);
628            bounce.setInterpolator(new AccelerateInterpolator());
629            bounce.start();
630        }
631    }
632
633    public boolean onKey(View v, int keyCode, KeyEvent event) {
634        return FocusHelper.handleAppsCustomizeKeyEvent(v,  keyCode, event);
635    }
636
637    /*
638     * PagedViewWithDraggableItems implementation
639     */
640    @Override
641    protected void determineDraggingStart(android.view.MotionEvent ev) {
642        // Disable dragging by pulling an app down for now.
643    }
644
645    private void beginDraggingApplication(View v) {
646        mLauncher.getWorkspace().onDragStartedWithItem(v);
647        mLauncher.getWorkspace().beginDragShared(v, this);
648    }
649
650    private void preloadWidget(final PendingAddWidgetInfo info) {
651        final AppWidgetProviderInfo pInfo = info.info;
652        if (pInfo.configure != null) {
653            return;
654        }
655
656        mBindWidgetRunnable = new Runnable() {
657            @Override
658            public void run() {
659                mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId();
660                if (AppWidgetManager.getInstance(mLauncher)
661                            .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) {
662                    mWidgetCleanupState = WIDGET_BOUND;
663                }
664            }
665        };
666        post(mBindWidgetRunnable);
667
668        mInflateWidgetRunnable = new Runnable() {
669            @Override
670            public void run() {
671                AppWidgetHostView hostView = mLauncher.
672                        getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo);
673                info.boundWidget = hostView;
674                mWidgetCleanupState = WIDGET_INFLATED;
675                hostView.setVisibility(INVISIBLE);
676                int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX,
677                        info.spanY, info, false);
678
679                // We want the first widget layout to be the correct size. This will be important
680                // for width size reporting to the AppWidgetManager.
681                DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0],
682                        unScaledSize[1]);
683                lp.x = lp.y = 0;
684                lp.customPosition = true;
685                hostView.setLayoutParams(lp);
686                mLauncher.getDragLayer().addView(hostView);
687            }
688        };
689        post(mInflateWidgetRunnable);
690    }
691
692    @Override
693    public void onShortPress(View v) {
694        // We are anticipating a long press, and we use this time to load bind and instantiate
695        // the widget. This will need to be cleaned up if it turns out no long press occurs.
696        if (mCreateWidgetInfo != null) {
697            // Just in case the cleanup process wasn't properly executed. This shouldn't happen.
698            cleanupWidgetPreloading(false);
699        }
700        mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag());
701        preloadWidget(mCreateWidgetInfo);
702    }
703
704    private void cleanupWidgetPreloading(boolean widgetWasAdded) {
705        if (!widgetWasAdded) {
706            // If the widget was not added, we may need to do further cleanup.
707            PendingAddWidgetInfo info = mCreateWidgetInfo;
708            mCreateWidgetInfo = null;
709            // First step was to allocate a widget id, revert that.
710            if ((mWidgetCleanupState == WIDGET_BOUND || mWidgetCleanupState == WIDGET_INFLATED) &&
711                    mWidgetLoadingId != -1) {
712                mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
713            }
714            if (mWidgetCleanupState == WIDGET_BOUND) {
715                // We never actually inflated the widget, so remove the callback to do so.
716                removeCallbacks(mInflateWidgetRunnable);
717            } else if (mWidgetCleanupState == WIDGET_INFLATED) {
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        mInTransition = false;
898        for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
899            onSyncWidgetPageItems(d);
900        }
901        mDeferredSyncWidgetPageItems.clear();
902        mForceDrawAllChildrenNextFrame = !toWorkspace;
903    }
904
905    @Override
906    public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
907            boolean success) {
908        // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
909        if (isFlingToDelete) return;
910
911        endDragging(target, false, success);
912
913        // Display an error message if the drag failed due to there not being enough space on the
914        // target layout we were dropping on.
915        if (!success) {
916            boolean showOutOfSpaceMessage = false;
917            if (target instanceof Workspace) {
918                int currentScreen = mLauncher.getCurrentWorkspaceScreen();
919                Workspace workspace = (Workspace) target;
920                CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
921                ItemInfo itemInfo = (ItemInfo) d.dragInfo;
922                if (layout != null) {
923                    layout.calculateSpans(itemInfo);
924                    showOutOfSpaceMessage =
925                            !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
926                }
927            }
928            if (showOutOfSpaceMessage) {
929                mLauncher.showOutOfSpaceMessage(false);
930            }
931
932            d.deferDragViewCleanupPostAnimation = false;
933        }
934        cleanupWidgetPreloading(success);
935        mDraggingWidget = false;
936    }
937
938    @Override
939    public void onFlingToDeleteCompleted() {
940        // We just dismiss the drag when we fling, so cleanup here
941        endDragging(null, true, true);
942        cleanupWidgetPreloading(false);
943        mDraggingWidget = false;
944    }
945
946    @Override
947    public boolean supportsFlingToDelete() {
948        return true;
949    }
950
951    @Override
952    protected void onDetachedFromWindow() {
953        super.onDetachedFromWindow();
954        cancelAllTasks();
955    }
956
957    public void clearAllWidgetPages() {
958        cancelAllTasks();
959        int count = getChildCount();
960        for (int i = 0; i < count; i++) {
961            View v = getPageAt(i);
962            if (v instanceof PagedViewGridLayout) {
963                ((PagedViewGridLayout) v).removeAllViewsOnPage();
964                mDirtyPageContent.set(i, true);
965            }
966        }
967    }
968
969    private void cancelAllTasks() {
970        // Clean up all the async tasks
971        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
972        while (iter.hasNext()) {
973            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
974            task.cancel(false);
975            iter.remove();
976            mDirtyPageContent.set(task.page, true);
977
978            // We've already preallocated the views for the data to load into, so clear them as well
979            View v = getPageAt(task.page);
980            if (v instanceof PagedViewGridLayout) {
981                ((PagedViewGridLayout) v).removeAllViewsOnPage();
982            }
983        }
984        mDeferredSyncWidgetPageItems.clear();
985    }
986
987    public void setContentType(ContentType type) {
988        if (type == ContentType.Widgets) {
989            invalidatePageData(mNumAppsPages, true);
990        } else if (type == ContentType.Applications) {
991            invalidatePageData(0, true);
992        }
993    }
994
995    protected void snapToPage(int whichPage, int delta, int duration) {
996        super.snapToPage(whichPage, delta, duration);
997        updateCurrentTab(whichPage);
998
999        // Update the thread priorities given the direction lookahead
1000        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1001        while (iter.hasNext()) {
1002            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1003            int pageIndex = task.page;
1004            if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
1005                (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
1006                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1007            } else {
1008                task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
1009            }
1010        }
1011    }
1012
1013    private void updateCurrentTab(int currentPage) {
1014        AppsCustomizeTabHost tabHost = getTabHost();
1015        if (tabHost != null) {
1016            String tag = tabHost.getCurrentTabTag();
1017            if (tag != null) {
1018                if (currentPage >= mNumAppsPages &&
1019                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
1020                    tabHost.setCurrentTabFromContent(ContentType.Widgets);
1021                } else if (currentPage < mNumAppsPages &&
1022                        !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1023                    tabHost.setCurrentTabFromContent(ContentType.Applications);
1024                }
1025            }
1026        }
1027    }
1028
1029    /*
1030     * Apps PagedView implementation
1031     */
1032    private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
1033        int childCount = layout.getChildCount();
1034        for (int i = 0; i < childCount; ++i) {
1035            layout.getChildAt(i).setVisibility(visibility);
1036        }
1037    }
1038    private void setupPage(PagedViewCellLayout layout) {
1039        layout.setCellCount(mCellCountX, mCellCountY);
1040        layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
1041        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1042                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1043
1044        // Note: We force a measure here to get around the fact that when we do layout calculations
1045        // immediately after syncing, we don't have a proper width.  That said, we already know the
1046        // expected page width, so we can actually optimize by hiding all the TextView-based
1047        // children that are expensive to measure, and let that happen naturally later.
1048        setVisibilityOnChildren(layout, View.GONE);
1049        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1050        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
1051        layout.setMinimumWidth(getPageContentWidth());
1052        layout.measure(widthSpec, heightSpec);
1053        setVisibilityOnChildren(layout, View.VISIBLE);
1054    }
1055
1056    public void syncAppsPageItems(int page, boolean immediate) {
1057        // ensure that we have the right number of items on the pages
1058        int numCells = mCellCountX * mCellCountY;
1059        int startIndex = page * numCells;
1060        int endIndex = Math.min(startIndex + numCells, mApps.size());
1061        PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
1062
1063        layout.removeAllViewsOnPage();
1064        ArrayList<Object> items = new ArrayList<Object>();
1065        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
1066        for (int i = startIndex; i < endIndex; ++i) {
1067            ApplicationInfo info = mApps.get(i);
1068            PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
1069                    R.layout.apps_customize_application, layout, false);
1070            icon.applyFromApplicationInfo(info, true, this);
1071            icon.setOnClickListener(this);
1072            icon.setOnLongClickListener(this);
1073            icon.setOnTouchListener(this);
1074            icon.setOnKeyListener(this);
1075
1076            int index = i - startIndex;
1077            int x = index % mCellCountX;
1078            int y = index / mCellCountX;
1079            layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
1080
1081            items.add(info);
1082            images.add(info.iconBitmap);
1083        }
1084
1085        layout.createHardwareLayers();
1086    }
1087
1088    /**
1089     * A helper to return the priority for loading of the specified widget page.
1090     */
1091    private int getWidgetPageLoadPriority(int page) {
1092        // If we are snapping to another page, use that index as the target page index
1093        int toPage = mCurrentPage;
1094        if (mNextPage > -1) {
1095            toPage = mNextPage;
1096        }
1097
1098        // We use the distance from the target page as an initial guess of priority, but if there
1099        // are no pages of higher priority than the page specified, then bump up the priority of
1100        // the specified page.
1101        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1102        int minPageDiff = Integer.MAX_VALUE;
1103        while (iter.hasNext()) {
1104            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1105            minPageDiff = Math.abs(task.page - toPage);
1106        }
1107
1108        int rawPageDiff = Math.abs(page - toPage);
1109        return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
1110    }
1111    /**
1112     * Return the appropriate thread priority for loading for a given page (we give the current
1113     * page much higher priority)
1114     */
1115    private int getThreadPriorityForPage(int page) {
1116        // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
1117        int pageDiff = getWidgetPageLoadPriority(page);
1118        if (pageDiff <= 0) {
1119            return Process.THREAD_PRIORITY_LESS_FAVORABLE;
1120        } else if (pageDiff <= 1) {
1121            return Process.THREAD_PRIORITY_LOWEST;
1122        } else {
1123            return Process.THREAD_PRIORITY_LOWEST;
1124        }
1125    }
1126    private int getSleepForPage(int page) {
1127        int pageDiff = getWidgetPageLoadPriority(page);
1128        return Math.max(0, pageDiff * sPageSleepDelay);
1129    }
1130    /**
1131     * Creates and executes a new AsyncTask to load a page of widget previews.
1132     */
1133    private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
1134            int cellWidth, int cellHeight, int cellCountX) {
1135
1136        // Prune all tasks that are no longer needed
1137        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1138        while (iter.hasNext()) {
1139            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1140            int taskPage = task.page;
1141            if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
1142                    taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
1143                task.cancel(false);
1144                iter.remove();
1145            } else {
1146                task.setThreadPriority(getThreadPriorityForPage(taskPage));
1147            }
1148        }
1149
1150        // We introduce a slight delay to order the loading of side pages so that we don't thrash
1151        final int sleepMs = getSleepForPage(page);
1152        AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
1153            new AsyncTaskCallback() {
1154                @Override
1155                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1156                    try {
1157                        try {
1158                            Thread.sleep(sleepMs);
1159                        } catch (Exception e) {}
1160                        loadWidgetPreviewsInBackground(task, data);
1161                    } finally {
1162                        if (task.isCancelled()) {
1163                            data.cleanup(true);
1164                        }
1165                    }
1166                }
1167            },
1168            new AsyncTaskCallback() {
1169                @Override
1170                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
1171                    mRunningTasks.remove(task);
1172                    if (task.isCancelled()) return;
1173                    // do cleanup inside onSyncWidgetPageItems
1174                    onSyncWidgetPageItems(data);
1175                }
1176            });
1177
1178        // Ensure that the task is appropriately prioritized and runs in parallel
1179        AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
1180                AsyncTaskPageData.Type.LoadWidgetPreviewData);
1181        t.setThreadPriority(getThreadPriorityForPage(page));
1182        t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
1183        mRunningTasks.add(t);
1184    }
1185
1186    /*
1187     * Widgets PagedView implementation
1188     */
1189    private void setupPage(PagedViewGridLayout layout) {
1190        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1191                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1192
1193        // Note: We force a measure here to get around the fact that when we do layout calculations
1194        // immediately after syncing, we don't have a proper width.
1195        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1196        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
1197        layout.setMinimumWidth(getPageContentWidth());
1198        layout.measure(widthSpec, heightSpec);
1199    }
1200
1201    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
1202        renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
1203    }
1204
1205    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
1206            float scale) {
1207        if (bitmap != null) {
1208            Canvas c = new Canvas(bitmap);
1209            c.scale(scale, scale);
1210            Rect oldBounds = d.copyBounds();
1211            d.setBounds(x, y, x + w, y + h);
1212            d.draw(c);
1213            d.setBounds(oldBounds); // Restore the bounds
1214            c.setBitmap(null);
1215        }
1216    }
1217
1218    private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
1219        Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
1220        final Canvas c = mCachedShortcutPreviewCanvas.get();
1221        if (tempBitmap == null ||
1222                tempBitmap.getWidth() != maxWidth ||
1223                tempBitmap.getHeight() != maxHeight) {
1224            tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1225            mCachedShortcutPreviewBitmap.set(tempBitmap);
1226        } else {
1227            c.setBitmap(tempBitmap);
1228            c.drawColor(0, PorterDuff.Mode.CLEAR);
1229            c.setBitmap(null);
1230        }
1231        // Render the icon
1232        Drawable icon = mIconCache.getFullResIcon(info);
1233
1234        int paddingTop =
1235                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
1236        int paddingLeft =
1237                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
1238        int paddingRight =
1239                getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
1240
1241        int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
1242        float scaleSize = scaledIconWidth / (float) mAppIconSize;
1243
1244        renderDrawableToBitmap(
1245                icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
1246
1247        Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1248        c.setBitmap(preview);
1249        Paint p = mCachedShortcutPreviewPaint.get();
1250        if (p == null) {
1251            p = new Paint();
1252            ColorMatrix colorMatrix = new ColorMatrix();
1253            colorMatrix.setSaturation(0);
1254            p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
1255            p.setAlpha((int) (255 * 0.06f));
1256            //float density = 1f;
1257            //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
1258            mCachedShortcutPreviewPaint.set(p);
1259        }
1260        c.drawBitmap(tempBitmap, 0, 0, p);
1261        c.setBitmap(null);
1262
1263        renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
1264
1265        return preview;
1266    }
1267
1268    private Bitmap getWidgetPreview(ComponentName provider, int previewImage,
1269            int iconId, int cellHSpan, int cellVSpan, int maxWidth,
1270            int maxHeight) {
1271        // Load the preview image if possible
1272        String packageName = provider.getPackageName();
1273        if (maxWidth < 0) maxWidth = Integer.MAX_VALUE;
1274        if (maxHeight < 0) maxHeight = Integer.MAX_VALUE;
1275
1276        Drawable drawable = null;
1277        if (previewImage != 0) {
1278            drawable = mPackageManager.getDrawable(packageName, previewImage, null);
1279            if (drawable == null) {
1280                Log.w(TAG, "Can't load widget preview drawable 0x" +
1281                        Integer.toHexString(previewImage) + " for provider: " + provider);
1282            }
1283        }
1284
1285        int bitmapWidth;
1286        int bitmapHeight;
1287        Bitmap defaultPreview = null;
1288        boolean widgetPreviewExists = (drawable != null);
1289        if (widgetPreviewExists) {
1290            bitmapWidth = drawable.getIntrinsicWidth();
1291            bitmapHeight = drawable.getIntrinsicHeight();
1292        } else {
1293            // Generate a preview image if we couldn't load one
1294            if (cellHSpan < 1) cellHSpan = 1;
1295            if (cellVSpan < 1) cellVSpan = 1;
1296
1297            BitmapDrawable previewDrawable = (BitmapDrawable) getResources()
1298                    .getDrawable(R.drawable.widget_preview_tile);
1299            final int previewDrawableWidth = previewDrawable
1300                    .getIntrinsicWidth();
1301            final int previewDrawableHeight = previewDrawable
1302                    .getIntrinsicHeight();
1303            bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
1304            bitmapHeight = previewDrawableHeight * cellVSpan;
1305
1306            defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1307                    Config.ARGB_8888);
1308            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1309            c.setBitmap(defaultPreview);
1310            previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
1311            previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
1312                    Shader.TileMode.REPEAT);
1313            previewDrawable.draw(c);
1314            c.setBitmap(null);
1315
1316            // Draw the icon in the top left corner
1317            int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1318            int smallestSide = Math.min(bitmapWidth, bitmapHeight);
1319            float iconScale = Math.min((float) smallestSide
1320                    / (mAppIconSize + 2 * minOffset), 1f);
1321
1322            try {
1323                Drawable icon = null;
1324                int hoffset =
1325                        (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
1326                int yoffset =
1327                        (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
1328                if (iconId > 0)
1329                    icon = mIconCache.getFullResIcon(packageName, iconId);
1330                Resources resources = mLauncher.getResources();
1331                if (icon != null) {
1332                    renderDrawableToBitmap(icon, defaultPreview, hoffset,
1333                            yoffset, (int) (mAppIconSize * iconScale),
1334                            (int) (mAppIconSize * iconScale));
1335                }
1336            } catch (Resources.NotFoundException e) {
1337            }
1338        }
1339
1340        // Scale to fit width only - let the widget preview be clipped in the
1341        // vertical dimension
1342        float scale = 1f;
1343        if (bitmapWidth > maxWidth) {
1344            scale = maxWidth / (float) bitmapWidth;
1345        }
1346        if (scale != 1f) {
1347            bitmapWidth = (int) (scale * bitmapWidth);
1348            bitmapHeight = (int) (scale * bitmapHeight);
1349        }
1350
1351        Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1352                Config.ARGB_8888);
1353
1354        // Draw the scaled preview into the final bitmap
1355        if (widgetPreviewExists) {
1356            renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth,
1357                    bitmapHeight);
1358        } else {
1359            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1360            final Rect src = mCachedAppWidgetPreviewSrcRect.get();
1361            final Rect dest = mCachedAppWidgetPreviewDestRect.get();
1362            c.setBitmap(preview);
1363            src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
1364            dest.set(0, 0, preview.getWidth(), preview.getHeight());
1365
1366            Paint p = mCachedAppWidgetPreviewPaint.get();
1367            if (p == null) {
1368                p = new Paint();
1369                p.setFilterBitmap(true);
1370                mCachedAppWidgetPreviewPaint.set(p);
1371            }
1372            c.drawBitmap(defaultPreview, src, dest, p);
1373            c.setBitmap(null);
1374        }
1375        return preview;
1376    }
1377
1378    public void syncWidgetPageItems(final int page, final boolean immediate) {
1379        int numItemsPerPage = mWidgetCountX * mWidgetCountY;
1380
1381        // Calculate the dimensions of each cell we are giving to each widget
1382        final ArrayList<Object> items = new ArrayList<Object>();
1383        int contentWidth = mWidgetSpacingLayout.getContentWidth();
1384        final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
1385                - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
1386        int contentHeight = mWidgetSpacingLayout.getContentHeight();
1387        final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
1388                - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
1389
1390        // Prepare the set of widgets to load previews for in the background
1391        int offset = (page - mNumAppsPages) * numItemsPerPage;
1392        for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1393            items.add(mWidgets.get(i));
1394        }
1395
1396        // Prepopulate the pages with the other widget info, and fill in the previews later
1397        final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1398        layout.setColumnCount(layout.getCellCountX());
1399        for (int i = 0; i < items.size(); ++i) {
1400            Object rawInfo = items.get(i);
1401            PendingAddItemInfo createItemInfo = null;
1402            PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1403                    R.layout.apps_customize_widget, layout, false);
1404            if (rawInfo instanceof AppWidgetProviderInfo) {
1405                // Fill in the widget information
1406                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1407                createItemInfo = new PendingAddWidgetInfo(info, null, null);
1408
1409                // Determine the widget spans and min resize spans.
1410                int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
1411                createItemInfo.spanX = spanXY[0];
1412                createItemInfo.spanY = spanXY[1];
1413                int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
1414                createItemInfo.minSpanX = minSpanXY[0];
1415                createItemInfo.minSpanY = minSpanXY[1];
1416
1417                widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
1418                widget.setTag(createItemInfo);
1419                widget.setShortPressListener(this);
1420            } else if (rawInfo instanceof ResolveInfo) {
1421                // Fill in the shortcuts information
1422                ResolveInfo info = (ResolveInfo) rawInfo;
1423                createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
1424                createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1425                createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1426                        info.activityInfo.name);
1427                widget.applyFromResolveInfo(mPackageManager, info);
1428                widget.setTag(createItemInfo);
1429            }
1430            widget.setOnClickListener(this);
1431            widget.setOnLongClickListener(this);
1432            widget.setOnTouchListener(this);
1433            widget.setOnKeyListener(this);
1434
1435            // Layout each widget
1436            int ix = i % mWidgetCountX;
1437            int iy = i / mWidgetCountX;
1438            GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1439                    GridLayout.spec(iy, GridLayout.LEFT),
1440                    GridLayout.spec(ix, GridLayout.TOP));
1441            lp.width = cellWidth;
1442            lp.height = cellHeight;
1443            lp.setGravity(Gravity.TOP | Gravity.LEFT);
1444            if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1445            if (iy > 0) lp.topMargin = mWidgetHeightGap;
1446            layout.addView(widget, lp);
1447        }
1448
1449        // wait until a call on onLayout to start loading, because
1450        // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
1451        // TODO: can we do a measure/layout immediately?
1452        layout.setOnLayoutListener(new Runnable() {
1453            public void run() {
1454                // Load the widget previews
1455                int maxPreviewWidth = cellWidth;
1456                int maxPreviewHeight = cellHeight;
1457                if (layout.getChildCount() > 0) {
1458                    PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
1459                    int[] maxSize = w.getPreviewSize();
1460                    maxPreviewWidth = maxSize[0];
1461                    maxPreviewHeight = maxSize[1];
1462                }
1463                if (immediate) {
1464                    AsyncTaskPageData data = new AsyncTaskPageData(page, items,
1465                            maxPreviewWidth, maxPreviewHeight, null, null);
1466                    loadWidgetPreviewsInBackground(null, data);
1467                    onSyncWidgetPageItems(data);
1468                } else {
1469                    prepareLoadWidgetPreviewsTask(page, items,
1470                            maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
1471                }
1472            }
1473        });
1474    }
1475    private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1476            AsyncTaskPageData data) {
1477        // loadWidgetPreviewsInBackground can be called without a task to load a set of widget
1478        // previews synchronously
1479        if (task != null) {
1480            // Ensure that this task starts running at the correct priority
1481            task.syncThreadPriority();
1482        }
1483
1484        // Load each of the widget/shortcut previews
1485        ArrayList<Object> items = data.items;
1486        ArrayList<Bitmap> images = data.generatedImages;
1487        int count = items.size();
1488        for (int i = 0; i < count; ++i) {
1489            if (task != null) {
1490                // Ensure we haven't been cancelled yet
1491                if (task.isCancelled()) break;
1492                // Before work on each item, ensure that this task is running at the correct
1493                // priority
1494                task.syncThreadPriority();
1495            }
1496
1497            Object rawInfo = items.get(i);
1498            if (rawInfo instanceof AppWidgetProviderInfo) {
1499                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1500                int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
1501
1502                int maxWidth = Math.min(data.maxImageWidth,
1503                        mWidgetSpacingLayout.estimateCellWidth(cellSpans[0]));
1504                int maxHeight = Math.min(data.maxImageHeight,
1505                        mWidgetSpacingLayout.estimateCellHeight(cellSpans[1]));
1506                Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon,
1507                        cellSpans[0], cellSpans[1], maxWidth, maxHeight);
1508                images.add(b);
1509            } else if (rawInfo instanceof ResolveInfo) {
1510                // Fill in the shortcuts information
1511                ResolveInfo info = (ResolveInfo) rawInfo;
1512                images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight));
1513            }
1514        }
1515    }
1516
1517    private void onSyncWidgetPageItems(AsyncTaskPageData data) {
1518        if (mInTransition) {
1519            mDeferredSyncWidgetPageItems.add(data);
1520            return;
1521        }
1522        try {
1523            int page = data.page;
1524            PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
1525
1526            ArrayList<Object> items = data.items;
1527            int count = items.size();
1528            for (int i = 0; i < count; ++i) {
1529                PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1530                if (widget != null) {
1531                    Bitmap preview = data.generatedImages.get(i);
1532                    widget.applyPreview(new FastBitmapDrawable(preview), i);
1533                }
1534            }
1535
1536            layout.createHardwareLayer();
1537            invalidate();
1538
1539            // Update all thread priorities
1540            Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1541            while (iter.hasNext()) {
1542                AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1543                int pageIndex = task.page;
1544                task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1545            }
1546        } finally {
1547            data.cleanup(false);
1548        }
1549    }
1550
1551    @Override
1552    public void syncPages() {
1553        removeAllViews();
1554        cancelAllTasks();
1555
1556        Context context = getContext();
1557        for (int j = 0; j < mNumWidgetPages; ++j) {
1558            PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1559                    mWidgetCountY);
1560            setupPage(layout);
1561            addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
1562                    LayoutParams.MATCH_PARENT));
1563        }
1564
1565        for (int i = 0; i < mNumAppsPages; ++i) {
1566            PagedViewCellLayout layout = new PagedViewCellLayout(context);
1567            setupPage(layout);
1568            addView(layout);
1569        }
1570    }
1571
1572    @Override
1573    public void syncPageItems(int page, boolean immediate) {
1574        if (page < mNumAppsPages) {
1575            syncAppsPageItems(page, immediate);
1576        } else {
1577            syncWidgetPageItems(page, immediate);
1578        }
1579    }
1580
1581    // We want our pages to be z-ordered such that the further a page is to the left, the higher
1582    // it is in the z-order. This is important to insure touch events are handled correctly.
1583    View getPageAt(int index) {
1584        return getChildAt(indexToPage(index));
1585    }
1586
1587    @Override
1588    protected int indexToPage(int index) {
1589        return getChildCount() - index - 1;
1590    }
1591
1592    // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1593    @Override
1594    protected void screenScrolled(int screenCenter) {
1595        super.screenScrolled(screenCenter);
1596
1597        for (int i = 0; i < getChildCount(); i++) {
1598            View v = getPageAt(i);
1599            if (v != null) {
1600                float scrollProgress = getScrollProgress(screenCenter, v, i);
1601
1602                float interpolatedProgress =
1603                        mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1604                float scale = (1 - interpolatedProgress) +
1605                        interpolatedProgress * TRANSITION_SCALE_FACTOR;
1606                float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
1607
1608                float alpha;
1609
1610                if (scrollProgress < 0) {
1611                    alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
1612                        1 - Math.abs(scrollProgress)) : 1.0f;
1613                } else {
1614                    // On large screens we need to fade the page as it nears its leftmost position
1615                    alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1616                }
1617
1618                v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1619                int pageWidth = v.getMeasuredWidth();
1620                int pageHeight = v.getMeasuredHeight();
1621
1622                if (PERFORM_OVERSCROLL_ROTATION) {
1623                    if (i == 0 && scrollProgress < 0) {
1624                        // Overscroll to the left
1625                        v.setPivotX(TRANSITION_PIVOT * pageWidth);
1626                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1627                        scale = 1.0f;
1628                        alpha = 1.0f;
1629                        // On the first page, we don't want the page to have any lateral motion
1630                        translationX = 0;
1631                    } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1632                        // Overscroll to the right
1633                        v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1634                        v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1635                        scale = 1.0f;
1636                        alpha = 1.0f;
1637                        // On the last page, we don't want the page to have any lateral motion.
1638                        translationX = 0;
1639                    } else {
1640                        v.setPivotY(pageHeight / 2.0f);
1641                        v.setPivotX(pageWidth / 2.0f);
1642                        v.setRotationY(0f);
1643                    }
1644                }
1645
1646                v.setTranslationX(translationX);
1647                v.setScaleX(scale);
1648                v.setScaleY(scale);
1649                v.setAlpha(alpha);
1650
1651                // If the view has 0 alpha, we set it to be invisible so as to prevent
1652                // it from accepting touches
1653                if (alpha == 0) {
1654                    v.setVisibility(INVISIBLE);
1655                } else if (v.getVisibility() != VISIBLE) {
1656                    v.setVisibility(VISIBLE);
1657                }
1658            }
1659        }
1660    }
1661
1662    protected void overScroll(float amount) {
1663        acceleratedOverScroll(amount);
1664    }
1665
1666    /**
1667     * Used by the parent to get the content width to set the tab bar to
1668     * @return
1669     */
1670    public int getPageContentWidth() {
1671        return mContentWidth;
1672    }
1673
1674    @Override
1675    protected void onPageEndMoving() {
1676        super.onPageEndMoving();
1677        mForceDrawAllChildrenNextFrame = true;
1678        // We reset the save index when we change pages so that it will be recalculated on next
1679        // rotation
1680        mSaveInstanceStateItemIndex = -1;
1681    }
1682
1683    /*
1684     * AllAppsView implementation
1685     */
1686    @Override
1687    public void setup(Launcher launcher, DragController dragController) {
1688        mLauncher = launcher;
1689        mDragController = dragController;
1690    }
1691    @Override
1692    public void zoom(float zoom, boolean animate) {
1693        // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1694    }
1695    @Override
1696    public boolean isVisible() {
1697        return (getVisibility() == VISIBLE);
1698    }
1699    @Override
1700    public boolean isAnimating() {
1701        return false;
1702    }
1703    @Override
1704    public void setApps(ArrayList<ApplicationInfo> list) {
1705        mApps = list;
1706        Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
1707        updatePageCounts();
1708
1709        // The next layout pass will trigger data-ready if both widgets and apps are set, so
1710        // request a layout to do this test and invalidate the page data when ready.
1711        if (testDataReady()) requestLayout();
1712    }
1713    private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1714        // We add it in place, in alphabetical order
1715        int count = list.size();
1716        for (int i = 0; i < count; ++i) {
1717            ApplicationInfo info = list.get(i);
1718            int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1719            if (index < 0) {
1720                mApps.add(-(index + 1), info);
1721            }
1722        }
1723    }
1724    @Override
1725    public void addApps(ArrayList<ApplicationInfo> list) {
1726        addAppsWithoutInvalidate(list);
1727        updatePageCounts();
1728        invalidatePageData();
1729    }
1730    private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1731        ComponentName removeComponent = item.intent.getComponent();
1732        int length = list.size();
1733        for (int i = 0; i < length; ++i) {
1734            ApplicationInfo info = list.get(i);
1735            if (info.intent.getComponent().equals(removeComponent)) {
1736                return i;
1737            }
1738        }
1739        return -1;
1740    }
1741    private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1742        // loop through all the apps and remove apps that have the same component
1743        int length = list.size();
1744        for (int i = 0; i < length; ++i) {
1745            ApplicationInfo info = list.get(i);
1746            int removeIndex = findAppByComponent(mApps, info);
1747            if (removeIndex > -1) {
1748                mApps.remove(removeIndex);
1749            }
1750        }
1751    }
1752    @Override
1753    public void removeApps(ArrayList<ApplicationInfo> list) {
1754        removeAppsWithoutInvalidate(list);
1755        updatePageCounts();
1756        invalidatePageData();
1757    }
1758    @Override
1759    public void updateApps(ArrayList<ApplicationInfo> list) {
1760        // We remove and re-add the updated applications list because it's properties may have
1761        // changed (ie. the title), and this will ensure that the items will be in their proper
1762        // place in the list.
1763        removeAppsWithoutInvalidate(list);
1764        addAppsWithoutInvalidate(list);
1765        updatePageCounts();
1766
1767        invalidatePageData();
1768    }
1769
1770    @Override
1771    public void reset() {
1772        // If we have reset, then we should not continue to restore the previous state
1773        mSaveInstanceStateItemIndex = -1;
1774
1775        AppsCustomizeTabHost tabHost = getTabHost();
1776        String tag = tabHost.getCurrentTabTag();
1777        if (tag != null) {
1778            if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1779                tabHost.setCurrentTabFromContent(ContentType.Applications);
1780            }
1781        }
1782
1783        if (mCurrentPage != 0) {
1784            invalidatePageData(0);
1785        }
1786    }
1787
1788    private AppsCustomizeTabHost getTabHost() {
1789        return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1790    }
1791
1792    @Override
1793    public void dumpState() {
1794        // TODO: Dump information related to current list of Applications, Widgets, etc.
1795        ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
1796        dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
1797    }
1798
1799    private void dumpAppWidgetProviderInfoList(String tag, String label,
1800            ArrayList<Object> list) {
1801        Log.d(tag, label + " size=" + list.size());
1802        for (Object i: list) {
1803            if (i instanceof AppWidgetProviderInfo) {
1804                AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1805                Log.d(tag, "   label=\"" + info.label + "\" previewImage=" + info.previewImage
1806                        + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1807                        + " initialLayout=" + info.initialLayout
1808                        + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1809            } else if (i instanceof ResolveInfo) {
1810                ResolveInfo info = (ResolveInfo) i;
1811                Log.d(tag, "   label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1812                        + info.icon);
1813            }
1814        }
1815    }
1816
1817    @Override
1818    public void surrender() {
1819        // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1820        // should stop this now.
1821
1822        // Stop all background tasks
1823        cancelAllTasks();
1824    }
1825
1826    @Override
1827    public void iconPressed(PagedViewIcon icon) {
1828        // Reset the previously pressed icon and store a reference to the pressed icon so that
1829        // we can reset it on return to Launcher (in Launcher.onResume())
1830        if (mPressedIcon != null) {
1831            mPressedIcon.resetDrawableState();
1832        }
1833        mPressedIcon = icon;
1834    }
1835
1836    public void resetDrawableState() {
1837        if (mPressedIcon != null) {
1838            mPressedIcon.resetDrawableState();
1839            mPressedIcon = null;
1840        }
1841    }
1842
1843    /*
1844     * We load an extra page on each side to prevent flashes from scrolling and loading of the
1845     * widget previews in the background with the AsyncTasks.
1846     */
1847    final static int sLookBehindPageCount = 2;
1848    final static int sLookAheadPageCount = 2;
1849    protected int getAssociatedLowerPageBound(int page) {
1850        final int count = getChildCount();
1851        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1852        int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
1853        return windowMinIndex;
1854    }
1855    protected int getAssociatedUpperPageBound(int page) {
1856        final int count = getChildCount();
1857        int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1858        int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
1859                count - 1);
1860        return windowMaxIndex;
1861    }
1862
1863    @Override
1864    protected String getCurrentPageDescription() {
1865        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1866        int stringId = R.string.default_scroll_format;
1867        int count = 0;
1868
1869        if (page < mNumAppsPages) {
1870            stringId = R.string.apps_customize_apps_scroll_format;
1871            count = mNumAppsPages;
1872        } else {
1873            page -= mNumAppsPages;
1874            stringId = R.string.apps_customize_widgets_scroll_format;
1875            count = mNumWidgetPages;
1876        }
1877
1878        return String.format(getContext().getString(stringId), page + 1, count);
1879    }
1880}
1881