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