LauncherModel.java revision 05bf644e371c9d965ba864cf7dda6515c7cdce91
1/*
2 * Copyright (C) 2008 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.app.SearchManager;
20import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
22import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
29import android.content.Intent.ShortcutIconResource;
30import android.content.pm.ActivityInfo;
31import android.content.pm.PackageInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
36import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
39import android.graphics.BitmapFactory;
40import android.net.Uri;
41import android.os.Environment;
42import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.Parcelable;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.util.Log;
49
50import com.android.launcher.R;
51import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
52
53import java.lang.ref.WeakReference;
54import java.net.URISyntaxException;
55import java.text.Collator;
56import java.util.ArrayList;
57import java.util.Collections;
58import java.util.Comparator;
59import java.util.HashMap;
60import java.util.List;
61
62/**
63 * Maintains in-memory state of the Launcher. It is expected that there should be only one
64 * LauncherModel object held in a static. Also provide APIs for updating the database state
65 * for the Launcher.
66 */
67public class LauncherModel extends BroadcastReceiver {
68    static final boolean DEBUG_LOADERS = false;
69    static final String TAG = "Launcher.Model";
70
71    private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
72    private final boolean mAppsCanBeOnExternalStorage;
73    private int mBatchSize; // 0 is all apps at once
74    private int mAllAppsLoadDelay; // milliseconds between batches
75
76    private final LauncherApplication mApp;
77    private final Object mLock = new Object();
78    private DeferredHandler mHandler = new DeferredHandler();
79    private LoaderTask mLoaderTask;
80
81    private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
82    static {
83        sWorkerThread.start();
84    }
85    private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
86
87    // We start off with everything not loaded.  After that, we assume that
88    // our monitoring of the package manager provides all updates and we never
89    // need to do a requery.  These are only ever touched from the loader thread.
90    private boolean mWorkspaceLoaded;
91    private boolean mAllAppsLoaded;
92
93    private WeakReference<Callbacks> mCallbacks;
94
95    // < only access in worker thread >
96    private AllAppsList mAllAppsList;
97
98    // sItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
99    // LauncherModel to their ids
100    static final HashMap<Long, ItemInfo> sItemsIdMap = new HashMap<Long, ItemInfo>();
101
102    // sItems is passed to bindItems, which expects a list of all folders and shortcuts created by
103    //       LauncherModel that are directly on the home screen (however, no widgets or shortcuts
104    //       within folders).
105    static final ArrayList<ItemInfo> sWorkspaceItems = new ArrayList<ItemInfo>();
106
107    // sAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
108    static final ArrayList<LauncherAppWidgetInfo> sAppWidgets =
109        new ArrayList<LauncherAppWidgetInfo>();
110
111    // sFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
112    static final HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
113
114    // sDbIconCache is the set of ItemInfos that need to have their icons updated in the database
115    static final HashMap<Object, byte[]> sDbIconCache = new HashMap<Object, byte[]>();
116
117    // </ only access in worker thread >
118
119    private IconCache mIconCache;
120    private Bitmap mDefaultIcon;
121
122    private static int mCellCountX;
123    private static int mCellCountY;
124
125    protected int mPreviousConfigMcc;
126
127    public interface Callbacks {
128        public boolean setLoadOnResume();
129        public int getCurrentWorkspaceScreen();
130        public void startBinding();
131        public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
132        public void bindFolders(HashMap<Long,FolderInfo> folders);
133        public void finishBindingItems();
134        public void bindAppWidget(LauncherAppWidgetInfo info);
135        public void bindAllApplications(ArrayList<ApplicationInfo> apps);
136        public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
137        public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
138        public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent);
139        public void bindPackagesUpdated();
140        public boolean isAllAppsVisible();
141        public void bindSearchablesChanged();
142    }
143
144    LauncherModel(LauncherApplication app, IconCache iconCache) {
145        mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
146        mApp = app;
147        mAllAppsList = new AllAppsList(iconCache);
148        mIconCache = iconCache;
149
150        mDefaultIcon = Utilities.createIconBitmap(
151                mIconCache.getFullResDefaultActivityIcon(), app);
152
153        final Resources res = app.getResources();
154        mAllAppsLoadDelay = res.getInteger(R.integer.config_allAppsBatchLoadDelay);
155        mBatchSize = res.getInteger(R.integer.config_allAppsBatchSize);
156        Configuration config = res.getConfiguration();
157        mPreviousConfigMcc = config.mcc;
158    }
159
160    public Bitmap getFallbackIcon() {
161        return Bitmap.createBitmap(mDefaultIcon);
162    }
163
164    public void unbindWorkspaceItems() {
165        sWorker.post(new Runnable() {
166            @Override
167            public void run() {
168                unbindWorkspaceItemsOnMainThread();
169            }
170        });
171    }
172
173    /** Unbinds all the sWorkspaceItems on the main thread, and return a copy of sWorkspaceItems
174     * that is save to reference from the main thread. */
175    private ArrayList<ItemInfo> unbindWorkspaceItemsOnMainThread() {
176        // Ensure that we don't use the same workspace items data structure on the main thread
177        // by making a copy of workspace items first.
178        final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(sWorkspaceItems);
179        final ArrayList<ItemInfo> appWidgets = new ArrayList<ItemInfo>(sAppWidgets);
180        mHandler.post(new Runnable() {
181            @Override
182            public void run() {
183               for (ItemInfo item : workspaceItems) {
184                   item.unbind();
185               }
186               for (ItemInfo item : appWidgets) {
187                   item.unbind();
188               }
189            }
190        });
191
192        return workspaceItems;
193    }
194
195    /**
196     * Adds an item to the DB if it was not created previously, or move it to a new
197     * <container, screen, cellX, cellY>
198     */
199    static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
200            int screen, int cellX, int cellY) {
201        if (item.container == ItemInfo.NO_ID) {
202            // From all apps
203            addItemToDatabase(context, item, container, screen, cellX, cellY, false);
204        } else {
205            // From somewhere else
206            moveItemInDatabase(context, item, container, screen, cellX, cellY);
207        }
208    }
209
210    static void updateItemInDatabaseHelper(Context context, final ContentValues values,
211            final ItemInfo item, final String callingFunction) {
212        final long itemId = item.id;
213        final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
214        final ContentResolver cr = context.getContentResolver();
215
216        Runnable r = new Runnable() {
217            public void run() {
218                cr.update(uri, values, null, null);
219
220                ItemInfo modelItem = sItemsIdMap.get(itemId);
221                if (item != modelItem) {
222                    // the modelItem needs to match up perfectly with item if our model is to be
223                    // consistent with the database-- for now, just require modelItem == item
224                    String msg = "item: " + ((item != null) ? item.toString() : "null") +
225                        "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
226                        "Error: ItemInfo passed to " + callingFunction + " doesn't match original";
227                    throw new RuntimeException(msg);
228                }
229
230                // Items are added/removed from the corresponding FolderInfo elsewhere, such
231                // as in Workspace.onDrop. Here, we just add/remove them from the list of items
232                // that are on the desktop, as appropriate
233                if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
234                        modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
235                    if (!sWorkspaceItems.contains(modelItem)) {
236                        sWorkspaceItems.add(modelItem);
237                    }
238                } else {
239                    sWorkspaceItems.remove(modelItem);
240                }
241            }
242        };
243
244        if (sWorkerThread.getThreadId() == Process.myTid()) {
245            r.run();
246        } else {
247            sWorker.post(r);
248        }
249    }
250    /**
251     * Move an item in the DB to a new <container, screen, cellX, cellY>
252     */
253    static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
254            final int screen, final int cellX, final int cellY) {
255        item.container = container;
256        item.cellX = cellX;
257        item.cellY = cellY;
258
259        // We store hotseat items in canonical form which is this orientation invariant position
260        // in the hotseat
261        if (context instanceof Launcher && screen < 0 &&
262                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
263            item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
264        } else {
265            item.screen = screen;
266        }
267
268        final ContentValues values = new ContentValues();
269        values.put(LauncherSettings.Favorites.CONTAINER, item.container);
270        values.put(LauncherSettings.Favorites.CELLX, item.cellX);
271        values.put(LauncherSettings.Favorites.CELLY, item.cellY);
272        values.put(LauncherSettings.Favorites.SCREEN, item.screen);
273
274        updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
275    }
276
277    /**
278     * Resize an item in the DB to a new <spanX, spanY, cellX, cellY>
279     */
280    static void resizeItemInDatabase(Context context, final ItemInfo item, final int cellX,
281            final int cellY, final int spanX, final int spanY) {
282        item.spanX = spanX;
283        item.spanY = spanY;
284        item.cellX = cellX;
285        item.cellY = cellY;
286
287        final ContentValues values = new ContentValues();
288        values.put(LauncherSettings.Favorites.CONTAINER, item.container);
289        values.put(LauncherSettings.Favorites.SPANX, spanX);
290        values.put(LauncherSettings.Favorites.SPANY, spanY);
291        values.put(LauncherSettings.Favorites.CELLX, cellX);
292        values.put(LauncherSettings.Favorites.CELLY, cellY);
293        updateItemInDatabaseHelper(context, values, item, "resizeItemInDatabase");
294    }
295
296
297    /**
298     * Update an item to the database in a specified container.
299     */
300    static void updateItemInDatabase(Context context, final ItemInfo item) {
301        final ContentValues values = new ContentValues();
302        item.onAddToDatabase(values);
303        item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
304        updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
305    }
306
307    /**
308     * Returns true if the shortcuts already exists in the database.
309     * we identify a shortcut by its title and intent.
310     */
311    static boolean shortcutExists(Context context, String title, Intent intent) {
312        final ContentResolver cr = context.getContentResolver();
313        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
314            new String[] { "title", "intent" }, "title=? and intent=?",
315            new String[] { title, intent.toUri(0) }, null);
316        boolean result = false;
317        try {
318            result = c.moveToFirst();
319        } finally {
320            c.close();
321        }
322        return result;
323    }
324
325    /**
326     * Returns an ItemInfo array containing all the items in the LauncherModel.
327     * The ItemInfo.id is not set through this function.
328     */
329    static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
330        ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
331        final ContentResolver cr = context.getContentResolver();
332        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
333                LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
334                LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
335                LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
336
337        final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
338        final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
339        final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
340        final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
341        final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
342        final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
343        final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
344
345        try {
346            while (c.moveToNext()) {
347                ItemInfo item = new ItemInfo();
348                item.cellX = c.getInt(cellXIndex);
349                item.cellY = c.getInt(cellYIndex);
350                item.spanX = c.getInt(spanXIndex);
351                item.spanY = c.getInt(spanYIndex);
352                item.container = c.getInt(containerIndex);
353                item.itemType = c.getInt(itemTypeIndex);
354                item.screen = c.getInt(screenIndex);
355
356                items.add(item);
357            }
358        } catch (Exception e) {
359            items.clear();
360        } finally {
361            c.close();
362        }
363
364        return items;
365    }
366
367    /**
368     * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
369     */
370    FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
371        final ContentResolver cr = context.getContentResolver();
372        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
373                "_id=? and (itemType=? or itemType=?)",
374                new String[] { String.valueOf(id),
375                        String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
376
377        try {
378            if (c.moveToFirst()) {
379                final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
380                final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
381                final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
382                final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
383                final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
384                final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
385
386                FolderInfo folderInfo = null;
387                switch (c.getInt(itemTypeIndex)) {
388                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
389                        folderInfo = findOrMakeFolder(folderList, id);
390                        break;
391                }
392
393                folderInfo.title = c.getString(titleIndex);
394                folderInfo.id = id;
395                folderInfo.container = c.getInt(containerIndex);
396                folderInfo.screen = c.getInt(screenIndex);
397                folderInfo.cellX = c.getInt(cellXIndex);
398                folderInfo.cellY = c.getInt(cellYIndex);
399
400                return folderInfo;
401            }
402        } finally {
403            c.close();
404        }
405
406        return null;
407    }
408
409    /**
410     * Add an item to the database in a specified container. Sets the container, screen, cellX and
411     * cellY fields of the item. Also assigns an ID to the item.
412     */
413    static void addItemToDatabase(Context context, final ItemInfo item, final long container,
414            final int screen, final int cellX, final int cellY, final boolean notify) {
415        item.container = container;
416        item.cellX = cellX;
417        item.cellY = cellY;
418        // We store hotseat items in canonical form which is this orientation invariant position
419        // in the hotseat
420        if (context instanceof Launcher && screen < 0 &&
421                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
422            item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
423        } else {
424            item.screen = screen;
425        }
426
427        final ContentValues values = new ContentValues();
428        final ContentResolver cr = context.getContentResolver();
429        item.onAddToDatabase(values);
430
431        LauncherApplication app = (LauncherApplication) context.getApplicationContext();
432        item.id = app.getLauncherProvider().generateNewId();
433        values.put(LauncherSettings.Favorites._ID, item.id);
434        item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
435
436        Runnable r = new Runnable() {
437            public void run() {
438                cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
439                        LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
440
441                if (sItemsIdMap.containsKey(item.id)) {
442                    // we should not be adding new items in the db with the same id
443                    throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
444                        "addItemToDatabase already exists." + item.toString());
445                }
446                sItemsIdMap.put(item.id, item);
447                switch (item.itemType) {
448                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
449                        sFolders.put(item.id, (FolderInfo) item);
450                        // Fall through
451                    case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
452                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
453                        if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
454                                item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
455                            sWorkspaceItems.add(item);
456                        }
457                        break;
458                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
459                        sAppWidgets.add((LauncherAppWidgetInfo) item);
460                        break;
461                }
462            }
463        };
464
465        if (sWorkerThread.getThreadId() == Process.myTid()) {
466            r.run();
467        } else {
468            sWorker.post(r);
469        }
470    }
471
472    /**
473     * Creates a new unique child id, for a given cell span across all layouts.
474     */
475    static int getCellLayoutChildId(
476            long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
477        return (((int) container & 0xFF) << 24)
478                | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
479    }
480
481    static int getCellCountX() {
482        return mCellCountX;
483    }
484
485    static int getCellCountY() {
486        return mCellCountY;
487    }
488
489    /**
490     * Updates the model orientation helper to take into account the current layout dimensions
491     * when performing local/canonical coordinate transformations.
492     */
493    static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
494        mCellCountX = shortAxisCellCount;
495        mCellCountY = longAxisCellCount;
496    }
497
498    /**
499     * Removes the specified item from the database
500     * @param context
501     * @param item
502     */
503    static void deleteItemFromDatabase(Context context, final ItemInfo item) {
504        final ContentResolver cr = context.getContentResolver();
505        final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
506        Runnable r = new Runnable() {
507            public void run() {
508                cr.delete(uriToDelete, null, null);
509                switch (item.itemType) {
510                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
511                        sFolders.remove(item.id);
512                        sWorkspaceItems.remove(item);
513                        break;
514                    case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
515                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
516                        sWorkspaceItems.remove(item);
517                        break;
518                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
519                        sAppWidgets.remove((LauncherAppWidgetInfo) item);
520                        break;
521                }
522                sItemsIdMap.remove(item.id);
523                sDbIconCache.remove(item);
524            }
525        };
526        if (sWorkerThread.getThreadId() == Process.myTid()) {
527            r.run();
528        } else {
529            sWorker.post(r);
530        }
531    }
532
533    /**
534     * Remove the contents of the specified folder from the database
535     */
536    static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
537        final ContentResolver cr = context.getContentResolver();
538
539        Runnable r = new Runnable() {
540            public void run() {
541                cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
542                sItemsIdMap.remove(info.id);
543                sFolders.remove(info.id);
544                sDbIconCache.remove(info);
545                sWorkspaceItems.remove(info);
546
547                cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
548                        LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
549                for (ItemInfo childInfo : info.contents) {
550                    sItemsIdMap.remove(childInfo.id);
551                    sDbIconCache.remove(childInfo);
552                }
553            }
554        };
555        if (sWorkerThread.getThreadId() == Process.myTid()) {
556            r.run();
557        } else {
558            sWorker.post(r);
559        }
560    }
561
562    /**
563     * Set this as the current Launcher activity object for the loader.
564     */
565    public void initialize(Callbacks callbacks) {
566        synchronized (mLock) {
567            mCallbacks = new WeakReference<Callbacks>(callbacks);
568        }
569    }
570
571    /**
572     * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
573     * ACTION_PACKAGE_CHANGED.
574     */
575    @Override
576    public void onReceive(Context context, Intent intent) {
577        if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
578
579        final String action = intent.getAction();
580
581        if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
582                || Intent.ACTION_PACKAGE_REMOVED.equals(action)
583                || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
584            final String packageName = intent.getData().getSchemeSpecificPart();
585            final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
586
587            int op = PackageUpdatedTask.OP_NONE;
588
589            if (packageName == null || packageName.length() == 0) {
590                // they sent us a bad intent
591                return;
592            }
593
594            if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
595                op = PackageUpdatedTask.OP_UPDATE;
596            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
597                if (!replacing) {
598                    op = PackageUpdatedTask.OP_REMOVE;
599                }
600                // else, we are replacing the package, so a PACKAGE_ADDED will be sent
601                // later, we will update the package at this time
602            } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
603                if (!replacing) {
604                    op = PackageUpdatedTask.OP_ADD;
605                } else {
606                    op = PackageUpdatedTask.OP_UPDATE;
607                }
608            }
609
610            if (op != PackageUpdatedTask.OP_NONE) {
611                enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
612            }
613
614        } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
615            // First, schedule to add these apps back in.
616            String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
617            enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
618            // Then, rebind everything.
619            startLoaderFromBackground();
620        } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
621            String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
622            enqueuePackageUpdated(new PackageUpdatedTask(
623                        PackageUpdatedTask.OP_UNAVAILABLE, packages));
624        } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
625            // If we have changed locale we need to clear out the labels in all apps/workspace.
626            forceReload();
627        } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
628             // Check if configuration change was an mcc/mnc change which would affect app resources
629             // and we would need to clear out the labels in all apps/workspace. Same handling as
630             // above for ACTION_LOCALE_CHANGED
631             Configuration currentConfig = context.getResources().getConfiguration();
632             if (mPreviousConfigMcc != currentConfig.mcc) {
633                   Log.d(TAG, "Reload apps on config change. curr_mcc:"
634                       + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
635                   forceReload();
636             }
637             // Update previousConfig
638             mPreviousConfigMcc = currentConfig.mcc;
639        } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
640                   SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
641            if (mCallbacks != null) {
642                Callbacks callbacks = mCallbacks.get();
643                if (callbacks != null) {
644                    callbacks.bindSearchablesChanged();
645                }
646            }
647        }
648    }
649
650    private void forceReload() {
651        synchronized (mLock) {
652            // Stop any existing loaders first, so they don't set mAllAppsLoaded or
653            // mWorkspaceLoaded to true later
654            stopLoaderLocked();
655            mAllAppsLoaded = false;
656            mWorkspaceLoaded = false;
657        }
658        // Do this here because if the launcher activity is running it will be restarted.
659        // If it's not running startLoaderFromBackground will merely tell it that it needs
660        // to reload.
661        startLoaderFromBackground();
662    }
663
664    /**
665     * When the launcher is in the background, it's possible for it to miss paired
666     * configuration changes.  So whenever we trigger the loader from the background
667     * tell the launcher that it needs to re-run the loader when it comes back instead
668     * of doing it now.
669     */
670    public void startLoaderFromBackground() {
671        boolean runLoader = false;
672        if (mCallbacks != null) {
673            Callbacks callbacks = mCallbacks.get();
674            if (callbacks != null) {
675                // Only actually run the loader if they're not paused.
676                if (!callbacks.setLoadOnResume()) {
677                    runLoader = true;
678                }
679            }
680        }
681        if (runLoader) {
682            startLoader(mApp, false);
683        }
684    }
685
686    // If there is already a loader task running, tell it to stop.
687    // returns true if isLaunching() was true on the old task
688    private boolean stopLoaderLocked() {
689        boolean isLaunching = false;
690        LoaderTask oldTask = mLoaderTask;
691        if (oldTask != null) {
692            if (oldTask.isLaunching()) {
693                isLaunching = true;
694            }
695            oldTask.stopLocked();
696        }
697        return isLaunching;
698    }
699
700    public void startLoader(Context context, boolean isLaunching) {
701        synchronized (mLock) {
702            if (DEBUG_LOADERS) {
703                Log.d(TAG, "startLoader isLaunching=" + isLaunching);
704            }
705
706            // Don't bother to start the thread if we know it's not going to do anything
707            if (mCallbacks != null && mCallbacks.get() != null) {
708                // If there is already one running, tell it to stop.
709                // also, don't downgrade isLaunching if we're already running
710                isLaunching = isLaunching || stopLoaderLocked();
711                mLoaderTask = new LoaderTask(context, isLaunching);
712                sWorkerThread.setPriority(Thread.NORM_PRIORITY);
713                sWorker.post(mLoaderTask);
714            }
715        }
716    }
717
718    public void stopLoader() {
719        synchronized (mLock) {
720            if (mLoaderTask != null) {
721                mLoaderTask.stopLocked();
722            }
723        }
724    }
725
726    public boolean isAllAppsLoaded() {
727        return mAllAppsLoaded;
728    }
729
730    /**
731     * Runnable for the thread that loads the contents of the launcher:
732     *   - workspace icons
733     *   - widgets
734     *   - all apps icons
735     */
736    private class LoaderTask implements Runnable {
737        private Context mContext;
738        private Thread mWaitThread;
739        private boolean mIsLaunching;
740        private boolean mStopped;
741        private boolean mLoadAndBindStepFinished;
742        private HashMap<Object, CharSequence> mLabelCache;
743
744        LoaderTask(Context context, boolean isLaunching) {
745            mContext = context;
746            mIsLaunching = isLaunching;
747            mLabelCache = new HashMap<Object, CharSequence>();
748        }
749
750        boolean isLaunching() {
751            return mIsLaunching;
752        }
753
754        private void loadAndBindWorkspace() {
755            // Load the workspace
756            if (DEBUG_LOADERS) {
757                Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
758            }
759
760            if (!mWorkspaceLoaded) {
761                loadWorkspace();
762                synchronized (LoaderTask.this) {
763                    if (mStopped) {
764                        return;
765                    }
766                    mWorkspaceLoaded = true;
767                }
768            }
769
770            // Bind the workspace
771            bindWorkspace();
772        }
773
774        private void waitForIdle() {
775            // Wait until the either we're stopped or the other threads are done.
776            // This way we don't start loading all apps until the workspace has settled
777            // down.
778            synchronized (LoaderTask.this) {
779                final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
780
781                mHandler.postIdle(new Runnable() {
782                        public void run() {
783                            synchronized (LoaderTask.this) {
784                                mLoadAndBindStepFinished = true;
785                                if (DEBUG_LOADERS) {
786                                    Log.d(TAG, "done with previous binding step");
787                                }
788                                LoaderTask.this.notify();
789                            }
790                        }
791                    });
792
793                while (!mStopped && !mLoadAndBindStepFinished) {
794                    try {
795                        this.wait();
796                    } catch (InterruptedException ex) {
797                        // Ignore
798                    }
799                }
800                if (DEBUG_LOADERS) {
801                    Log.d(TAG, "waited "
802                            + (SystemClock.uptimeMillis()-workspaceWaitTime)
803                            + "ms for previous step to finish binding");
804                }
805            }
806        }
807
808        public void run() {
809            // Optimize for end-user experience: if the Launcher is up and // running with the
810            // All Apps interface in the foreground, load All Apps first. Otherwise, load the
811            // workspace first (default).
812            final Callbacks cbk = mCallbacks.get();
813            final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
814
815            keep_running: {
816                // Elevate priority when Home launches for the first time to avoid
817                // starving at boot time. Staring at a blank home is not cool.
818                synchronized (mLock) {
819                    if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
820                            (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
821                    android.os.Process.setThreadPriority(mIsLaunching
822                            ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
823                }
824                if (loadWorkspaceFirst) {
825                    if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
826                    loadAndBindWorkspace();
827                } else {
828                    if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
829                    loadAndBindAllApps();
830                }
831
832                if (mStopped) {
833                    break keep_running;
834                }
835
836                // Whew! Hard work done.  Slow us down, and wait until the UI thread has
837                // settled down.
838                synchronized (mLock) {
839                    if (mIsLaunching) {
840                        if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
841                        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
842                    }
843                }
844                waitForIdle();
845
846                // second step
847                if (loadWorkspaceFirst) {
848                    if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
849                    loadAndBindAllApps();
850                } else {
851                    if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
852                    loadAndBindWorkspace();
853                }
854
855                // Restore the default thread priority after we are done loading items
856                synchronized (mLock) {
857                    android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
858                }
859            }
860
861
862            // Update the saved icons if necessary
863            if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
864            for (Object key : sDbIconCache.keySet()) {
865                updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
866            }
867            sDbIconCache.clear();
868
869            // Clear out this reference, otherwise we end up holding it until all of the
870            // callback runnables are done.
871            mContext = null;
872
873            synchronized (mLock) {
874                // If we are still the last one to be scheduled, remove ourselves.
875                if (mLoaderTask == this) {
876                    mLoaderTask = null;
877                }
878            }
879        }
880
881        public void stopLocked() {
882            synchronized (LoaderTask.this) {
883                mStopped = true;
884                this.notify();
885            }
886        }
887
888        /**
889         * Gets the callbacks object.  If we've been stopped, or if the launcher object
890         * has somehow been garbage collected, return null instead.  Pass in the Callbacks
891         * object that was around when the deferred message was scheduled, and if there's
892         * a new Callbacks object around then also return null.  This will save us from
893         * calling onto it with data that will be ignored.
894         */
895        Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
896            synchronized (mLock) {
897                if (mStopped) {
898                    return null;
899                }
900
901                if (mCallbacks == null) {
902                    return null;
903                }
904
905                final Callbacks callbacks = mCallbacks.get();
906                if (callbacks != oldCallbacks) {
907                    return null;
908                }
909                if (callbacks == null) {
910                    Log.w(TAG, "no mCallbacks");
911                    return null;
912                }
913
914                return callbacks;
915            }
916        }
917
918        // check & update map of what's occupied; used to discard overlapping/invalid items
919        private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
920            int containerIndex = item.screen;
921            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
922                // Return early if we detect that an item is under the hotseat button
923                if (Hotseat.isAllAppsButtonRank(item.screen)) {
924                    return false;
925                }
926
927                // We use the last index to refer to the hotseat and the screen as the rank, so
928                // test and update the occupied state accordingly
929                if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
930                    Log.e(TAG, "Error loading shortcut into hotseat " + item
931                        + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
932                        + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
933                    return false;
934                } else {
935                    occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
936                    return true;
937                }
938            } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
939                // Skip further checking if it is not the hotseat or workspace container
940                return true;
941            }
942
943            // Check if any workspace icons overlap with each other
944            for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
945                for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
946                    if (occupied[containerIndex][x][y] != null) {
947                        Log.e(TAG, "Error loading shortcut " + item
948                            + " into cell (" + containerIndex + "-" + item.screen + ":"
949                            + x + "," + y
950                            + ") occupied by "
951                            + occupied[containerIndex][x][y]);
952                        return false;
953                    }
954                }
955            }
956            for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
957                for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
958                    occupied[containerIndex][x][y] = item;
959                }
960            }
961
962            return true;
963        }
964
965        private void loadWorkspace() {
966            final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
967
968            final Context context = mContext;
969            final ContentResolver contentResolver = context.getContentResolver();
970            final PackageManager manager = context.getPackageManager();
971            final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
972            final boolean isSafeMode = manager.isSafeMode();
973
974            sWorkspaceItems.clear();
975            sAppWidgets.clear();
976            sFolders.clear();
977            sItemsIdMap.clear();
978            sDbIconCache.clear();
979
980            final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
981
982            final Cursor c = contentResolver.query(
983                    LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
984
985            // +1 for the hotseat (it can be larger than the workspace)
986            // Load workspace in reverse order to ensure that latest items are loaded first (and
987            // before any earlier duplicates)
988            final ItemInfo occupied[][][] =
989                    new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
990
991            try {
992                final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
993                final int intentIndex = c.getColumnIndexOrThrow
994                        (LauncherSettings.Favorites.INTENT);
995                final int titleIndex = c.getColumnIndexOrThrow
996                        (LauncherSettings.Favorites.TITLE);
997                final int iconTypeIndex = c.getColumnIndexOrThrow(
998                        LauncherSettings.Favorites.ICON_TYPE);
999                final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1000                final int iconPackageIndex = c.getColumnIndexOrThrow(
1001                        LauncherSettings.Favorites.ICON_PACKAGE);
1002                final int iconResourceIndex = c.getColumnIndexOrThrow(
1003                        LauncherSettings.Favorites.ICON_RESOURCE);
1004                final int containerIndex = c.getColumnIndexOrThrow(
1005                        LauncherSettings.Favorites.CONTAINER);
1006                final int itemTypeIndex = c.getColumnIndexOrThrow(
1007                        LauncherSettings.Favorites.ITEM_TYPE);
1008                final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1009                        LauncherSettings.Favorites.APPWIDGET_ID);
1010                final int screenIndex = c.getColumnIndexOrThrow(
1011                        LauncherSettings.Favorites.SCREEN);
1012                final int cellXIndex = c.getColumnIndexOrThrow
1013                        (LauncherSettings.Favorites.CELLX);
1014                final int cellYIndex = c.getColumnIndexOrThrow
1015                        (LauncherSettings.Favorites.CELLY);
1016                final int spanXIndex = c.getColumnIndexOrThrow
1017                        (LauncherSettings.Favorites.SPANX);
1018                final int spanYIndex = c.getColumnIndexOrThrow(
1019                        LauncherSettings.Favorites.SPANY);
1020                final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1021                final int displayModeIndex = c.getColumnIndexOrThrow(
1022                        LauncherSettings.Favorites.DISPLAY_MODE);
1023
1024                ShortcutInfo info;
1025                String intentDescription;
1026                LauncherAppWidgetInfo appWidgetInfo;
1027                int container;
1028                long id;
1029                Intent intent;
1030
1031                while (!mStopped && c.moveToNext()) {
1032                    try {
1033                        int itemType = c.getInt(itemTypeIndex);
1034
1035                        switch (itemType) {
1036                        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1037                        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1038                            intentDescription = c.getString(intentIndex);
1039                            try {
1040                                intent = Intent.parseUri(intentDescription, 0);
1041                            } catch (URISyntaxException e) {
1042                                continue;
1043                            }
1044
1045                            if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1046                                info = getShortcutInfo(manager, intent, context, c, iconIndex,
1047                                        titleIndex, mLabelCache);
1048                            } else {
1049                                info = getShortcutInfo(c, context, iconTypeIndex,
1050                                        iconPackageIndex, iconResourceIndex, iconIndex,
1051                                        titleIndex);
1052                            }
1053
1054                            if (info != null) {
1055                                info.intent = intent;
1056                                info.id = c.getLong(idIndex);
1057                                container = c.getInt(containerIndex);
1058                                info.container = container;
1059                                info.screen = c.getInt(screenIndex);
1060                                info.cellX = c.getInt(cellXIndex);
1061                                info.cellY = c.getInt(cellYIndex);
1062
1063                                // check & update map of what's occupied
1064                                if (!checkItemPlacement(occupied, info)) {
1065                                    break;
1066                                }
1067
1068                                switch (container) {
1069                                case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1070                                case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1071                                    sWorkspaceItems.add(info);
1072                                    break;
1073                                default:
1074                                    // Item is in a user folder
1075                                    FolderInfo folderInfo =
1076                                            findOrMakeFolder(sFolders, container);
1077                                    folderInfo.add(info);
1078                                    break;
1079                                }
1080                                sItemsIdMap.put(info.id, info);
1081
1082                                // now that we've loaded everthing re-save it with the
1083                                // icon in case it disappears somehow.
1084                                queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
1085                            } else {
1086                                // Failed to load the shortcut, probably because the
1087                                // activity manager couldn't resolve it (maybe the app
1088                                // was uninstalled), or the db row was somehow screwed up.
1089                                // Delete it.
1090                                id = c.getLong(idIndex);
1091                                Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1092                                contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1093                                            id, false), null, null);
1094                            }
1095                            break;
1096
1097                        case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1098                            id = c.getLong(idIndex);
1099                            FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
1100
1101                            folderInfo.title = c.getString(titleIndex);
1102                            folderInfo.id = id;
1103                            container = c.getInt(containerIndex);
1104                            folderInfo.container = container;
1105                            folderInfo.screen = c.getInt(screenIndex);
1106                            folderInfo.cellX = c.getInt(cellXIndex);
1107                            folderInfo.cellY = c.getInt(cellYIndex);
1108
1109                            // check & update map of what's occupied
1110                            if (!checkItemPlacement(occupied, folderInfo)) {
1111                                break;
1112                            }
1113                            switch (container) {
1114                                case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1115                                case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1116                                    sWorkspaceItems.add(folderInfo);
1117                                    break;
1118                            }
1119
1120                            sItemsIdMap.put(folderInfo.id, folderInfo);
1121                            sFolders.put(folderInfo.id, folderInfo);
1122                            break;
1123
1124                        case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1125                            // Read all Launcher-specific widget details
1126                            int appWidgetId = c.getInt(appWidgetIdIndex);
1127                            id = c.getLong(idIndex);
1128
1129                            final AppWidgetProviderInfo provider =
1130                                    widgets.getAppWidgetInfo(appWidgetId);
1131
1132                            if (!isSafeMode && (provider == null || provider.provider == null ||
1133                                    provider.provider.getPackageName() == null)) {
1134                                String log = "Deleting widget that isn't installed anymore: id="
1135                                    + id + " appWidgetId=" + appWidgetId;
1136                                Log.e(TAG, log);
1137                                Launcher.sDumpLogs.add(log);
1138                                itemsToRemove.add(id);
1139                            } else {
1140                                appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
1141                                appWidgetInfo.id = id;
1142                                appWidgetInfo.screen = c.getInt(screenIndex);
1143                                appWidgetInfo.cellX = c.getInt(cellXIndex);
1144                                appWidgetInfo.cellY = c.getInt(cellYIndex);
1145                                appWidgetInfo.spanX = c.getInt(spanXIndex);
1146                                appWidgetInfo.spanY = c.getInt(spanYIndex);
1147
1148                                container = c.getInt(containerIndex);
1149                                if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1150                                    container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1151                                    Log.e(TAG, "Widget found where container "
1152                                        + "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1153                                    continue;
1154                                }
1155                                appWidgetInfo.container = c.getInt(containerIndex);
1156
1157                                // check & update map of what's occupied
1158                                if (!checkItemPlacement(occupied, appWidgetInfo)) {
1159                                    break;
1160                                }
1161                                sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1162                                sAppWidgets.add(appWidgetInfo);
1163                            }
1164                            break;
1165                        }
1166                    } catch (Exception e) {
1167                        Log.w(TAG, "Desktop items loading interrupted:", e);
1168                    }
1169                }
1170            } finally {
1171                c.close();
1172            }
1173
1174            if (itemsToRemove.size() > 0) {
1175                ContentProviderClient client = contentResolver.acquireContentProviderClient(
1176                                LauncherSettings.Favorites.CONTENT_URI);
1177                // Remove dead items
1178                for (long id : itemsToRemove) {
1179                    if (DEBUG_LOADERS) {
1180                        Log.d(TAG, "Removed id = " + id);
1181                    }
1182                    // Don't notify content observers
1183                    try {
1184                        client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1185                                null, null);
1186                    } catch (RemoteException e) {
1187                        Log.w(TAG, "Could not remove id = " + id);
1188                    }
1189                }
1190            }
1191
1192            if (DEBUG_LOADERS) {
1193                Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1194                Log.d(TAG, "workspace layout: ");
1195                for (int y = 0; y < mCellCountY; y++) {
1196                    String line = "";
1197                    for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
1198                        if (s > 0) {
1199                            line += " | ";
1200                        }
1201                        for (int x = 0; x < mCellCountX; x++) {
1202                            line += ((occupied[s][x][y] != null) ? "#" : ".");
1203                        }
1204                    }
1205                    Log.d(TAG, "[ " + line + " ]");
1206                }
1207            }
1208        }
1209
1210        /**
1211         * Read everything out of our database.
1212         */
1213        private void bindWorkspace() {
1214            final long t = SystemClock.uptimeMillis();
1215
1216            // Don't use these two variables in any of the callback runnables.
1217            // Otherwise we hold a reference to them.
1218            final Callbacks oldCallbacks = mCallbacks.get();
1219            if (oldCallbacks == null) {
1220                // This launcher has exited and nobody bothered to tell us.  Just bail.
1221                Log.w(TAG, "LoaderTask running with no launcher");
1222                return;
1223            }
1224
1225            int N;
1226            // Tell the workspace that we're about to start firing items at it
1227            mHandler.post(new Runnable() {
1228                public void run() {
1229                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1230                    if (callbacks != null) {
1231                        callbacks.startBinding();
1232                    }
1233                }
1234            });
1235
1236            final ArrayList<ItemInfo> workspaceItems = unbindWorkspaceItemsOnMainThread();
1237
1238            // Add the items to the workspace.
1239            N = workspaceItems.size();
1240            for (int i=0; i<N; i+=ITEMS_CHUNK) {
1241                final int start = i;
1242                final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
1243                mHandler.post(new Runnable() {
1244                    public void run() {
1245                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1246                        if (callbacks != null) {
1247                            callbacks.bindItems(workspaceItems, start, start+chunkSize);
1248                        }
1249                    }
1250                });
1251            }
1252            // Ensure that we don't use the same folders data structure on the main thread
1253            final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders);
1254            mHandler.post(new Runnable() {
1255                public void run() {
1256                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1257                    if (callbacks != null) {
1258                        callbacks.bindFolders(folders);
1259                    }
1260                }
1261            });
1262            // Wait until the queue goes empty.
1263            mHandler.post(new Runnable() {
1264                public void run() {
1265                    if (DEBUG_LOADERS) {
1266                        Log.d(TAG, "Going to start binding widgets soon.");
1267                    }
1268                }
1269            });
1270            // Bind the widgets, one at a time.
1271            // WARNING: this is calling into the workspace from the background thread,
1272            // but since getCurrentScreen() just returns the int, we should be okay.  This
1273            // is just a hint for the order, and if it's wrong, we'll be okay.
1274            // TODO: instead, we should have that push the current screen into here.
1275            final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
1276            N = sAppWidgets.size();
1277            // once for the current screen
1278            for (int i=0; i<N; i++) {
1279                final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
1280                if (widget.screen == currentScreen) {
1281                    mHandler.post(new Runnable() {
1282                        public void run() {
1283                            Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1284                            if (callbacks != null) {
1285                                callbacks.bindAppWidget(widget);
1286                            }
1287                        }
1288                    });
1289                }
1290            }
1291            // once for the other screens
1292            for (int i=0; i<N; i++) {
1293                final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
1294                if (widget.screen != currentScreen) {
1295                    mHandler.post(new Runnable() {
1296                        public void run() {
1297                            Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1298                            if (callbacks != null) {
1299                                callbacks.bindAppWidget(widget);
1300                            }
1301                        }
1302                    });
1303                }
1304            }
1305            // Tell the workspace that we're done.
1306            mHandler.post(new Runnable() {
1307                public void run() {
1308                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1309                    if (callbacks != null) {
1310                        callbacks.finishBindingItems();
1311                    }
1312                }
1313            });
1314            // If we're profiling, this is the last thing in the queue.
1315            mHandler.post(new Runnable() {
1316                public void run() {
1317                    if (DEBUG_LOADERS) {
1318                        Log.d(TAG, "bound workspace in "
1319                            + (SystemClock.uptimeMillis()-t) + "ms");
1320                    }
1321                }
1322            });
1323        }
1324
1325        private void loadAndBindAllApps() {
1326            if (DEBUG_LOADERS) {
1327                Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
1328            }
1329            if (!mAllAppsLoaded) {
1330                loadAllAppsByBatch();
1331                synchronized (LoaderTask.this) {
1332                    if (mStopped) {
1333                        return;
1334                    }
1335                    mAllAppsLoaded = true;
1336                }
1337            } else {
1338                onlyBindAllApps();
1339            }
1340        }
1341
1342        private void onlyBindAllApps() {
1343            final Callbacks oldCallbacks = mCallbacks.get();
1344            if (oldCallbacks == null) {
1345                // This launcher has exited and nobody bothered to tell us.  Just bail.
1346                Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1347                return;
1348            }
1349
1350            // shallow copy
1351            final ArrayList<ApplicationInfo> list
1352                    = (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
1353            mHandler.post(new Runnable() {
1354                public void run() {
1355                    final long t = SystemClock.uptimeMillis();
1356                    final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1357                    if (callbacks != null) {
1358                        callbacks.bindAllApplications(list);
1359                    }
1360                    if (DEBUG_LOADERS) {
1361                        Log.d(TAG, "bound all " + list.size() + " apps from cache in "
1362                                + (SystemClock.uptimeMillis()-t) + "ms");
1363                    }
1364                }
1365            });
1366
1367        }
1368
1369        private void loadAllAppsByBatch() {
1370            final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1371
1372            // Don't use these two variables in any of the callback runnables.
1373            // Otherwise we hold a reference to them.
1374            final Callbacks oldCallbacks = mCallbacks.get();
1375            if (oldCallbacks == null) {
1376                // This launcher has exited and nobody bothered to tell us.  Just bail.
1377                Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
1378                return;
1379            }
1380
1381            final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1382            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1383
1384            final PackageManager packageManager = mContext.getPackageManager();
1385            List<ResolveInfo> apps = null;
1386
1387            int N = Integer.MAX_VALUE;
1388
1389            int startIndex;
1390            int i=0;
1391            int batchSize = -1;
1392            while (i < N && !mStopped) {
1393                if (i == 0) {
1394                    mAllAppsList.clear();
1395                    final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1396                    apps = packageManager.queryIntentActivities(mainIntent, 0);
1397                    if (DEBUG_LOADERS) {
1398                        Log.d(TAG, "queryIntentActivities took "
1399                                + (SystemClock.uptimeMillis()-qiaTime) + "ms");
1400                    }
1401                    if (apps == null) {
1402                        return;
1403                    }
1404                    N = apps.size();
1405                    if (DEBUG_LOADERS) {
1406                        Log.d(TAG, "queryIntentActivities got " + N + " apps");
1407                    }
1408                    if (N == 0) {
1409                        // There are no apps?!?
1410                        return;
1411                    }
1412                    if (mBatchSize == 0) {
1413                        batchSize = N;
1414                    } else {
1415                        batchSize = mBatchSize;
1416                    }
1417
1418                    final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1419                    Collections.sort(apps,
1420                            new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
1421                    if (DEBUG_LOADERS) {
1422                        Log.d(TAG, "sort took "
1423                                + (SystemClock.uptimeMillis()-sortTime) + "ms");
1424                    }
1425                }
1426
1427                final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1428
1429                startIndex = i;
1430                for (int j=0; i<N && j<batchSize; j++) {
1431                    // This builds the icon bitmaps.
1432                    mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
1433                            mIconCache, mLabelCache));
1434                    i++;
1435                }
1436
1437                final boolean first = i <= batchSize;
1438                final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1439                final ArrayList<ApplicationInfo> added = mAllAppsList.added;
1440                mAllAppsList.added = new ArrayList<ApplicationInfo>();
1441
1442                mHandler.post(new Runnable() {
1443                    public void run() {
1444                        final long t = SystemClock.uptimeMillis();
1445                        if (callbacks != null) {
1446                            if (first) {
1447                                callbacks.bindAllApplications(added);
1448                            } else {
1449                                callbacks.bindAppsAdded(added);
1450                            }
1451                            if (DEBUG_LOADERS) {
1452                                Log.d(TAG, "bound " + added.size() + " apps in "
1453                                    + (SystemClock.uptimeMillis() - t) + "ms");
1454                            }
1455                        } else {
1456                            Log.i(TAG, "not binding apps: no Launcher activity");
1457                        }
1458                    }
1459                });
1460
1461                if (DEBUG_LOADERS) {
1462                    Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
1463                            + (SystemClock.uptimeMillis()-t2) + "ms");
1464                }
1465
1466                if (mAllAppsLoadDelay > 0 && i < N) {
1467                    try {
1468                        if (DEBUG_LOADERS) {
1469                            Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
1470                        }
1471                        Thread.sleep(mAllAppsLoadDelay);
1472                    } catch (InterruptedException exc) { }
1473                }
1474            }
1475
1476            if (DEBUG_LOADERS) {
1477                Log.d(TAG, "cached all " + N + " apps in "
1478                        + (SystemClock.uptimeMillis()-t) + "ms"
1479                        + (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
1480            }
1481        }
1482
1483        public void dumpState() {
1484            Log.d(TAG, "mLoaderTask.mContext=" + mContext);
1485            Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
1486            Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
1487            Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
1488            Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
1489            Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
1490        }
1491    }
1492
1493    void enqueuePackageUpdated(PackageUpdatedTask task) {
1494        sWorker.post(task);
1495    }
1496
1497    private class PackageUpdatedTask implements Runnable {
1498        int mOp;
1499        String[] mPackages;
1500
1501        public static final int OP_NONE = 0;
1502        public static final int OP_ADD = 1;
1503        public static final int OP_UPDATE = 2;
1504        public static final int OP_REMOVE = 3; // uninstlled
1505        public static final int OP_UNAVAILABLE = 4; // external media unmounted
1506
1507
1508        public PackageUpdatedTask(int op, String[] packages) {
1509            mOp = op;
1510            mPackages = packages;
1511        }
1512
1513        public void run() {
1514            final Context context = mApp;
1515
1516            final String[] packages = mPackages;
1517            final int N = packages.length;
1518            switch (mOp) {
1519                case OP_ADD:
1520                    for (int i=0; i<N; i++) {
1521                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
1522                        mAllAppsList.addPackage(context, packages[i]);
1523                    }
1524                    break;
1525                case OP_UPDATE:
1526                    for (int i=0; i<N; i++) {
1527                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
1528                        mAllAppsList.updatePackage(context, packages[i]);
1529                    }
1530                    break;
1531                case OP_REMOVE:
1532                case OP_UNAVAILABLE:
1533                    for (int i=0; i<N; i++) {
1534                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
1535                        mAllAppsList.removePackage(packages[i]);
1536                    }
1537                    break;
1538            }
1539
1540            ArrayList<ApplicationInfo> added = null;
1541            ArrayList<ApplicationInfo> removed = null;
1542            ArrayList<ApplicationInfo> modified = null;
1543
1544            if (mAllAppsList.added.size() > 0) {
1545                added = mAllAppsList.added;
1546                mAllAppsList.added = new ArrayList<ApplicationInfo>();
1547            }
1548            if (mAllAppsList.removed.size() > 0) {
1549                removed = mAllAppsList.removed;
1550                mAllAppsList.removed = new ArrayList<ApplicationInfo>();
1551                for (ApplicationInfo info: removed) {
1552                    mIconCache.remove(info.intent.getComponent());
1553                }
1554            }
1555            if (mAllAppsList.modified.size() > 0) {
1556                modified = mAllAppsList.modified;
1557                mAllAppsList.modified = new ArrayList<ApplicationInfo>();
1558            }
1559
1560            final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
1561            if (callbacks == null) {
1562                Log.w(TAG, "Nobody to tell about the new app.  Launcher is probably loading.");
1563                return;
1564            }
1565
1566            if (added != null) {
1567                final ArrayList<ApplicationInfo> addedFinal = added;
1568                mHandler.post(new Runnable() {
1569                    public void run() {
1570                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1571                        if (callbacks == cb && cb != null) {
1572                            callbacks.bindAppsAdded(addedFinal);
1573                        }
1574                    }
1575                });
1576            }
1577            if (modified != null) {
1578                final ArrayList<ApplicationInfo> modifiedFinal = modified;
1579                mHandler.post(new Runnable() {
1580                    public void run() {
1581                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1582                        if (callbacks == cb && cb != null) {
1583                            callbacks.bindAppsUpdated(modifiedFinal);
1584                        }
1585                    }
1586                });
1587            }
1588            if (removed != null) {
1589                final boolean permanent = mOp != OP_UNAVAILABLE;
1590                final ArrayList<ApplicationInfo> removedFinal = removed;
1591                mHandler.post(new Runnable() {
1592                    public void run() {
1593                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1594                        if (callbacks == cb && cb != null) {
1595                            callbacks.bindAppsRemoved(removedFinal, permanent);
1596                        }
1597                    }
1598                });
1599            }
1600
1601            mHandler.post(new Runnable() {
1602                @Override
1603                public void run() {
1604                    Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1605                    if (callbacks == cb && cb != null) {
1606                        callbacks.bindPackagesUpdated();
1607                    }
1608                }
1609            });
1610        }
1611    }
1612
1613    /**
1614     * This is called from the code that adds shortcuts from the intent receiver.  This
1615     * doesn't have a Cursor, but
1616     */
1617    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
1618        return getShortcutInfo(manager, intent, context, null, -1, -1, null);
1619    }
1620
1621    /**
1622     * Make an ShortcutInfo object for a shortcut that is an application.
1623     *
1624     * If c is not null, then it will be used to fill in missing data like the title and icon.
1625     */
1626    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
1627            Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
1628        Bitmap icon = null;
1629        final ShortcutInfo info = new ShortcutInfo();
1630
1631        ComponentName componentName = intent.getComponent();
1632        if (componentName == null) {
1633            return null;
1634        }
1635
1636        try {
1637            PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
1638            if (!pi.applicationInfo.enabled) {
1639                // If we return null here, the corresponding item will be removed from the launcher
1640                // db and will not appear in the workspace.
1641                return null;
1642            }
1643        } catch (NameNotFoundException e) {
1644            Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
1645        }
1646
1647        // TODO: See if the PackageManager knows about this case.  If it doesn't
1648        // then return null & delete this.
1649
1650        // the resource -- This may implicitly give us back the fallback icon,
1651        // but don't worry about that.  All we're doing with usingFallbackIcon is
1652        // to avoid saving lots of copies of that in the database, and most apps
1653        // have icons anyway.
1654        final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
1655        if (resolveInfo != null) {
1656            icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
1657        }
1658        // the db
1659        if (icon == null) {
1660            if (c != null) {
1661                icon = getIconFromCursor(c, iconIndex, context);
1662            }
1663        }
1664        // the fallback icon
1665        if (icon == null) {
1666            icon = getFallbackIcon();
1667            info.usingFallbackIcon = true;
1668        }
1669        info.setIcon(icon);
1670
1671        // from the resource
1672        if (resolveInfo != null) {
1673            ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
1674            if (labelCache != null && labelCache.containsKey(key)) {
1675                info.title = labelCache.get(key);
1676            } else {
1677                info.title = resolveInfo.activityInfo.loadLabel(manager);
1678                if (labelCache != null) {
1679                    labelCache.put(key, info.title);
1680                }
1681            }
1682        }
1683        // from the db
1684        if (info.title == null) {
1685            if (c != null) {
1686                info.title =  c.getString(titleIndex);
1687            }
1688        }
1689        // fall back to the class name of the activity
1690        if (info.title == null) {
1691            info.title = componentName.getClassName();
1692        }
1693        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
1694        return info;
1695    }
1696
1697    /**
1698     * Make an ShortcutInfo object for a shortcut that isn't an application.
1699     */
1700    private ShortcutInfo getShortcutInfo(Cursor c, Context context,
1701            int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
1702            int titleIndex) {
1703
1704        Bitmap icon = null;
1705        final ShortcutInfo info = new ShortcutInfo();
1706        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1707
1708        // TODO: If there's an explicit component and we can't install that, delete it.
1709
1710        info.title = c.getString(titleIndex);
1711
1712        int iconType = c.getInt(iconTypeIndex);
1713        switch (iconType) {
1714        case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
1715            String packageName = c.getString(iconPackageIndex);
1716            String resourceName = c.getString(iconResourceIndex);
1717            PackageManager packageManager = context.getPackageManager();
1718            info.customIcon = false;
1719            // the resource
1720            try {
1721                Resources resources = packageManager.getResourcesForApplication(packageName);
1722                if (resources != null) {
1723                    final int id = resources.getIdentifier(resourceName, null, null);
1724                    icon = Utilities.createIconBitmap(
1725                            mIconCache.getFullResIcon(resources, id), context);
1726                }
1727            } catch (Exception e) {
1728                // drop this.  we have other places to look for icons
1729            }
1730            // the db
1731            if (icon == null) {
1732                icon = getIconFromCursor(c, iconIndex, context);
1733            }
1734            // the fallback icon
1735            if (icon == null) {
1736                icon = getFallbackIcon();
1737                info.usingFallbackIcon = true;
1738            }
1739            break;
1740        case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
1741            icon = getIconFromCursor(c, iconIndex, context);
1742            if (icon == null) {
1743                icon = getFallbackIcon();
1744                info.customIcon = false;
1745                info.usingFallbackIcon = true;
1746            } else {
1747                info.customIcon = true;
1748            }
1749            break;
1750        default:
1751            icon = getFallbackIcon();
1752            info.usingFallbackIcon = true;
1753            info.customIcon = false;
1754            break;
1755        }
1756        info.setIcon(icon);
1757        return info;
1758    }
1759
1760    Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
1761        if (false) {
1762            Log.d(TAG, "getIconFromCursor app="
1763                    + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
1764        }
1765        byte[] data = c.getBlob(iconIndex);
1766        try {
1767            return Utilities.createIconBitmap(
1768                    BitmapFactory.decodeByteArray(data, 0, data.length), context);
1769        } catch (Exception e) {
1770            return null;
1771        }
1772    }
1773
1774    ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
1775            int cellX, int cellY, boolean notify) {
1776        final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
1777        if (info == null) {
1778            return null;
1779        }
1780        addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
1781
1782        return info;
1783    }
1784
1785    /**
1786     * Attempts to find an AppWidgetProviderInfo that matches the given component.
1787     */
1788    AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
1789            ComponentName component) {
1790        List<AppWidgetProviderInfo> widgets =
1791            AppWidgetManager.getInstance(context).getInstalledProviders();
1792        for (AppWidgetProviderInfo info : widgets) {
1793            if (info.provider.equals(component)) {
1794                return info;
1795            }
1796        }
1797        return null;
1798    }
1799
1800    /**
1801     * Returns a list of all the widgets that can handle configuration with a particular mimeType.
1802     */
1803    List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
1804        final PackageManager packageManager = context.getPackageManager();
1805        final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
1806            new ArrayList<WidgetMimeTypeHandlerData>();
1807
1808        final Intent supportsIntent =
1809            new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
1810        supportsIntent.setType(mimeType);
1811
1812        // Create a set of widget configuration components that we can test against
1813        final List<AppWidgetProviderInfo> widgets =
1814            AppWidgetManager.getInstance(context).getInstalledProviders();
1815        final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
1816            new HashMap<ComponentName, AppWidgetProviderInfo>();
1817        for (AppWidgetProviderInfo info : widgets) {
1818            configurationComponentToWidget.put(info.configure, info);
1819        }
1820
1821        // Run through each of the intents that can handle this type of clip data, and cross
1822        // reference them with the components that are actual configuration components
1823        final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
1824                PackageManager.MATCH_DEFAULT_ONLY);
1825        for (ResolveInfo info : activities) {
1826            final ActivityInfo activityInfo = info.activityInfo;
1827            final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
1828                    activityInfo.name);
1829            if (configurationComponentToWidget.containsKey(infoComponent)) {
1830                supportedConfigurationActivities.add(
1831                        new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
1832                                configurationComponentToWidget.get(infoComponent)));
1833            }
1834        }
1835        return supportedConfigurationActivities;
1836    }
1837
1838    ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
1839        Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
1840        String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1841        Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
1842
1843        if (intent == null) {
1844            // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
1845            Log.e(TAG, "Can't construct ShorcutInfo with null intent");
1846            return null;
1847        }
1848
1849        Bitmap icon = null;
1850        boolean customIcon = false;
1851        ShortcutIconResource iconResource = null;
1852
1853        if (bitmap != null && bitmap instanceof Bitmap) {
1854            icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
1855            customIcon = true;
1856        } else {
1857            Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
1858            if (extra != null && extra instanceof ShortcutIconResource) {
1859                try {
1860                    iconResource = (ShortcutIconResource) extra;
1861                    final PackageManager packageManager = context.getPackageManager();
1862                    Resources resources = packageManager.getResourcesForApplication(
1863                            iconResource.packageName);
1864                    final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1865                    icon = Utilities.createIconBitmap(
1866                            mIconCache.getFullResIcon(resources, id), context);
1867                } catch (Exception e) {
1868                    Log.w(TAG, "Could not load shortcut icon: " + extra);
1869                }
1870            }
1871        }
1872
1873        final ShortcutInfo info = new ShortcutInfo();
1874
1875        if (icon == null) {
1876            if (fallbackIcon != null) {
1877                icon = fallbackIcon;
1878            } else {
1879                icon = getFallbackIcon();
1880                info.usingFallbackIcon = true;
1881            }
1882        }
1883        info.setIcon(icon);
1884
1885        info.title = name;
1886        info.intent = intent;
1887        info.customIcon = customIcon;
1888        info.iconResource = iconResource;
1889
1890        return info;
1891    }
1892
1893    boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
1894            int iconIndex) {
1895        // If apps can't be on SD, don't even bother.
1896        if (!mAppsCanBeOnExternalStorage) {
1897            return false;
1898        }
1899        // If this icon doesn't have a custom icon, check to see
1900        // what's stored in the DB, and if it doesn't match what
1901        // we're going to show, store what we are going to show back
1902        // into the DB.  We do this so when we're loading, if the
1903        // package manager can't find an icon (for example because
1904        // the app is on SD) then we can use that instead.
1905        if (!info.customIcon && !info.usingFallbackIcon) {
1906            cache.put(info, c.getBlob(iconIndex));
1907            return true;
1908        }
1909        return false;
1910    }
1911    void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
1912        boolean needSave = false;
1913        try {
1914            if (data != null) {
1915                Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
1916                Bitmap loaded = info.getIcon(mIconCache);
1917                needSave = !saved.sameAs(loaded);
1918            } else {
1919                needSave = true;
1920            }
1921        } catch (Exception e) {
1922            needSave = true;
1923        }
1924        if (needSave) {
1925            Log.d(TAG, "going to save icon bitmap for info=" + info);
1926            // This is slower than is ideal, but this only happens once
1927            // or when the app is updated with a new icon.
1928            updateItemInDatabase(context, info);
1929        }
1930    }
1931
1932    /**
1933     * Return an existing FolderInfo object if we have encountered this ID previously,
1934     * or make a new one.
1935     */
1936    private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
1937        // See if a placeholder was created for us already
1938        FolderInfo folderInfo = folders.get(id);
1939        if (folderInfo == null) {
1940            // No placeholder -- create a new instance
1941            folderInfo = new FolderInfo();
1942            folders.put(id, folderInfo);
1943        }
1944        return folderInfo;
1945    }
1946
1947    private static final Collator sCollator = Collator.getInstance();
1948    public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
1949            = new Comparator<ApplicationInfo>() {
1950        public final int compare(ApplicationInfo a, ApplicationInfo b) {
1951            int result = sCollator.compare(a.title.toString(), b.title.toString());
1952            if (result == 0) {
1953                result = a.componentName.compareTo(b.componentName);
1954            }
1955            return result;
1956        }
1957    };
1958    public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
1959            = new Comparator<ApplicationInfo>() {
1960        public final int compare(ApplicationInfo a, ApplicationInfo b) {
1961            if (a.firstInstallTime < b.firstInstallTime) return 1;
1962            if (a.firstInstallTime > b.firstInstallTime) return -1;
1963            return 0;
1964        }
1965    };
1966    public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
1967            = new Comparator<AppWidgetProviderInfo>() {
1968        public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
1969            return sCollator.compare(a.label.toString(), b.label.toString());
1970        }
1971    };
1972    static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
1973        if (info.activityInfo != null) {
1974            return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
1975        } else {
1976            return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
1977        }
1978    }
1979    public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
1980        private PackageManager mPackageManager;
1981        private HashMap<Object, CharSequence> mLabelCache;
1982        ShortcutNameComparator(PackageManager pm) {
1983            mPackageManager = pm;
1984            mLabelCache = new HashMap<Object, CharSequence>();
1985        }
1986        ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
1987            mPackageManager = pm;
1988            mLabelCache = labelCache;
1989        }
1990        public final int compare(ResolveInfo a, ResolveInfo b) {
1991            CharSequence labelA, labelB;
1992            ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
1993            ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
1994            if (mLabelCache.containsKey(keyA)) {
1995                labelA = mLabelCache.get(keyA);
1996            } else {
1997                labelA = a.loadLabel(mPackageManager).toString();
1998
1999                mLabelCache.put(keyA, labelA);
2000            }
2001            if (mLabelCache.containsKey(keyB)) {
2002                labelB = mLabelCache.get(keyB);
2003            } else {
2004                labelB = b.loadLabel(mPackageManager).toString();
2005
2006                mLabelCache.put(keyB, labelB);
2007            }
2008            return sCollator.compare(labelA, labelB);
2009        }
2010    };
2011    public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
2012        private PackageManager mPackageManager;
2013        private HashMap<Object, String> mLabelCache;
2014        WidgetAndShortcutNameComparator(PackageManager pm) {
2015            mPackageManager = pm;
2016            mLabelCache = new HashMap<Object, String>();
2017        }
2018        public final int compare(Object a, Object b) {
2019            String labelA, labelB;
2020            if (mLabelCache.containsKey(a)) {
2021                labelA = mLabelCache.get(a);
2022            } else {
2023                labelA = (a instanceof AppWidgetProviderInfo) ?
2024                    ((AppWidgetProviderInfo) a).label :
2025                    ((ResolveInfo) a).loadLabel(mPackageManager).toString();
2026                mLabelCache.put(a, labelA);
2027            }
2028            if (mLabelCache.containsKey(b)) {
2029                labelB = mLabelCache.get(b);
2030            } else {
2031                labelB = (b instanceof AppWidgetProviderInfo) ?
2032                    ((AppWidgetProviderInfo) b).label :
2033                    ((ResolveInfo) b).loadLabel(mPackageManager).toString();
2034                mLabelCache.put(b, labelB);
2035            }
2036            return sCollator.compare(labelA, labelB);
2037        }
2038    };
2039
2040    public void dumpState() {
2041        Log.d(TAG, "mCallbacks=" + mCallbacks);
2042        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
2043        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
2044        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
2045        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
2046        if (mLoaderTask != null) {
2047            mLoaderTask.dumpState();
2048        } else {
2049            Log.d(TAG, "mLoaderTask=null");
2050        }
2051    }
2052}
2053