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