AppsCustomizePagedView.java revision b60fd0eafbb4e6e61b429c403f024dc903bc483a
1ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung/*
2ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * Copyright (C) 2011 The Android Open Source Project
3ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung *
4ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * Licensed under the Apache License, Version 2.0 (the "License");
5ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * you may not use this file except in compliance with the License.
6ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * You may obtain a copy of the License at
7ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung *
8ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung *      http://www.apache.org/licenses/LICENSE-2.0
9ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung *
10ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * Unless required by applicable law or agreed to in writing, software
11ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * distributed under the License is distributed on an "AS IS" BASIS,
12ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * See the License for the specific language governing permissions and
14ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * limitations under the License.
15ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung */
16ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung
17ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungpackage com.android.launcher2;
18ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung
19ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.animation.AnimatorSet;
20ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.animation.ObjectAnimator;
21ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.animation.ValueAnimator;
22ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.appwidget.AppWidgetManager;
235183285847816cee9d0db6a8a7ab1a5929163e4eSunny Goyalimport android.appwidget.AppWidgetProviderInfo;
245183285847816cee9d0db6a8a7ab1a5929163e4eSunny Goyalimport android.content.ComponentName;
25ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.Context;
26ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.Intent;
27ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.pm.ActivityInfo;
28ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.pm.PackageManager;
29ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.pm.ResolveInfo;
30ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.res.Configuration;
31ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.res.Resources;
32ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.content.res.TypedArray;
33ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.graphics.Bitmap;
34ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.graphics.Bitmap.Config;
35ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.graphics.Canvas;
36ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.graphics.PorterDuff;
37ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.graphics.Rect;
38ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.graphics.drawable.Drawable;
39ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.os.AsyncTask;
40ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.os.Process;
41ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.util.AttributeSet;
42ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.util.Log;
43ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.view.Gravity;
44ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.view.LayoutInflater;
45ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.view.MotionEvent;
46ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.view.View;
47ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.view.ViewGroup;
48ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.view.animation.AccelerateInterpolator;
49ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.widget.GridLayout;
50ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.widget.ImageView;
51ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport android.widget.Toast;
52ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung
53ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport com.android.launcher.R;
54ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport com.android.launcher2.DropTarget.DragObject;
55ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung
56ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport java.util.ArrayList;
57ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport java.util.Collections;
58ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport java.util.Iterator;
59ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungimport java.util.List;
60ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung
61ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung/**
62ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * A simple callback interface which also provides the results of the task.
63ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung */
64ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chunginterface AsyncTaskCallback {
65ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
66ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung}
67ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung
68ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung/**
69ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung * The data needed to perform either of the custom AsyncTasks.
70ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung */
71ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chungclass AsyncTaskPageData {
72ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    enum Type {
73ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        LoadWidgetPreviewData,
74ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        LoadHolographicIconsData
75ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    }
76ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung
77ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
78ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung            AsyncTaskCallback postR) {
79ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        page = p;
80ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        items = l;
81ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        sourceImages = si;
82ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        generatedImages = new ArrayList<Bitmap>();
83ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        cellWidth = cellHeight = -1;
84ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        doInBackgroundCallback = bgR;
85ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        postExecuteCallback = postR;
86ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    }
87ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR,
88ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung            AsyncTaskCallback postR) {
89ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        page = p;
90ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        items = l;
91ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        generatedImages = new ArrayList<Bitmap>();
925183285847816cee9d0db6a8a7ab1a5929163e4eSunny Goyal        cellWidth = cw;
93ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        cellHeight = ch;
94ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        cellCountX = ccx;
95ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        doInBackgroundCallback = bgR;
96ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung        postExecuteCallback = postR;
97ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    }
98ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    int page;
99ef7f874a889b609bd34e692b9c9a1f8cefd1ea95Winson Chung    ArrayList<Object> items;
100    ArrayList<Bitmap> sourceImages;
101    ArrayList<Bitmap> generatedImages;
102    int cellWidth;
103    int cellHeight;
104    int cellCountX;
105    AsyncTaskCallback doInBackgroundCallback;
106    AsyncTaskCallback postExecuteCallback;
107}
108
109/**
110 * A generic template for an async task used in AppsCustomize.
111 */
112class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
113    AppsCustomizeAsyncTask(int p, AppsCustomizePagedView.ContentType t, AsyncTaskPageData.Type ty) {
114        page = p;
115        pageContentType = t;
116        threadPriority = Process.THREAD_PRIORITY_DEFAULT;
117        dataType = ty;
118    }
119    @Override
120    protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
121        if (params.length != 1) return null;
122        // Load each of the widget previews in the background
123        params[0].doInBackgroundCallback.run(this, params[0]);
124        return params[0];
125    }
126    @Override
127    protected void onPostExecute(AsyncTaskPageData result) {
128        // All the widget previews are loaded, so we can just callback to inflate the page
129        result.postExecuteCallback.run(this, result);
130    }
131
132    void setThreadPriority(int p) {
133        threadPriority = p;
134    }
135    void syncThreadPriority() {
136        Process.setThreadPriority(threadPriority);
137    }
138
139    // The page that this async task is associated with
140    AsyncTaskPageData.Type dataType;
141    int page;
142    AppsCustomizePagedView.ContentType pageContentType;
143    int threadPriority;
144}
145
146/**
147 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
148 */
149public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
150        AllAppsView, View.OnClickListener, DragSource {
151    static final String LOG_TAG = "AppsCustomizePagedView";
152
153    /**
154     * The different content types that this paged view can show.
155     */
156    public enum ContentType {
157        Applications,
158        Widgets
159    }
160
161    // Refs
162    private Launcher mLauncher;
163    private DragController mDragController;
164    private final LayoutInflater mLayoutInflater;
165    private final PackageManager mPackageManager;
166
167    // Save and Restore
168    private int mSaveInstanceStateItemIndex = -1;
169    private int mRestorePage = -1;
170
171    // Content
172    private ContentType mContentType;
173    private ArrayList<ApplicationInfo> mApps;
174    private ArrayList<Object> mWidgets;
175
176    // Caching
177    private Canvas mCanvas;
178    private Drawable mDefaultWidgetBackground;
179    private IconCache mIconCache;
180    private int mDragViewMultiplyColor;
181
182    // Dimens
183    private int mContentWidth;
184    private int mAppIconSize;
185    private int mMaxWidgetSpan, mMinWidgetSpan;
186    private int mWidgetCountX, mWidgetCountY;
187    private int mWidgetWidthGap, mWidgetHeightGap;
188    private final int mWidgetPreviewIconPaddedDimension;
189    private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
190    private PagedViewCellLayout mWidgetSpacingLayout;
191
192    // Previews & outlines
193    ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
194    private HolographicOutlineHelper mHolographicOutlineHelper;
195    private static final int sPageSleepDelay = 200;
196
197    public AppsCustomizePagedView(Context context, AttributeSet attrs) {
198        super(context, attrs);
199        mLayoutInflater = LayoutInflater.from(context);
200        mPackageManager = context.getPackageManager();
201        mContentType = ContentType.Applications;
202        mApps = new ArrayList<ApplicationInfo>();
203        mWidgets = new ArrayList<Object>();
204        mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
205        mHolographicOutlineHelper = new HolographicOutlineHelper();
206        mCanvas = new Canvas();
207        mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
208
209        // Save the default widget preview background
210        Resources resources = context.getResources();
211        mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo);
212        mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
213        mDragViewMultiplyColor = resources.getColor(R.color.drag_view_multiply_color);
214
215        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0);
216        // TODO-APPS_CUSTOMIZE: remove these unnecessary attrs after
217        mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6);
218        mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4);
219        a.recycle();
220        a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
221        mWidgetWidthGap =
222            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
223        mWidgetHeightGap =
224            a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
225        mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
226        mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
227        a.recycle();
228        mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
229
230        // The max widget span is the length N, such that NxN is the largest bounds that the widget
231        // preview can be before applying the widget scaling
232        mMinWidgetSpan = 1;
233        mMaxWidgetSpan = 3;
234
235        // The padding on the non-matched dimension for the default widget preview icons
236        // (top + bottom)
237        mWidgetPreviewIconPaddedDimension =
238            (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage)));
239        mFadeInAdjacentScreens = LauncherApplication.isScreenLarge();
240    }
241
242    @Override
243    protected void init() {
244        super.init();
245        mCenterPagesVertically = false;
246
247        Context context = getContext();
248        Resources r = context.getResources();
249        setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
250    }
251
252    @Override
253    protected void onUnhandledTap(MotionEvent ev) {
254        if (LauncherApplication.isScreenLarge()) {
255            // Dismiss AppsCustomize if we tap
256            mLauncher.showWorkspace(true);
257        }
258    }
259
260    /** Returns the item index of the center item on this page so that we can restore to this
261     *  item index when we rotate. */
262    private int getMiddleComponentIndexOnCurrentPage() {
263        int i = -1;
264        if (getPageCount() > 0) {
265            int currentPage = getCurrentPage();
266            switch (mContentType) {
267            case Applications: {
268                PagedViewCellLayout layout = (PagedViewCellLayout) getChildAt(currentPage);
269                PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout();
270                int numItemsPerPage = mCellCountX * mCellCountY;
271                int childCount = childrenLayout.getChildCount();
272                if (childCount > 0) {
273                    i = (currentPage * numItemsPerPage) + (childCount / 2);
274                }}
275                break;
276            case Widgets: {
277                PagedViewGridLayout layout = (PagedViewGridLayout) getChildAt(currentPage);
278                int numItemsPerPage = mWidgetCountX * mWidgetCountY;
279                int childCount = layout.getChildCount();
280                if (childCount > 0) {
281                    i = (currentPage * numItemsPerPage) + (childCount / 2);
282                }}
283                break;
284            }
285        }
286        return i;
287    }
288
289    /** Get the index of the item to restore to if we need to restore the current page. */
290    int getSaveInstanceStateIndex() {
291        if (mSaveInstanceStateItemIndex == -1) {
292            mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage();
293        }
294        return mSaveInstanceStateItemIndex;
295    }
296
297    /** Returns the page in the current orientation which is expected to contain the specified
298     *  item index. */
299    int getPageForComponent(int index) {
300        switch (mContentType) {
301        case Applications: {
302            int numItemsPerPage = mCellCountX * mCellCountY;
303            return (index / numItemsPerPage);
304        }
305        case Widgets: {
306            int numItemsPerPage = mWidgetCountX * mWidgetCountY;
307            return (index / numItemsPerPage);
308        }}
309        return -1;
310    }
311
312    /**
313     * This differs from isDataReady as this is the test done if isDataReady is not set.
314     */
315    private boolean testDataReady() {
316        // We only do this test once, and we default to the Applications page, so we only really
317        // have to wait for there to be apps.
318        if (mContentType == AppsCustomizePagedView.ContentType.Widgets) {
319            return !mApps.isEmpty() && !mWidgets.isEmpty();
320        } else {
321            return !mApps.isEmpty();
322        }
323    }
324
325    /** Restores the page for an item at the specified index */
326    void restorePageForIndex(int index) {
327        if (index < 0) return;
328
329        int page = getPageForComponent(index);
330        if (page > -1) {
331            if (getChildCount() > 0) {
332                invalidatePageData(page);
333            } else {
334                mRestorePage = page;
335            }
336        }
337    }
338
339    protected void onDataReady(int width, int height) {
340        // Note that we transpose the counts in portrait so that we get a similar layout
341        boolean isLandscape = getResources().getConfiguration().orientation ==
342            Configuration.ORIENTATION_LANDSCAPE;
343        int maxCellCountX = Integer.MAX_VALUE;
344        int maxCellCountY = Integer.MAX_VALUE;
345        if (LauncherApplication.isScreenLarge()) {
346            maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
347                LauncherModel.getCellCountY());
348            maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
349                LauncherModel.getCellCountX());
350        }
351
352        // Now that the data is ready, we can calculate the content width, the number of cells to
353        // use for each page
354        mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
355        mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
356                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
357        mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
358        mCellCountX = mWidgetSpacingLayout.getCellCountX();
359        mCellCountY = mWidgetSpacingLayout.getCellCountY();
360
361        // Force a measure to update recalculate the gaps
362        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
363        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
364        mWidgetSpacingLayout.measure(widthSpec, heightSpec);
365        mContentWidth = mWidgetSpacingLayout.getContentWidth();
366        invalidatePageData(Math.max(0, mRestorePage));
367        mRestorePage = -1;
368    }
369
370    @Override
371    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
372        int width = MeasureSpec.getSize(widthMeasureSpec);
373        int height = MeasureSpec.getSize(heightMeasureSpec);
374        if (!isDataReady()) {
375            if (testDataReady()) {
376                setDataIsReady();
377                setMeasuredDimension(width, height);
378                onDataReady(width, height);
379            }
380        }
381
382        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
383    }
384
385    /** Removes and returns the ResolveInfo with the specified ComponentName */
386    private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list,
387            ComponentName cn) {
388        Iterator<ResolveInfo> iter = list.iterator();
389        while (iter.hasNext()) {
390            ResolveInfo rinfo = iter.next();
391            ActivityInfo info = rinfo.activityInfo;
392            ComponentName c = new ComponentName(info.packageName, info.name);
393            if (c.equals(cn)) {
394                iter.remove();
395                return rinfo;
396            }
397        }
398        return null;
399    }
400
401    public void onPackagesUpdated() {
402        // TODO: this isn't ideal, but we actually need to delay here. This call is triggered
403        // by a broadcast receiver, and in order for it to work correctly, we need to know that
404        // the AppWidgetService has already received and processed the same broadcast. Since there
405        // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally,
406        // we should have a more precise way of ensuring the AppWidgetService is up to date.
407        postDelayed(new Runnable() {
408           public void run() {
409               updatePackages();
410           }
411        }, 500);
412    }
413
414    public void updatePackages() {
415        // Get the list of widgets and shortcuts
416        boolean wasEmpty = mWidgets.isEmpty();
417        mWidgets.clear();
418        List<AppWidgetProviderInfo> widgets =
419            AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
420        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
421        List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
422        mWidgets.addAll(widgets);
423        mWidgets.addAll(shortcuts);
424        Collections.sort(mWidgets,
425                new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
426
427        if (wasEmpty) {
428            // The next layout pass will trigger data-ready if both widgets and apps are set, so request
429            // a layout to do this test and invalidate the page data when ready.
430            if (testDataReady()) requestLayout();
431        } else {
432            invalidatePageData();
433        }
434    }
435
436    @Override
437    public void onClick(View v) {
438        // When we have exited all apps or are in transition, disregard clicks
439        if (!mLauncher.isAllAppsCustomizeOpen() ||
440                mLauncher.getWorkspace().isSwitchingState()) return;
441
442        if (v instanceof PagedViewIcon) {
443            // Animate some feedback to the click
444            final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
445            animateClickFeedback(v, new Runnable() {
446                @Override
447                public void run() {
448                    mLauncher.startActivitySafely(appInfo.intent, appInfo);
449                }
450            });
451        } else if (v instanceof PagedViewWidget) {
452            // Let the user know that they have to long press to add a widget
453            Toast.makeText(getContext(), R.string.long_press_widget_to_add,
454                    Toast.LENGTH_SHORT).show();
455
456            // Create a little animation to show that the widget can move
457            float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
458            final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
459            AnimatorSet bounce = new AnimatorSet();
460            ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
461            tyuAnim.setDuration(125);
462            ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
463            tydAnim.setDuration(100);
464            bounce.play(tyuAnim).before(tydAnim);
465            bounce.setInterpolator(new AccelerateInterpolator());
466            bounce.start();
467        }
468    }
469
470    /*
471     * PagedViewWithDraggableItems implementation
472     */
473    @Override
474    protected void determineDraggingStart(android.view.MotionEvent ev) {
475        // Disable dragging by pulling an app down for now.
476    }
477
478    private void beginDraggingApplication(View v) {
479        mLauncher.getWorkspace().onDragStartedWithItem(v);
480        mLauncher.getWorkspace().beginDragShared(v, this);
481    }
482
483    private void beginDraggingWidget(View v) {
484        // Get the widget preview as the drag representation
485        ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
486        PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
487
488        // Compose the drag image
489        Bitmap b;
490        Drawable preview = image.getDrawable();
491        int w = preview.getIntrinsicWidth();
492        int h = preview.getIntrinsicHeight();
493        if (createItemInfo instanceof PendingAddWidgetInfo) {
494            PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo;
495            int[] spanXY = CellLayout.rectToCell(getResources(),
496                    createWidgetInfo.minWidth, createWidgetInfo.minHeight, null);
497            createItemInfo.spanX = spanXY[0];
498            createItemInfo.spanY = spanXY[1];
499
500            b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
501            renderDrawableToBitmap(preview, b, 0, 0, w, h, 1, 1, mDragViewMultiplyColor);
502        } else {
503            // Workaround for the fact that we don't keep the original ResolveInfo associated with
504            // the shortcut around.  To get the icon, we just render the preview image (which has
505            // the shortcut icon) to a new drag bitmap that clips the non-icon space.
506            b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension,
507                    mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888);
508            mCanvas.setBitmap(b);
509            mCanvas.save();
510            preview.draw(mCanvas);
511            mCanvas.restore();
512            mCanvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY);
513            mCanvas.setBitmap(null);
514            createItemInfo.spanX = createItemInfo.spanY = 1;
515        }
516
517        // Start the drag
518        mLauncher.lockScreenOrientation();
519        mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX,
520                createItemInfo.spanY, b);
521        mDragController.startDrag(image, b, this, createItemInfo,
522                DragController.DRAG_ACTION_COPY, null);
523        b.recycle();
524    }
525    @Override
526    protected boolean beginDragging(View v) {
527        if (!super.beginDragging(v)) return false;
528
529        // Go into spring loaded mode (must happen before we startDrag())
530        int currentPageIndex = mLauncher.getWorkspace().getCurrentPage();
531        CellLayout currentPage = (CellLayout) mLauncher.getWorkspace().getChildAt(currentPageIndex);
532        mLauncher.enterSpringLoadedDragMode(currentPage);
533
534        if (v instanceof PagedViewIcon) {
535            beginDraggingApplication(v);
536        } else if (v instanceof PagedViewWidget) {
537            beginDraggingWidget(v);
538        }
539        return true;
540    }
541    private void endDragging(View target, boolean success) {
542        mLauncher.getWorkspace().onDragStopped(success);
543        if (!success || (target != mLauncher.getWorkspace() &&
544                !(target instanceof DeleteDropTarget))) {
545            // Exit spring loaded mode if we have not successfully dropped or have not handled the
546            // drop in Workspace
547            mLauncher.exitSpringLoadedDragMode();
548        }
549        mLauncher.unlockScreenOrientation();
550
551    }
552
553    @Override
554    public void onDropCompleted(View target, DragObject d, boolean success) {
555        endDragging(target, success);
556
557        // Display an error message if the drag failed due to there not being enough space on the
558        // target layout we were dropping on.
559        if (!success) {
560            boolean showOutOfSpaceMessage = false;
561            if (target instanceof Workspace) {
562                int currentScreen = mLauncher.getCurrentWorkspaceScreen();
563                Workspace workspace = (Workspace) target;
564                CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
565                ItemInfo itemInfo = (ItemInfo) d.dragInfo;
566                if (layout != null) {
567                    layout.calculateSpans(itemInfo);
568                    showOutOfSpaceMessage =
569                            !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
570                }
571            }
572            // TODO-APPS_CUSTOMIZE: We need to handle this for folders as well later.
573            if (showOutOfSpaceMessage) {
574                mLauncher.showOutOfSpaceMessage();
575            }
576        }
577    }
578
579    public void setContentType(ContentType type) {
580        mContentType = type;
581        invalidatePageData(0, (type != ContentType.Applications));
582    }
583
584    public boolean isContentType(ContentType type) {
585        return (mContentType == type);
586    }
587
588    public void setCurrentPageToWidgets() {
589        invalidatePageData(0);
590    }
591
592    /*
593     * Apps PagedView implementation
594     */
595    private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
596        int childCount = layout.getChildCount();
597        for (int i = 0; i < childCount; ++i) {
598            layout.getChildAt(i).setVisibility(visibility);
599        }
600    }
601    private void setupPage(PagedViewCellLayout layout) {
602        layout.setCellCount(mCellCountX, mCellCountY);
603        layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
604        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
605                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
606
607        // Note: We force a measure here to get around the fact that when we do layout calculations
608        // immediately after syncing, we don't have a proper width.  That said, we already know the
609        // expected page width, so we can actually optimize by hiding all the TextView-based
610        // children that are expensive to measure, and let that happen naturally later.
611        setVisibilityOnChildren(layout, View.GONE);
612        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
613        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
614        layout.setMinimumWidth(getPageContentWidth());
615        layout.measure(widthSpec, heightSpec);
616        setVisibilityOnChildren(layout, View.VISIBLE);
617    }
618    public void syncAppsPages() {
619        // Ensure that we have the right number of pages
620        Context context = getContext();
621        int numPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
622        for (int i = 0; i < numPages; ++i) {
623            PagedViewCellLayout layout = new PagedViewCellLayout(context);
624            setupPage(layout);
625            addView(layout);
626        }
627    }
628    public void syncAppsPageItems(int page, boolean immediate) {
629        // ensure that we have the right number of items on the pages
630        int numPages = getPageCount();
631        int numCells = mCellCountX * mCellCountY;
632        int startIndex = page * numCells;
633        int endIndex = Math.min(startIndex + numCells, mApps.size());
634        PagedViewCellLayout layout = (PagedViewCellLayout) getChildAt(page);
635
636        layout.removeAllViewsOnPage();
637        ArrayList<Object> items = new ArrayList<Object>();
638        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
639        for (int i = startIndex; i < endIndex; ++i) {
640            ApplicationInfo info = mApps.get(i);
641            PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
642                    R.layout.apps_customize_application, layout, false);
643            icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper);
644            icon.setOnClickListener(this);
645            icon.setOnLongClickListener(this);
646            icon.setOnTouchListener(this);
647
648            int index = i - startIndex;
649            int x = index % mCellCountX;
650            int y = index / mCellCountX;
651            layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
652
653            items.add(info);
654            images.add(info.iconBitmap);
655        }
656
657        // Create the hardware layers
658        layout.allowHardwareLayerCreation();
659        layout.createHardwareLayers();
660
661        if (mFadeInAdjacentScreens) {
662            prepareGenerateHoloOutlinesTask(page, items, images);
663        }
664    }
665
666    /**
667     * Return the appropriate thread priority for loading for a given page (we give the current
668     * page much higher priority)
669     */
670    private int getThreadPriorityForPage(int page) {
671        // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
672        int pageDiff = Math.abs(page - mCurrentPage);
673        if (pageDiff <= 0) {
674            // return Process.THREAD_PRIORITY_DEFAULT;
675            return Process.THREAD_PRIORITY_MORE_FAVORABLE;
676        } else if (pageDiff <= 1) {
677            // return Process.THREAD_PRIORITY_BACKGROUND;
678            return Process.THREAD_PRIORITY_DEFAULT;
679        } else {
680            // return Process.THREAD_PRIORITY_LOWEST;
681            return Process.THREAD_PRIORITY_DEFAULT;
682        }
683    }
684    private int getSleepForPage(int page) {
685        int pageDiff = Math.abs(page - mCurrentPage) - 1;
686        return Math.max(0, pageDiff * sPageSleepDelay);
687    }
688    /**
689     * Creates and executes a new AsyncTask to load a page of widget previews.
690     */
691    private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
692            int cellWidth, int cellHeight, int cellCountX) {
693        // Prune all tasks that are no longer needed
694        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
695        while (iter.hasNext()) {
696            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
697            int taskPage = task.page;
698            if ((taskPage == page) ||
699                    taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
700                    taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
701                task.cancel(false);
702                iter.remove();
703            } else {
704                task.setThreadPriority(getThreadPriorityForPage(taskPage));
705            }
706        }
707
708        // We introduce a slight delay to order the loading of side pages so that we don't thrash
709        final int sleepMs = getSleepForPage(page);
710        AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
711            cellCountX, new AsyncTaskCallback() {
712                @Override
713                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
714                    try {
715                        Thread.sleep(sleepMs);
716                    } catch (Exception e) {}
717                    loadWidgetPreviewsInBackground(task, data);
718                }
719            },
720            new AsyncTaskCallback() {
721                @Override
722                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
723                    mRunningTasks.remove(task);
724                    if (task.isCancelled()) return;
725                    if (task.page > getPageCount()) return;
726                    if (task.pageContentType != mContentType) return;
727                    onSyncWidgetPageItems(data);
728                }
729        });
730
731        // Ensure that the task is appropriately prioritized and runs in parallel
732        AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, mContentType,
733                AsyncTaskPageData.Type.LoadWidgetPreviewData);
734        t.setThreadPriority(getThreadPriorityForPage(page));
735        t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
736        mRunningTasks.add(t);
737    }
738    /**
739     * Creates and executes a new AsyncTask to load the outlines for a page of content.
740     */
741    private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items,
742            ArrayList<Bitmap> images) {
743        // Prune old tasks for this page
744        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
745        while (iter.hasNext()) {
746            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
747            int taskPage = task.page;
748            if ((taskPage == page) &&
749                    (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) {
750                task.cancel(false);
751                iter.remove();
752            }
753        }
754
755        AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images,
756            new AsyncTaskCallback() {
757                @Override
758                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
759                    // Ensure that this task starts running at the correct priority
760                    task.syncThreadPriority();
761
762                    ArrayList<Bitmap> images = data.generatedImages;
763                    ArrayList<Bitmap> srcImages = data.sourceImages;
764                    int count = srcImages.size();
765                    Canvas c = new Canvas();
766                    for (int i = 0; i < count && !task.isCancelled(); ++i) {
767                        // Before work on each item, ensure that this task is running at the correct
768                        // priority
769                        task.syncThreadPriority();
770
771                        Bitmap b = srcImages.get(i);
772                        Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(),
773                                Bitmap.Config.ARGB_8888);
774
775                        c.setBitmap(outline);
776                        c.save();
777                        c.drawBitmap(b, 0, 0, null);
778                        c.restore();
779                        c.setBitmap(null);
780
781                        images.add(outline);
782                    }
783                }
784            },
785            new AsyncTaskCallback() {
786                @Override
787                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
788                    mRunningTasks.remove(task);
789                    if (task.isCancelled()) return;
790                    if (task.page > getPageCount()) return;
791                    if (task.pageContentType != mContentType) return;
792                    onHolographicPageItemsLoaded(data);
793                }
794            });
795
796        // Ensure that the outline task always runs in the background, serially
797        AppsCustomizeAsyncTask t =
798            new AppsCustomizeAsyncTask(page, mContentType,
799                    AsyncTaskPageData.Type.LoadHolographicIconsData);
800        t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
801        t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData);
802        mRunningTasks.add(t);
803    }
804
805    /*
806     * Widgets PagedView implementation
807     */
808    private void setupPage(PagedViewGridLayout layout) {
809        layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
810                mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
811
812        // Note: We force a measure here to get around the fact that when we do layout calculations
813        // immediately after syncing, we don't have a proper width.
814        int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
815        int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
816        layout.setMinimumWidth(getPageContentWidth());
817        layout.measure(widthSpec, heightSpec);
818    }
819    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
820            float scaleX, float scaleY) {
821        renderDrawableToBitmap(d, bitmap, x, y, w, h, scaleX, scaleY, 0xFFFFFFFF);
822    }
823    private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
824            float scaleX, float scaleY, int multiplyColor) {
825        if (bitmap != null) {
826            Canvas c = new Canvas(bitmap);
827            c.scale(scaleX, scaleY);
828            Rect oldBounds = d.copyBounds();
829            d.setBounds(x, y, x + w, y + h);
830            d.draw(c);
831            d.setBounds(oldBounds); // Restore the bounds
832            if (multiplyColor != 0xFFFFFFFF) {
833                c.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY);
834            }
835            c.setBitmap(null);
836        }
837    }
838    private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) {
839        // Render the icon
840        Bitmap preview = Bitmap.createBitmap(cellWidth, mAppIconSize, Config.ARGB_8888);
841        Drawable icon = mIconCache.getFullResIcon(info, mPackageManager);
842        renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize, 1f, 1f);
843        return preview;
844    }
845    private Bitmap getWidgetPreview(AppWidgetProviderInfo info,
846            int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) {
847
848        // Calculate the size of the drawable
849        cellHSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellHSpan));
850        cellVSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellVSpan));
851        int expectedWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan);
852        int expectedHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan);
853
854        // Scale down the bitmap to fit the space
855        float widgetPreviewScale = (float) cellWidth / expectedWidth;
856        expectedWidth = (int) (widgetPreviewScale * expectedWidth);
857        expectedHeight = (int) (widgetPreviewScale * expectedHeight);
858
859        // Load the preview image if possible
860        String packageName = info.provider.getPackageName();
861        Drawable drawable = null;
862        Bitmap preview = null;
863        if (info.previewImage != 0) {
864            drawable = mPackageManager.getDrawable(packageName, info.previewImage, null);
865            if (drawable == null) {
866                Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon)
867                        + " for provider: " + info.provider);
868            } else {
869                // Scale down the preview to the dimensions we want
870                int imageWidth = drawable.getIntrinsicWidth();
871                int imageHeight = drawable.getIntrinsicHeight();
872                float aspect = (float) imageWidth / imageHeight;
873                int newWidth = imageWidth;
874                int newHeight = imageHeight;
875                if (aspect > 1f) {
876                    newWidth = expectedWidth;
877                    newHeight = (int) (imageHeight * ((float) expectedWidth / imageWidth));
878                } else {
879                    newHeight = expectedHeight;
880                    newWidth = (int) (imageWidth * ((float) expectedHeight / imageHeight));
881                }
882
883                preview = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
884                renderDrawableToBitmap(drawable, preview, 0, 0, newWidth, newHeight, 1f, 1f);
885            }
886        }
887
888        // Generate a preview image if we couldn't load one
889        if (drawable == null) {
890            Resources resources = mLauncher.getResources();
891            int bitmapWidth;
892            int bitmapHeight;
893
894            // Specify the dimensions of the bitmap (since we are using a default preview bg with
895            // the full icon, we only imply the aspect ratio of the widget)
896            if (cellHSpan == cellVSpan) {
897                bitmapWidth = bitmapHeight = cellWidth;
898                expectedWidth = expectedHeight = mWidgetPreviewIconPaddedDimension;
899            } else if (cellHSpan >= cellVSpan) {
900                bitmapWidth = expectedWidth = cellWidth;
901                bitmapHeight = expectedHeight = mWidgetPreviewIconPaddedDimension;
902            } else {
903                // Note that in vertical widgets, we might not have enough space due to the text
904                // label, so be conservative and use the width as a height bound
905                bitmapWidth = expectedWidth = mWidgetPreviewIconPaddedDimension;
906                bitmapHeight = expectedHeight = cellWidth;
907            }
908
909            preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
910            renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, expectedWidth,
911                    expectedHeight, 1f, 1f);
912
913            // Draw the icon in the top left corner
914            try {
915                Drawable icon = null;
916                if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null);
917                if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application);
918
919                int offset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
920                renderDrawableToBitmap(icon, preview, offset, offset,
921                        mAppIconSize, mAppIconSize, 1f, 1f);
922            } catch (Resources.NotFoundException e) {}
923        }
924        return preview;
925    }
926    public void syncWidgetPages() {
927        // Ensure that we have the right number of pages
928        Context context = getContext();
929        int numPages = (int) Math.ceil(mWidgets.size() /
930                (float) (mWidgetCountX * mWidgetCountY));
931        for (int j = 0; j < numPages; ++j) {
932            PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
933                    mWidgetCountY);
934            setupPage(layout);
935            addView(layout);
936        }
937    }
938    public void syncWidgetPageItems(int page, boolean immediate) {
939        int numItemsPerPage = mWidgetCountX * mWidgetCountY;
940        int contentWidth = mWidgetSpacingLayout.getContentWidth();
941        int contentHeight = mWidgetSpacingLayout.getContentHeight();
942
943        // Calculate the dimensions of each cell we are giving to each widget
944        ArrayList<Object> items = new ArrayList<Object>();
945        int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
946                - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
947        int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
948                - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
949
950        int offset = page * numItemsPerPage;
951        for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
952            items.add(mWidgets.get(i));
953        }
954
955        if (immediate) {
956            AsyncTaskPageData data = new AsyncTaskPageData(page, items, cellWidth, cellHeight,
957                    mWidgetCountX, null, null);
958            loadWidgetPreviewsInBackground(null, data);
959            onSyncWidgetPageItems(data);
960        } else {
961            prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, mWidgetCountX);
962        }
963    }
964    private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
965            AsyncTaskPageData data) {
966        if (task != null) {
967            // Ensure that this task starts running at the correct priority
968            task.syncThreadPriority();
969        }
970
971        // Load each of the widget/shortcut previews
972        ArrayList<Object> items = data.items;
973        ArrayList<Bitmap> images = data.generatedImages;
974        int count = items.size();
975        int cellWidth = data.cellWidth;
976        int cellHeight = data.cellHeight;
977        for (int i = 0; i < count; ++i) {
978            if (task != null) {
979                // Ensure we haven't been cancelled yet
980                if (task.isCancelled()) break;
981                // Before work on each item, ensure that this task is running at the correct
982                // priority
983                task.syncThreadPriority();
984            }
985
986            Object rawInfo = items.get(i);
987            if (rawInfo instanceof AppWidgetProviderInfo) {
988                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
989                int[] cellSpans = CellLayout.rectToCell(getResources(),
990                        info.minWidth, info.minHeight, null);
991                images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1],
992                        cellWidth, cellHeight));
993            } else if (rawInfo instanceof ResolveInfo) {
994                // Fill in the shortcuts information
995                ResolveInfo info = (ResolveInfo) rawInfo;
996                images.add(getShortcutPreview(info, cellWidth, cellHeight));
997            }
998        }
999    }
1000    private void onSyncWidgetPageItems(AsyncTaskPageData data) {
1001        int page = data.page;
1002        PagedViewGridLayout layout = (PagedViewGridLayout) getChildAt(page);
1003        // Only set the column count once we have items
1004        layout.setColumnCount(layout.getCellCountX());
1005
1006        ArrayList<Object> items = data.items;
1007        int count = items.size();
1008        int cellWidth = data.cellWidth;
1009        int cellHeight = data.cellHeight;
1010        int cellCountX = data.cellCountX;
1011        for (int i = 0; i < count; ++i) {
1012            Object rawInfo = items.get(i);
1013            PendingAddItemInfo createItemInfo = null;
1014            PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1015                    R.layout.apps_customize_widget, layout, false);
1016            if (rawInfo instanceof AppWidgetProviderInfo) {
1017                // Fill in the widget information
1018                AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1019                createItemInfo = new PendingAddWidgetInfo(info, null, null, "13");
1020                int[] cellSpans = CellLayout.rectToCell(getResources(),
1021                        info.minWidth, info.minHeight, null);
1022                FastBitmapDrawable preview = new FastBitmapDrawable(data.generatedImages.get(i));
1023                widget.applyFromAppWidgetProviderInfo(info, preview, -1, cellSpans,
1024                        mHolographicOutlineHelper);
1025                widget.setTag(createItemInfo);
1026            } else if (rawInfo instanceof ResolveInfo) {
1027                // Fill in the shortcuts information
1028                ResolveInfo info = (ResolveInfo) rawInfo;
1029                createItemInfo = new PendingAddItemInfo("14");
1030                createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1031                createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1032                        info.activityInfo.name);
1033                FastBitmapDrawable preview = new FastBitmapDrawable(data.generatedImages.get(i));
1034                widget.applyFromResolveInfo(mPackageManager, info, preview,
1035                        mHolographicOutlineHelper);
1036                widget.setTag(createItemInfo);
1037            }
1038            widget.setOnClickListener(this);
1039            widget.setOnLongClickListener(this);
1040            widget.setOnTouchListener(this);
1041
1042            // Layout each widget
1043            int ix = i % cellCountX;
1044            int iy = i / cellCountX;
1045            GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1046                    GridLayout.spec(iy, GridLayout.LEFT),
1047                    GridLayout.spec(ix, GridLayout.TOP));
1048            lp.width = cellWidth;
1049            lp.height = cellHeight;
1050            lp.setGravity(Gravity.TOP | Gravity.LEFT);
1051            if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1052            if (iy > 0) lp.topMargin = mWidgetHeightGap;
1053            layout.addView(widget, lp);
1054        }
1055
1056        invalidate();
1057        forceUpdateAdjacentPagesAlpha();
1058
1059        if (mFadeInAdjacentScreens) {
1060            prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages);
1061        }
1062    }
1063    private void onHolographicPageItemsLoaded(AsyncTaskPageData data) {
1064        // Invalidate early to short-circuit children invalidates
1065        invalidate();
1066
1067        int page = data.page;
1068        ViewGroup layout = (ViewGroup) getChildAt(page);
1069        if (layout instanceof PagedViewCellLayout) {
1070            PagedViewCellLayout cl = (PagedViewCellLayout) layout;
1071            int count = cl.getPageChildCount();
1072            if (count != data.generatedImages.size()) return;
1073            for (int i = 0; i < count; ++i) {
1074                PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i);
1075                icon.setHolographicOutline(data.generatedImages.get(i));
1076            }
1077        } else {
1078            int count = layout.getChildCount();
1079            if (count != data.generatedImages.size()) return;
1080            for (int i = 0; i < count; ++i) {
1081                View v = layout.getChildAt(i);
1082                ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i));
1083            }
1084        }
1085    }
1086
1087    @Override
1088    public void syncPages() {
1089        removeAllViews();
1090
1091        // Remove all background asyc tasks if we are loading content anew
1092        Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1093        while (iter.hasNext()) {
1094            AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1095            task.cancel(false);
1096            iter.remove();
1097        }
1098
1099        switch (mContentType) {
1100        case Applications:
1101            syncAppsPages();
1102            break;
1103        case Widgets:
1104            syncWidgetPages();
1105            break;
1106        }
1107    }
1108    @Override
1109    public void syncPageItems(int page, boolean immediate) {
1110        switch (mContentType) {
1111        case Applications:
1112            syncAppsPageItems(page, immediate);
1113            break;
1114        case Widgets:
1115            syncWidgetPageItems(page, immediate);
1116            break;
1117        }
1118    }
1119
1120    /**
1121     * Used by the parent to get the content width to set the tab bar to
1122     * @return
1123     */
1124    public int getPageContentWidth() {
1125        return mContentWidth;
1126    }
1127
1128    @Override
1129    protected void onPageBeginMoving() {
1130        /* TO BE ENABLED LATER
1131        setChildrenDrawnWithCacheEnabled(true);
1132        for (int i = 0; i < getChildCount(); ++i) {
1133            View v = getChildAt(i);
1134            if (v instanceof PagedViewCellLayout) {
1135                ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(true);
1136            }
1137        }
1138        */
1139        super.onPageBeginMoving();
1140    }
1141
1142    @Override
1143    protected void onPageEndMoving() {
1144        /* TO BE ENABLED LATER
1145        for (int i = 0; i < getChildCount(); ++i) {
1146            View v = getChildAt(i);
1147            if (v instanceof PagedViewCellLayout) {
1148                ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(false);
1149            }
1150        }
1151        setChildrenDrawnWithCacheEnabled(false);
1152        */
1153        super.onPageEndMoving();
1154
1155        // We reset the save index when we change pages so that it will be recalculated on next
1156        // rotation
1157        mSaveInstanceStateItemIndex = -1;
1158    }
1159
1160    /*
1161     * AllAppsView implementation
1162     */
1163    @Override
1164    public void setup(Launcher launcher, DragController dragController) {
1165        mLauncher = launcher;
1166        mDragController = dragController;
1167    }
1168    @Override
1169    public void zoom(float zoom, boolean animate) {
1170        // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1171    }
1172    @Override
1173    public boolean isVisible() {
1174        return (getVisibility() == VISIBLE);
1175    }
1176    @Override
1177    public boolean isAnimating() {
1178        return false;
1179    }
1180    @Override
1181    public void setApps(ArrayList<ApplicationInfo> list) {
1182        mApps = list;
1183        Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
1184
1185        // The next layout pass will trigger data-ready if both widgets and apps are set, so
1186        // request a layout to do this test and invalidate the page data when ready.
1187        if (testDataReady()) requestLayout();
1188    }
1189    private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1190        // We add it in place, in alphabetical order
1191        int count = list.size();
1192        for (int i = 0; i < count; ++i) {
1193            ApplicationInfo info = list.get(i);
1194            int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1195            if (index < 0) {
1196                mApps.add(-(index + 1), info);
1197            }
1198        }
1199    }
1200    @Override
1201    public void addApps(ArrayList<ApplicationInfo> list) {
1202        addAppsWithoutInvalidate(list);
1203        invalidatePageData();
1204    }
1205    private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1206        ComponentName removeComponent = item.intent.getComponent();
1207        int length = list.size();
1208        for (int i = 0; i < length; ++i) {
1209            ApplicationInfo info = list.get(i);
1210            if (info.intent.getComponent().equals(removeComponent)) {
1211                return i;
1212            }
1213        }
1214        return -1;
1215    }
1216    private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1217        // loop through all the apps and remove apps that have the same component
1218        int length = list.size();
1219        for (int i = 0; i < length; ++i) {
1220            ApplicationInfo info = list.get(i);
1221            int removeIndex = findAppByComponent(mApps, info);
1222            if (removeIndex > -1) {
1223                mApps.remove(removeIndex);
1224            }
1225        }
1226    }
1227    @Override
1228    public void removeApps(ArrayList<ApplicationInfo> list) {
1229        removeAppsWithoutInvalidate(list);
1230        invalidatePageData();
1231    }
1232    @Override
1233    public void updateApps(ArrayList<ApplicationInfo> list) {
1234        // We remove and re-add the updated applications list because it's properties may have
1235        // changed (ie. the title), and this will ensure that the items will be in their proper
1236        // place in the list.
1237        removeAppsWithoutInvalidate(list);
1238        addAppsWithoutInvalidate(list);
1239        invalidatePageData();
1240    }
1241
1242    @Override
1243    public void reset() {
1244        if (mContentType != ContentType.Applications) {
1245            // Reset to the first page of the Apps pane
1246            AppsCustomizeTabHost tabs = (AppsCustomizeTabHost)
1247                    mLauncher.findViewById(R.id.apps_customize_pane);
1248            tabs.selectAppsTab();
1249        } else if (getCurrentPage() != 0) {
1250            invalidatePageData(0);
1251        }
1252    }
1253    @Override
1254    public void dumpState() {
1255        // TODO: Dump information related to current list of Applications, Widgets, etc.
1256        ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps);
1257        dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets);
1258    }
1259    private void dumpAppWidgetProviderInfoList(String tag, String label,
1260            ArrayList<Object> list) {
1261        Log.d(tag, label + " size=" + list.size());
1262        for (Object i: list) {
1263            if (i instanceof AppWidgetProviderInfo) {
1264                AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1265                Log.d(tag, "   label=\"" + info.label + "\" previewImage=" + info.previewImage
1266                        + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1267                        + " initialLayout=" + info.initialLayout
1268                        + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1269            } else if (i instanceof ResolveInfo) {
1270                ResolveInfo info = (ResolveInfo) i;
1271                Log.d(tag, "   label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1272                        + info.icon);
1273            }
1274        }
1275    }
1276    @Override
1277    public void surrender() {
1278        // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1279        // should stop this now.
1280    }
1281
1282    /*
1283     * We load an extra page on each side to prevent flashes from scrolling and loading of the
1284     * widget previews in the background with the AsyncTasks.
1285     */
1286    protected int getAssociatedLowerPageBound(int page) {
1287        return Math.max(0, page - 2);
1288    }
1289    protected int getAssociatedUpperPageBound(int page) {
1290        final int count = getChildCount();
1291        return Math.min(page + 2, count - 1);
1292    }
1293
1294    @Override
1295    protected String getCurrentPageDescription() {
1296        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1297        int stringId = R.string.default_scroll_format;
1298        switch (mContentType) {
1299        case Applications:
1300            stringId = R.string.apps_customize_apps_scroll_format;
1301            break;
1302        case Widgets:
1303            stringId = R.string.apps_customize_widgets_scroll_format;
1304            break;
1305        }
1306        return String.format(mContext.getString(stringId), page + 1, getChildCount());
1307    }
1308}
1309