LauncherModel.java revision 3dba179949b4c1ce6d91c8eb847a91d9f2c56282
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.launcher3;
18
19import android.app.SearchManager;
20import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
22import android.content.*;
23import android.content.Intent.ShortcutIconResource;
24import android.content.pm.ActivityInfo;
25import android.content.pm.PackageInfo;
26import android.content.pm.PackageManager;
27import android.content.pm.PackageManager.NameNotFoundException;
28import android.content.pm.ResolveInfo;
29import android.content.res.Configuration;
30import android.content.res.Resources;
31import android.database.Cursor;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.net.Uri;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.HandlerThread;
38import android.os.Parcelable;
39import android.os.Process;
40import android.os.RemoteException;
41import android.os.SystemClock;
42import android.util.Log;
43import android.util.Pair;
44import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
45
46import java.lang.ref.WeakReference;
47import java.net.URISyntaxException;
48import java.text.Collator;
49import java.util.ArrayList;
50import java.util.Arrays;
51import java.util.Collection;
52import java.util.Collections;
53import java.util.Comparator;
54import java.util.HashMap;
55import java.util.HashSet;
56import java.util.Iterator;
57import java.util.List;
58import java.util.Set;
59import java.util.TreeMap;
60
61/**
62 * Maintains in-memory state of the Launcher. It is expected that there should be only one
63 * LauncherModel object held in a static. Also provide APIs for updating the database state
64 * for the Launcher.
65 */
66public class LauncherModel extends BroadcastReceiver {
67    static final boolean DEBUG_LOADERS = false;
68    static final String TAG = "Launcher.Model";
69
70    private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
71    private final boolean mAppsCanBeOnExternalStorage;
72
73    private final LauncherAppState mApp;
74    private final Object mLock = new Object();
75    private DeferredHandler mHandler = new DeferredHandler();
76    private LoaderTask mLoaderTask;
77    private boolean mIsLoaderTaskRunning;
78    private volatile boolean mFlushingWorkerThread;
79
80    // Specific runnable types that are run on the main thread deferred handler, this allows us to
81    // clear all queued binding runnables when the Launcher activity is destroyed.
82    private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
83    private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
84
85
86    private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
87    static {
88        sWorkerThread.start();
89    }
90    private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
91
92    // We start off with everything not loaded.  After that, we assume that
93    // our monitoring of the package manager provides all updates and we never
94    // need to do a requery.  These are only ever touched from the loader thread.
95    private boolean mWorkspaceLoaded;
96    private boolean mAllAppsLoaded;
97
98    // When we are loading pages synchronously, we can't just post the binding of items on the side
99    // pages as this delays the rotation process.  Instead, we wait for a callback from the first
100    // draw (in Workspace) to initiate the binding of the remaining side pages.  Any time we start
101    // a normal load, we also clear this set of Runnables.
102    static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
103
104    private WeakReference<Callbacks> mCallbacks;
105
106    // < only access in worker thread >
107    private AllAppsList mBgAllAppsList;
108
109    // The lock that must be acquired before referencing any static bg data structures.  Unlike
110    // other locks, this one can generally be held long-term because we never expect any of these
111    // static data structures to be referenced outside of the worker thread except on the first
112    // load after configuration change.
113    static final Object sBgLock = new Object();
114
115    // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
116    // LauncherModel to their ids
117    static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
118
119    // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
120    //       created by LauncherModel that are directly on the home screen (however, no widgets or
121    //       shortcuts within folders).
122    static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
123
124    // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
125    static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
126        new ArrayList<LauncherAppWidgetInfo>();
127
128    // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
129    static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
130
131    // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
132    static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
133
134    // sBgWorkspaceScreens is the ordered set of workspace screens.
135    static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
136
137    // </ only access in worker thread >
138
139    private IconCache mIconCache;
140    private Bitmap mDefaultIcon;
141
142    private static int mCellCountX;
143    private static int mCellCountY;
144
145    protected int mPreviousConfigMcc;
146
147    public interface Callbacks {
148        public boolean setLoadOnResume();
149        public int getCurrentWorkspaceScreen();
150        public void startBinding();
151        public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
152                              boolean forceAnimateIcons);
153        public void bindScreens(ArrayList<Long> orderedScreenIds);
154        public void bindAddScreens(ArrayList<Long> orderedScreenIds);
155        public void bindFolders(HashMap<Long,FolderInfo> folders);
156        public void finishBindingItems(boolean upgradePath);
157        public void bindAppWidget(LauncherAppWidgetInfo info);
158        public void bindAllApplications(ArrayList<ApplicationInfo> apps);
159        public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
160        public void bindComponentsRemoved(ArrayList<String> packageNames,
161                        ArrayList<ApplicationInfo> appInfos,
162                        boolean matchPackageNamesOnly);
163        public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
164        public void bindSearchablesChanged();
165        public void onPageBoundSynchronously(int page);
166    }
167
168    public interface ItemInfoFilter {
169        public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
170    }
171
172    LauncherModel(LauncherAppState app, IconCache iconCache) {
173        final Context context = app.getContext();
174
175        mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
176        mApp = app;
177        mBgAllAppsList = new AllAppsList(iconCache);
178        mIconCache = iconCache;
179
180        mDefaultIcon = Utilities.createIconBitmap(
181                mIconCache.getFullResDefaultActivityIcon(), context);
182
183        final Resources res = context.getResources();
184        Configuration config = res.getConfiguration();
185        mPreviousConfigMcc = config.mcc;
186    }
187
188    /** Runs the specified runnable immediately if called from the main thread, otherwise it is
189     * posted on the main thread handler. */
190    private void runOnMainThread(Runnable r) {
191        runOnMainThread(r, 0);
192    }
193    private void runOnMainThread(Runnable r, int type) {
194        if (sWorkerThread.getThreadId() == Process.myTid()) {
195            // If we are on the worker thread, post onto the main handler
196            mHandler.post(r);
197        } else {
198            r.run();
199        }
200    }
201
202    /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
203     * posted on the worker thread handler. */
204    private static void runOnWorkerThread(Runnable r) {
205        if (sWorkerThread.getThreadId() == Process.myTid()) {
206            r.run();
207        } else {
208            // If we are not on the worker thread, then post to the worker handler
209            sWorker.post(r);
210        }
211    }
212
213    static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
214                                 long screen) {
215        final int xCount = LauncherModel.getCellCountX();
216        final int yCount = LauncherModel.getCellCountY();
217        boolean[][] occupied = new boolean[xCount][yCount];
218
219        int cellX, cellY, spanX, spanY;
220        for (int i = 0; i < items.size(); ++i) {
221            final ItemInfo item = items.get(i);
222            if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
223                if (item.screenId == screen) {
224                    cellX = item.cellX;
225                    cellY = item.cellY;
226                    spanX = item.spanX;
227                    spanY = item.spanY;
228                    for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
229                        for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
230                            occupied[x][y] = true;
231                        }
232                    }
233                }
234            }
235        }
236
237        return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
238    }
239    static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
240                                                        Intent launchIntent,
241                                                        int firstScreenIndex) {
242        // Lock on the app so that we don't try and get the items while apps are being added
243        LauncherAppState app = LauncherAppState.getInstance();
244        LauncherModel model = app.getModel();
245        boolean found = false;
246        synchronized (app) {
247            if (sWorkerThread.getThreadId() != Process.myTid()) {
248                // Flush the LauncherModel worker thread, so that if we just did another
249                // processInstallShortcut, we give it time for its shortcut to get added to the
250                // database (getItemsInLocalCoordinates reads the database)
251                model.flushWorkerThread();
252            }
253            final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
254
255            // Try adding to the workspace screens incrementally, starting at the default or center
256            // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
257            firstScreenIndex = Math.min(firstScreenIndex, sBgWorkspaceScreens.size());
258            int count = sBgWorkspaceScreens.size();
259            for (int screen = firstScreenIndex; screen < count && !found; screen++) {
260                int[] tmpCoordinates = new int[2];
261                if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
262                        sBgWorkspaceScreens.get(screen))) {
263                    // Update the Launcher db
264                    return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates);
265                }
266            }
267        }
268        return null;
269    }
270
271    public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added) {
272        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
273        addAndBindAddedApps(context, added, cb);
274    }
275    public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added,
276                                    final Callbacks callbacks) {
277        if (added.isEmpty()) {
278            throw new RuntimeException("EMPTY ADDED ARRAY?");
279        }
280        // Process the newly added applications and add them to the database first
281        Runnable r = new Runnable() {
282            public void run() {
283                final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
284                final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
285
286                synchronized(sBgLock) {
287                    Iterator<ItemInfo> iter = added.iterator();
288                    while (iter.hasNext()) {
289                        ItemInfo a = iter.next();
290                        final String name = a.title.toString();
291                        final Intent launchIntent = a.getIntent();
292
293                        // Short-circuit this logic if the icon exists somewhere on the workspace
294                        if (LauncherModel.shortcutExists(context, name, launchIntent)) {
295                            continue;
296                        }
297
298                        // Add this icon to the db, creating a new page if necessary
299                        int startSearchPageIndex = 1;
300                        Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
301                                name, launchIntent, startSearchPageIndex);
302                        if (coords == null) {
303                            LauncherAppState appState = LauncherAppState.getInstance();
304                            LauncherProvider lp = appState.getLauncherProvider();
305
306                            // If we can't find a valid position, then just add a new screen.
307                            // This takes time so we need to re-queue the add until the new
308                            // page is added.  Create as many screens as necessary to satisfy
309                            // the startSearchPageIndex.
310                            int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
311                                    sBgWorkspaceScreens.size());
312                            while (numPagesToAdd > 0) {
313                                long screenId = lp.generateNewScreenId();
314                                // Update the model
315                                sBgWorkspaceScreens.add(screenId);
316                                updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
317                                // Save the screen id for binding in the workspace
318                                addedWorkspaceScreensFinal.add(screenId);
319                                numPagesToAdd--;
320                            }
321                            // Find the coordinate again
322                            coords = LauncherModel.findNextAvailableIconSpace(context,
323                                    name, launchIntent, startSearchPageIndex);
324                        }
325                        if (coords == null) {
326                            throw new RuntimeException("Coordinates should not be null");
327                        }
328
329                        ShortcutInfo shortcutInfo;
330                        if (a instanceof ShortcutInfo) {
331                            shortcutInfo = (ShortcutInfo) a;
332                        } else if (a instanceof ApplicationInfo) {
333                            shortcutInfo = ((ApplicationInfo) a).makeShortcut();
334                        } else {
335                            throw new RuntimeException("Unexpected info type");
336                        }
337                        // Add the shortcut to the db
338                        addItemToDatabase(context, shortcutInfo,
339                                LauncherSettings.Favorites.CONTAINER_DESKTOP,
340                                coords.first, coords.second[0], coords.second[1], false);
341                        // Save the ShortcutInfo for binding in the workspace
342                        addedShortcutsFinal.add(shortcutInfo);
343                    }
344                }
345
346                if (!addedShortcutsFinal.isEmpty()) {
347                    runOnMainThread(new Runnable() {
348                        public void run() {
349                            Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
350                            if (callbacks == cb && cb != null) {
351                                callbacks.bindAddScreens(addedWorkspaceScreensFinal);
352
353                                ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
354                                long lastScreenId = info.screenId;
355                                final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
356                                final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
357                                for (ItemInfo i : addedShortcutsFinal) {
358                                    if (i.screenId == lastScreenId) {
359                                        addAnimated.add(i);
360                                    } else {
361                                        addNotAnimated.add(i);
362                                    }
363                                }
364                                // We add the items without animation on non-visible pages, and with
365                                // animations on the new page (which we will try and snap to).
366                                if (!addNotAnimated.isEmpty()) {
367                                    callbacks.bindItems(addNotAnimated, 0,
368                                            addNotAnimated.size(), false);
369                                }
370                                if (!addAnimated.isEmpty()) {
371                                    callbacks.bindItems(addAnimated, 0,
372                                            addAnimated.size(), true);
373                                }
374                            }
375                        }
376                    });
377                }
378            }
379        };
380        runOnWorkerThread(r);
381    }
382
383    public Bitmap getFallbackIcon() {
384        return Bitmap.createBitmap(mDefaultIcon);
385    }
386
387    public void unbindItemInfosAndClearQueuedBindRunnables() {
388        if (sWorkerThread.getThreadId() == Process.myTid()) {
389            throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
390                    "main thread");
391        }
392
393        // Clear any deferred bind runnables
394        mDeferredBindRunnables.clear();
395        // Remove any queued bind runnables
396        mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
397        // Unbind all the workspace items
398        unbindWorkspaceItemsOnMainThread();
399    }
400
401    /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
402    void unbindWorkspaceItemsOnMainThread() {
403        // Ensure that we don't use the same workspace items data structure on the main thread
404        // by making a copy of workspace items first.
405        final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
406        final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
407        synchronized (sBgLock) {
408            tmpWorkspaceItems.addAll(sBgWorkspaceItems);
409            tmpAppWidgets.addAll(sBgAppWidgets);
410        }
411        Runnable r = new Runnable() {
412                @Override
413                public void run() {
414                   for (ItemInfo item : tmpWorkspaceItems) {
415                       item.unbind();
416                   }
417                   for (ItemInfo item : tmpAppWidgets) {
418                       item.unbind();
419                   }
420                }
421            };
422        runOnMainThread(r);
423    }
424
425    /**
426     * Adds an item to the DB if it was not created previously, or move it to a new
427     * <container, screen, cellX, cellY>
428     */
429    static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
430            long screenId, int cellX, int cellY) {
431        if (item.container == ItemInfo.NO_ID) {
432            // From all apps
433            addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
434        } else {
435            // From somewhere else
436            moveItemInDatabase(context, item, container, screenId, cellX, cellY);
437        }
438    }
439
440    static void checkItemInfoLocked(
441            final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
442        ItemInfo modelItem = sBgItemsIdMap.get(itemId);
443        if (modelItem != null && item != modelItem) {
444            // check all the data is consistent
445            if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
446                ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
447                ShortcutInfo shortcut = (ShortcutInfo) item;
448                if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
449                        modelShortcut.intent.filterEquals(shortcut.intent) &&
450                        modelShortcut.id == shortcut.id &&
451                        modelShortcut.itemType == shortcut.itemType &&
452                        modelShortcut.container == shortcut.container &&
453                        modelShortcut.screenId == shortcut.screenId &&
454                        modelShortcut.cellX == shortcut.cellX &&
455                        modelShortcut.cellY == shortcut.cellY &&
456                        modelShortcut.spanX == shortcut.spanX &&
457                        modelShortcut.spanY == shortcut.spanY &&
458                        ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
459                        (modelShortcut.dropPos != null &&
460                                shortcut.dropPos != null &&
461                                modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
462                        modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
463                    // For all intents and purposes, this is the same object
464                    return;
465                }
466            }
467
468            // the modelItem needs to match up perfectly with item if our model is
469            // to be consistent with the database-- for now, just require
470            // modelItem == item or the equality check above
471            String msg = "item: " + ((item != null) ? item.toString() : "null") +
472                    "modelItem: " +
473                    ((modelItem != null) ? modelItem.toString() : "null") +
474                    "Error: ItemInfo passed to checkItemInfo doesn't match original";
475            RuntimeException e = new RuntimeException(msg);
476            if (stackTrace != null) {
477                e.setStackTrace(stackTrace);
478            }
479            // TODO: something breaks this in the upgrade path
480            //throw e;
481        }
482    }
483
484    static void checkItemInfo(final ItemInfo item) {
485        final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
486        final long itemId = item.id;
487        Runnable r = new Runnable() {
488            public void run() {
489                synchronized (sBgLock) {
490                    checkItemInfoLocked(itemId, item, stackTrace);
491                }
492            }
493        };
494        runOnWorkerThread(r);
495    }
496
497    static void updateItemInDatabaseHelper(Context context, final ContentValues values,
498            final ItemInfo item, final String callingFunction) {
499        final long itemId = item.id;
500        final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
501        final ContentResolver cr = context.getContentResolver();
502
503        final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
504        Runnable r = new Runnable() {
505            public void run() {
506                cr.update(uri, values, null, null);
507                updateItemArrays(item, itemId, stackTrace);
508            }
509        };
510        runOnWorkerThread(r);
511    }
512
513    static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
514            final ArrayList<ItemInfo> items, final String callingFunction) {
515        final ContentResolver cr = context.getContentResolver();
516
517        final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
518        Runnable r = new Runnable() {
519            public void run() {
520                ArrayList<ContentProviderOperation> ops =
521                        new ArrayList<ContentProviderOperation>();
522                int count = items.size();
523                for (int i = 0; i < count; i++) {
524                    ItemInfo item = items.get(i);
525                    final long itemId = item.id;
526                    final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
527                    ContentValues values = valuesList.get(i);
528
529                    ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
530                    updateItemArrays(item, itemId, stackTrace);
531
532                }
533                try {
534                    cr.applyBatch(LauncherProvider.AUTHORITY, ops);
535                } catch (Exception e) {
536                    e.printStackTrace();
537                }
538            }
539        };
540        runOnWorkerThread(r);
541    }
542
543    static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
544        // Lock on mBgLock *after* the db operation
545        synchronized (sBgLock) {
546            checkItemInfoLocked(itemId, item, stackTrace);
547
548            if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
549                    item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
550                // Item is in a folder, make sure this folder exists
551                if (!sBgFolders.containsKey(item.container)) {
552                    // An items container is being set to a that of an item which is not in
553                    // the list of Folders.
554                    String msg = "item: " + item + " container being set to: " +
555                            item.container + ", not in the list of folders";
556                    Log.e(TAG, msg);
557                    Launcher.dumpDebugLogsToConsole();
558                }
559            }
560
561            // Items are added/removed from the corresponding FolderInfo elsewhere, such
562            // as in Workspace.onDrop. Here, we just add/remove them from the list of items
563            // that are on the desktop, as appropriate
564            ItemInfo modelItem = sBgItemsIdMap.get(itemId);
565            if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
566                    modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
567                switch (modelItem.itemType) {
568                    case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
569                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
570                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
571                        if (!sBgWorkspaceItems.contains(modelItem)) {
572                            sBgWorkspaceItems.add(modelItem);
573                        }
574                        break;
575                    default:
576                        break;
577                }
578            } else {
579                sBgWorkspaceItems.remove(modelItem);
580            }
581        }
582    }
583
584    public void flushWorkerThread() {
585        mFlushingWorkerThread = true;
586        Runnable waiter = new Runnable() {
587                public void run() {
588                    synchronized (this) {
589                        notifyAll();
590                        mFlushingWorkerThread = false;
591                    }
592                }
593            };
594
595        synchronized(waiter) {
596            runOnWorkerThread(waiter);
597            if (mLoaderTask != null) {
598                synchronized(mLoaderTask) {
599                    mLoaderTask.notify();
600                }
601            }
602            boolean success = false;
603            while (!success) {
604                try {
605                    waiter.wait();
606                    success = true;
607                } catch (InterruptedException e) {
608                }
609            }
610        }
611    }
612
613    /**
614     * Move an item in the DB to a new <container, screen, cellX, cellY>
615     */
616    static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
617            final long screenId, final int cellX, final int cellY) {
618        String transaction = "DbDebug    Modify item (" + item.title + ") in db, id: " + item.id +
619                " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
620                ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
621        Launcher.sDumpLogs.add(transaction);
622        Log.d(TAG, transaction);
623        item.container = container;
624        item.cellX = cellX;
625        item.cellY = cellY;
626
627        // We store hotseat items in canonical form which is this orientation invariant position
628        // in the hotseat
629        if (context instanceof Launcher && screenId < 0 &&
630                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
631            item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
632        } else {
633            item.screenId = screenId;
634        }
635
636        final ContentValues values = new ContentValues();
637        values.put(LauncherSettings.Favorites.CONTAINER, item.container);
638        values.put(LauncherSettings.Favorites.CELLX, item.cellX);
639        values.put(LauncherSettings.Favorites.CELLY, item.cellY);
640        values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
641
642        updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
643    }
644
645    /**
646     * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
647     * cellX, cellY have already been updated on the ItemInfos.
648     */
649    static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
650            final long container, final int screen) {
651
652        ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
653        int count = items.size();
654
655        for (int i = 0; i < count; i++) {
656            ItemInfo item = items.get(i);
657            String transaction = "DbDebug    Modify item (" + item.title + ") in db, id: "
658                    + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
659                    + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
660                    + item.cellX + ", " + item.cellY + ")";
661            Launcher.sDumpLogs.add(transaction);
662            item.container = container;
663
664            // We store hotseat items in canonical form which is this orientation invariant position
665            // in the hotseat
666            if (context instanceof Launcher && screen < 0 &&
667                    container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
668                item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
669                        item.cellY);
670            } else {
671                item.screenId = screen;
672            }
673
674            final ContentValues values = new ContentValues();
675            values.put(LauncherSettings.Favorites.CONTAINER, item.container);
676            values.put(LauncherSettings.Favorites.CELLX, item.cellX);
677            values.put(LauncherSettings.Favorites.CELLY, item.cellY);
678            values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
679
680            contentValues.add(values);
681        }
682        updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
683    }
684
685    /**
686     * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
687     */
688    static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
689            final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
690        String transaction = "DbDebug    Modify item (" + item.title + ") in db, id: " + item.id +
691                " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
692                ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
693        Launcher.sDumpLogs.add(transaction);
694        Log.d(TAG, transaction);
695        item.cellX = cellX;
696        item.cellY = cellY;
697        item.spanX = spanX;
698        item.spanY = spanY;
699
700        // We store hotseat items in canonical form which is this orientation invariant position
701        // in the hotseat
702        if (context instanceof Launcher && screenId < 0 &&
703                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
704            item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
705        } else {
706            item.screenId = screenId;
707        }
708
709        final ContentValues values = new ContentValues();
710        values.put(LauncherSettings.Favorites.CONTAINER, item.container);
711        values.put(LauncherSettings.Favorites.CELLX, item.cellX);
712        values.put(LauncherSettings.Favorites.CELLY, item.cellY);
713        values.put(LauncherSettings.Favorites.SPANX, item.spanX);
714        values.put(LauncherSettings.Favorites.SPANY, item.spanY);
715        values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
716
717        updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
718    }
719
720    /**
721     * Update an item to the database in a specified container.
722     */
723    static void updateItemInDatabase(Context context, final ItemInfo item) {
724        final ContentValues values = new ContentValues();
725        item.onAddToDatabase(values);
726        item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
727        updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
728    }
729
730    /**
731     * Returns true if the shortcuts already exists in the database.
732     * we identify a shortcut by its title and intent.
733     */
734    static boolean shortcutExists(Context context, String title, Intent intent) {
735        final ContentResolver cr = context.getContentResolver();
736        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
737            new String[] { "title", "intent" }, "title=? and intent=?",
738            new String[] { title, intent.toUri(0) }, null);
739        boolean result = false;
740        try {
741            result = c.moveToFirst();
742        } finally {
743            c.close();
744        }
745        return result;
746    }
747
748    /**
749     * Returns an ItemInfo array containing all the items in the LauncherModel.
750     * The ItemInfo.id is not set through this function.
751     */
752    static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
753        ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
754        final ContentResolver cr = context.getContentResolver();
755        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
756                LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
757                LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
758                LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
759
760        final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
761        final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
762        final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
763        final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
764        final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
765        final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
766        final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
767
768        try {
769            while (c.moveToNext()) {
770                ItemInfo item = new ItemInfo();
771                item.cellX = c.getInt(cellXIndex);
772                item.cellY = c.getInt(cellYIndex);
773                item.spanX = c.getInt(spanXIndex);
774                item.spanY = c.getInt(spanYIndex);
775                item.container = c.getInt(containerIndex);
776                item.itemType = c.getInt(itemTypeIndex);
777                item.screenId = c.getInt(screenIndex);
778
779                items.add(item);
780            }
781        } catch (Exception e) {
782            items.clear();
783        } finally {
784            c.close();
785        }
786
787        return items;
788    }
789
790    /**
791     * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
792     */
793    FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
794        final ContentResolver cr = context.getContentResolver();
795        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
796                "_id=? and (itemType=? or itemType=?)",
797                new String[] { String.valueOf(id),
798                        String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
799
800        try {
801            if (c.moveToFirst()) {
802                final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
803                final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
804                final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
805                final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
806                final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
807                final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
808
809                FolderInfo folderInfo = null;
810                switch (c.getInt(itemTypeIndex)) {
811                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
812                        folderInfo = findOrMakeFolder(folderList, id);
813                        break;
814                }
815
816                folderInfo.title = c.getString(titleIndex);
817                folderInfo.id = id;
818                folderInfo.container = c.getInt(containerIndex);
819                folderInfo.screenId = c.getInt(screenIndex);
820                folderInfo.cellX = c.getInt(cellXIndex);
821                folderInfo.cellY = c.getInt(cellYIndex);
822
823                return folderInfo;
824            }
825        } finally {
826            c.close();
827        }
828
829        return null;
830    }
831
832    /**
833     * Add an item to the database in a specified container. Sets the container, screen, cellX and
834     * cellY fields of the item. Also assigns an ID to the item.
835     */
836    static void addItemToDatabase(Context context, final ItemInfo item, final long container,
837            final long screenId, final int cellX, final int cellY, final boolean notify) {
838        item.container = container;
839        item.cellX = cellX;
840        item.cellY = cellY;
841        // We store hotseat items in canonical form which is this orientation invariant position
842        // in the hotseat
843        if (context instanceof Launcher && screenId < 0 &&
844                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
845            item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
846        } else {
847            item.screenId = screenId;
848        }
849
850        final ContentValues values = new ContentValues();
851        final ContentResolver cr = context.getContentResolver();
852        item.onAddToDatabase(values);
853
854        LauncherAppState app = LauncherAppState.getInstance();
855        item.id = app.getLauncherProvider().generateNewItemId();
856        values.put(LauncherSettings.Favorites._ID, item.id);
857        item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
858
859        Runnable r = new Runnable() {
860            public void run() {
861                String transaction = "DbDebug    Add item (" + item.title + ") to db, id: "
862                        + item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
863                        + cellY + ")";
864                Launcher.sDumpLogs.add(transaction);
865                Log.d(TAG, transaction);
866
867                cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
868                        LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
869
870                // Lock on mBgLock *after* the db operation
871                synchronized (sBgLock) {
872                    checkItemInfoLocked(item.id, item, null);
873                    sBgItemsIdMap.put(item.id, item);
874                    switch (item.itemType) {
875                        case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
876                            sBgFolders.put(item.id, (FolderInfo) item);
877                            // Fall through
878                        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
879                        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
880                            if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
881                                    item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
882                                sBgWorkspaceItems.add(item);
883                            } else {
884                                if (!sBgFolders.containsKey(item.container)) {
885                                    // Adding an item to a folder that doesn't exist.
886                                    String msg = "adding item: " + item + " to a folder that " +
887                                            " doesn't exist";
888                                    Log.e(TAG, msg);
889                                    Launcher.dumpDebugLogsToConsole();
890                                }
891                            }
892                            break;
893                        case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
894                            sBgAppWidgets.add((LauncherAppWidgetInfo) item);
895                            break;
896                    }
897                }
898            }
899        };
900        runOnWorkerThread(r);
901    }
902
903    /**
904     * Creates a new unique child id, for a given cell span across all layouts.
905     */
906    static int getCellLayoutChildId(
907            long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
908        return (((int) container & 0xFF) << 24)
909                | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
910    }
911
912    static int getCellCountX() {
913        return mCellCountX;
914    }
915
916    static int getCellCountY() {
917        return mCellCountY;
918    }
919
920    /**
921     * Updates the model orientation helper to take into account the current layout dimensions
922     * when performing local/canonical coordinate transformations.
923     */
924    static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
925        mCellCountX = shortAxisCellCount;
926        mCellCountY = longAxisCellCount;
927    }
928
929    /**
930     * Removes the specified item from the database
931     * @param context
932     * @param item
933     */
934    static void deleteItemFromDatabase(Context context, final ItemInfo item) {
935        final ContentResolver cr = context.getContentResolver();
936        final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
937
938        Runnable r = new Runnable() {
939            public void run() {
940                String transaction = "DbDebug    Delete item (" + item.title + ") from db, id: "
941                        + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
942                        ", " + item.cellY + ")";
943                Launcher.sDumpLogs.add(transaction);
944                Log.d(TAG, transaction);
945
946                cr.delete(uriToDelete, null, null);
947
948                // Lock on mBgLock *after* the db operation
949                synchronized (sBgLock) {
950                    switch (item.itemType) {
951                        case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
952                            sBgFolders.remove(item.id);
953                            for (ItemInfo info: sBgItemsIdMap.values()) {
954                                if (info.container == item.id) {
955                                    // We are deleting a folder which still contains items that
956                                    // think they are contained by that folder.
957                                    String msg = "deleting a folder (" + item + ") which still " +
958                                            "contains items (" + info + ")";
959                                    Log.e(TAG, msg);
960                                    Launcher.dumpDebugLogsToConsole();
961                                }
962                            }
963                            sBgWorkspaceItems.remove(item);
964                            break;
965                        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
966                        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
967                            sBgWorkspaceItems.remove(item);
968                            break;
969                        case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
970                            sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
971                            break;
972                    }
973                    sBgItemsIdMap.remove(item.id);
974                    sBgDbIconCache.remove(item);
975                }
976            }
977        };
978        runOnWorkerThread(r);
979    }
980
981    /**
982     * Update the order of the workspace screens in the database. The array list contains
983     * a list of screen ids in the order that they should appear.
984     */
985    void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
986        final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
987        final ContentResolver cr = context.getContentResolver();
988        final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
989
990        // Remove any negative screen ids -- these aren't persisted
991        Iterator<Long> iter = screensCopy.iterator();
992        while (iter.hasNext()) {
993            long id = iter.next();
994            if (id < 0) {
995                iter.remove();
996            }
997        }
998
999        Runnable r = new Runnable() {
1000            @Override
1001            public void run() {
1002                // Clear the table
1003                cr.delete(uri, null, null);
1004                int count = screens.size();
1005                ContentValues[] values = new ContentValues[count];
1006                for (int i = 0; i < count; i++) {
1007                    ContentValues v = new ContentValues();
1008                    long screenId = screens.get(i);
1009                    v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1010                    v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1011                    values[i] = v;
1012                }
1013                cr.bulkInsert(uri, values);
1014                sBgWorkspaceScreens.clear();
1015                sBgWorkspaceScreens.addAll(screensCopy);
1016            }
1017        };
1018        runOnWorkerThread(r);
1019    }
1020
1021    /**
1022     * Remove the contents of the specified folder from the database
1023     */
1024    static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
1025        final ContentResolver cr = context.getContentResolver();
1026
1027        Runnable r = new Runnable() {
1028            public void run() {
1029                cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
1030                // Lock on mBgLock *after* the db operation
1031                synchronized (sBgLock) {
1032                    sBgItemsIdMap.remove(info.id);
1033                    sBgFolders.remove(info.id);
1034                    sBgDbIconCache.remove(info);
1035                    sBgWorkspaceItems.remove(info);
1036                }
1037
1038                cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1039                        LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
1040                // Lock on mBgLock *after* the db operation
1041                synchronized (sBgLock) {
1042                    for (ItemInfo childInfo : info.contents) {
1043                        sBgItemsIdMap.remove(childInfo.id);
1044                        sBgDbIconCache.remove(childInfo);
1045                    }
1046                }
1047            }
1048        };
1049        runOnWorkerThread(r);
1050    }
1051
1052    /**
1053     * Set this as the current Launcher activity object for the loader.
1054     */
1055    public void initialize(Callbacks callbacks) {
1056        synchronized (mLock) {
1057            mCallbacks = new WeakReference<Callbacks>(callbacks);
1058        }
1059    }
1060
1061    /**
1062     * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1063     * ACTION_PACKAGE_CHANGED.
1064     */
1065    @Override
1066    public void onReceive(Context context, Intent intent) {
1067        if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
1068
1069        final String action = intent.getAction();
1070
1071        if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1072                || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1073                || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1074            final String packageName = intent.getData().getSchemeSpecificPart();
1075            final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1076
1077            int op = PackageUpdatedTask.OP_NONE;
1078
1079            if (packageName == null || packageName.length() == 0) {
1080                // they sent us a bad intent
1081                return;
1082            }
1083
1084            if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1085                op = PackageUpdatedTask.OP_UPDATE;
1086            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1087                if (!replacing) {
1088                    op = PackageUpdatedTask.OP_REMOVE;
1089                }
1090                // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1091                // later, we will update the package at this time
1092            } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1093                if (!replacing) {
1094                    op = PackageUpdatedTask.OP_ADD;
1095                } else {
1096                    op = PackageUpdatedTask.OP_UPDATE;
1097                }
1098            }
1099
1100            if (op != PackageUpdatedTask.OP_NONE) {
1101                enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1102            }
1103
1104        } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
1105            // First, schedule to add these apps back in.
1106            String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1107            enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1108            // Then, rebind everything.
1109            startLoaderFromBackground();
1110        } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1111            String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1112            enqueuePackageUpdated(new PackageUpdatedTask(
1113                        PackageUpdatedTask.OP_UNAVAILABLE, packages));
1114        } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
1115            // If we have changed locale we need to clear out the labels in all apps/workspace.
1116            forceReload();
1117        } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1118             // Check if configuration change was an mcc/mnc change which would affect app resources
1119             // and we would need to clear out the labels in all apps/workspace. Same handling as
1120             // above for ACTION_LOCALE_CHANGED
1121             Configuration currentConfig = context.getResources().getConfiguration();
1122             if (mPreviousConfigMcc != currentConfig.mcc) {
1123                   Log.d(TAG, "Reload apps on config change. curr_mcc:"
1124                       + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
1125                   forceReload();
1126             }
1127             // Update previousConfig
1128             mPreviousConfigMcc = currentConfig.mcc;
1129        } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1130                   SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
1131            if (mCallbacks != null) {
1132                Callbacks callbacks = mCallbacks.get();
1133                if (callbacks != null) {
1134                    callbacks.bindSearchablesChanged();
1135                }
1136            }
1137        }
1138    }
1139
1140    private void forceReload() {
1141        resetLoadedState(true, true);
1142
1143        // Do this here because if the launcher activity is running it will be restarted.
1144        // If it's not running startLoaderFromBackground will merely tell it that it needs
1145        // to reload.
1146        startLoaderFromBackground();
1147    }
1148
1149    public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1150        synchronized (mLock) {
1151            // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1152            // mWorkspaceLoaded to true later
1153            stopLoaderLocked();
1154            if (resetAllAppsLoaded) mAllAppsLoaded = false;
1155            if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1156        }
1157    }
1158
1159    /**
1160     * When the launcher is in the background, it's possible for it to miss paired
1161     * configuration changes.  So whenever we trigger the loader from the background
1162     * tell the launcher that it needs to re-run the loader when it comes back instead
1163     * of doing it now.
1164     */
1165    public void startLoaderFromBackground() {
1166        boolean runLoader = false;
1167        if (mCallbacks != null) {
1168            Callbacks callbacks = mCallbacks.get();
1169            if (callbacks != null) {
1170                // Only actually run the loader if they're not paused.
1171                if (!callbacks.setLoadOnResume()) {
1172                    runLoader = true;
1173                }
1174            }
1175        }
1176        if (runLoader) {
1177            startLoader(false, -1);
1178        }
1179    }
1180
1181    // If there is already a loader task running, tell it to stop.
1182    // returns true if isLaunching() was true on the old task
1183    private boolean stopLoaderLocked() {
1184        boolean isLaunching = false;
1185        LoaderTask oldTask = mLoaderTask;
1186        if (oldTask != null) {
1187            if (oldTask.isLaunching()) {
1188                isLaunching = true;
1189            }
1190            oldTask.stopLocked();
1191        }
1192        return isLaunching;
1193    }
1194
1195    public void startLoader(boolean isLaunching, int synchronousBindPage) {
1196        synchronized (mLock) {
1197            if (DEBUG_LOADERS) {
1198                Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1199            }
1200
1201            // Clear any deferred bind-runnables from the synchronized load process
1202            // We must do this before any loading/binding is scheduled below.
1203            mDeferredBindRunnables.clear();
1204
1205            // Don't bother to start the thread if we know it's not going to do anything
1206            if (mCallbacks != null && mCallbacks.get() != null) {
1207                // If there is already one running, tell it to stop.
1208                // also, don't downgrade isLaunching if we're already running
1209                isLaunching = isLaunching || stopLoaderLocked();
1210                mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
1211                if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1212                    mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1213                } else {
1214                    sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1215                    sWorker.post(mLoaderTask);
1216                }
1217            }
1218        }
1219    }
1220
1221    void bindRemainingSynchronousPages() {
1222        // Post the remaining side pages to be loaded
1223        if (!mDeferredBindRunnables.isEmpty()) {
1224            for (final Runnable r : mDeferredBindRunnables) {
1225                mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
1226            }
1227            mDeferredBindRunnables.clear();
1228        }
1229    }
1230
1231    public void stopLoader() {
1232        synchronized (mLock) {
1233            if (mLoaderTask != null) {
1234                mLoaderTask.stopLocked();
1235            }
1236        }
1237    }
1238
1239    public boolean isAllAppsLoaded() {
1240        return mAllAppsLoaded;
1241    }
1242
1243    boolean isLoadingWorkspace() {
1244        synchronized (mLock) {
1245            if (mLoaderTask != null) {
1246                return mLoaderTask.isLoadingWorkspace();
1247            }
1248        }
1249        return false;
1250    }
1251
1252    /**
1253     * Runnable for the thread that loads the contents of the launcher:
1254     *   - workspace icons
1255     *   - widgets
1256     *   - all apps icons
1257     */
1258    private class LoaderTask implements Runnable {
1259        private Context mContext;
1260        private boolean mIsLaunching;
1261        private boolean mIsLoadingAndBindingWorkspace;
1262        private boolean mStopped;
1263        private boolean mLoadAndBindStepFinished;
1264
1265        private HashMap<Object, CharSequence> mLabelCache;
1266
1267        LoaderTask(Context context, boolean isLaunching) {
1268            mContext = context;
1269            mIsLaunching = isLaunching;
1270            mLabelCache = new HashMap<Object, CharSequence>();
1271        }
1272
1273        boolean isLaunching() {
1274            return mIsLaunching;
1275        }
1276
1277        boolean isLoadingWorkspace() {
1278            return mIsLoadingAndBindingWorkspace;
1279        }
1280
1281        /** Returns whether this is an upgrade path */
1282        private boolean loadAndBindWorkspace() {
1283            mIsLoadingAndBindingWorkspace = true;
1284
1285            // Load the workspace
1286            if (DEBUG_LOADERS) {
1287                Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
1288            }
1289
1290            boolean isUpgradePath = false;
1291            if (!mWorkspaceLoaded) {
1292                isUpgradePath = loadWorkspace();
1293                synchronized (LoaderTask.this) {
1294                    if (mStopped) {
1295                        return isUpgradePath;
1296                    }
1297                    mWorkspaceLoaded = true;
1298                }
1299            }
1300
1301            // Bind the workspace
1302            bindWorkspace(-1, isUpgradePath);
1303            return isUpgradePath;
1304        }
1305
1306        private void waitForIdle() {
1307            // Wait until the either we're stopped or the other threads are done.
1308            // This way we don't start loading all apps until the workspace has settled
1309            // down.
1310            synchronized (LoaderTask.this) {
1311                final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1312
1313                mHandler.postIdle(new Runnable() {
1314                        public void run() {
1315                            synchronized (LoaderTask.this) {
1316                                mLoadAndBindStepFinished = true;
1317                                if (DEBUG_LOADERS) {
1318                                    Log.d(TAG, "done with previous binding step");
1319                                }
1320                                LoaderTask.this.notify();
1321                            }
1322                        }
1323                    });
1324
1325                while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
1326                    try {
1327                        // Just in case mFlushingWorkerThread changes but we aren't woken up,
1328                        // wait no longer than 1sec at a time
1329                        this.wait(1000);
1330                    } catch (InterruptedException ex) {
1331                        // Ignore
1332                    }
1333                }
1334                if (DEBUG_LOADERS) {
1335                    Log.d(TAG, "waited "
1336                            + (SystemClock.uptimeMillis()-workspaceWaitTime)
1337                            + "ms for previous step to finish binding");
1338                }
1339            }
1340        }
1341
1342        void runBindSynchronousPage(int synchronousBindPage) {
1343            if (synchronousBindPage < 0) {
1344                // Ensure that we have a valid page index to load synchronously
1345                throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1346                        "valid page index");
1347            }
1348            if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1349                // Ensure that we don't try and bind a specified page when the pages have not been
1350                // loaded already (we should load everything asynchronously in that case)
1351                throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1352            }
1353            synchronized (mLock) {
1354                if (mIsLoaderTaskRunning) {
1355                    // Ensure that we are never running the background loading at this point since
1356                    // we also touch the background collections
1357                    throw new RuntimeException("Error! Background loading is already running");
1358                }
1359            }
1360
1361            // XXX: Throw an exception if we are already loading (since we touch the worker thread
1362            //      data structures, we can't allow any other thread to touch that data, but because
1363            //      this call is synchronous, we can get away with not locking).
1364
1365            // The LauncherModel is static in the LauncherAppState and mHandler may have queued
1366            // operations from the previous activity.  We need to ensure that all queued operations
1367            // are executed before any synchronous binding work is done.
1368            mHandler.flush();
1369
1370            // Divide the set of loaded items into those that we are binding synchronously, and
1371            // everything else that is to be bound normally (asynchronously).
1372            bindWorkspace(synchronousBindPage, false);
1373            // XXX: For now, continue posting the binding of AllApps as there are other issues that
1374            //      arise from that.
1375            onlyBindAllApps();
1376        }
1377
1378        public void run() {
1379            boolean isUpgrade = false;
1380
1381            synchronized (mLock) {
1382                mIsLoaderTaskRunning = true;
1383            }
1384            // Optimize for end-user experience: if the Launcher is up and // running with the
1385            // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1386            // workspace first (default).
1387            final Callbacks cbk = mCallbacks.get();
1388            keep_running: {
1389                // Elevate priority when Home launches for the first time to avoid
1390                // starving at boot time. Staring at a blank home is not cool.
1391                synchronized (mLock) {
1392                    if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1393                            (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
1394                    android.os.Process.setThreadPriority(mIsLaunching
1395                            ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1396                }
1397                if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
1398                isUpgrade = loadAndBindWorkspace();
1399
1400                if (mStopped) {
1401                    break keep_running;
1402                }
1403
1404                // Whew! Hard work done.  Slow us down, and wait until the UI thread has
1405                // settled down.
1406                synchronized (mLock) {
1407                    if (mIsLaunching) {
1408                        if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
1409                        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                    }
1411                }
1412                waitForIdle();
1413
1414                // second step
1415                if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1416                loadAndBindAllApps();
1417
1418                // Restore the default thread priority after we are done loading items
1419                synchronized (mLock) {
1420                    android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1421                }
1422            }
1423
1424            // Update the saved icons if necessary
1425            if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
1426            synchronized (sBgLock) {
1427                for (Object key : sBgDbIconCache.keySet()) {
1428                    updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1429                }
1430                sBgDbIconCache.clear();
1431            }
1432
1433            // Ensure that all the applications that are in the system are represented on the home
1434            // screen.
1435            if (!isUpgrade) {
1436                verifyApplications();
1437            }
1438
1439            // Clear out this reference, otherwise we end up holding it until all of the
1440            // callback runnables are done.
1441            mContext = null;
1442
1443            synchronized (mLock) {
1444                // If we are still the last one to be scheduled, remove ourselves.
1445                if (mLoaderTask == this) {
1446                    mLoaderTask = null;
1447                }
1448                mIsLoaderTaskRunning = false;
1449            }
1450        }
1451
1452        public void stopLocked() {
1453            synchronized (LoaderTask.this) {
1454                mStopped = true;
1455                this.notify();
1456            }
1457        }
1458
1459        /**
1460         * Gets the callbacks object.  If we've been stopped, or if the launcher object
1461         * has somehow been garbage collected, return null instead.  Pass in the Callbacks
1462         * object that was around when the deferred message was scheduled, and if there's
1463         * a new Callbacks object around then also return null.  This will save us from
1464         * calling onto it with data that will be ignored.
1465         */
1466        Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1467            synchronized (mLock) {
1468                if (mStopped) {
1469                    return null;
1470                }
1471
1472                if (mCallbacks == null) {
1473                    return null;
1474                }
1475
1476                final Callbacks callbacks = mCallbacks.get();
1477                if (callbacks != oldCallbacks) {
1478                    return null;
1479                }
1480                if (callbacks == null) {
1481                    Log.w(TAG, "no mCallbacks");
1482                    return null;
1483                }
1484
1485                return callbacks;
1486            }
1487        }
1488
1489        private void verifyApplications() {
1490            final Context context = mApp.getContext();
1491
1492            // Cross reference all the applications in our apps list with items in the workspace
1493            ArrayList<ItemInfo> tmpInfos;
1494            ArrayList<ApplicationInfo> added = new ArrayList<ApplicationInfo>();
1495            synchronized (sBgLock) {
1496                for (ApplicationInfo app : mBgAllAppsList.data) {
1497                    tmpInfos = getItemInfoForComponentName(app.componentName);
1498                    if (tmpInfos.isEmpty()) {
1499                        // We are missing an application icon, so add this to the workspace
1500                        added.add(app);
1501                        // This is a rare event, so lets log it
1502                        Log.e(TAG, "Missing Application on load: " + app);
1503                    }
1504                }
1505            }
1506            if (!added.isEmpty()) {
1507                Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1508                addAndBindAddedApps(context, added, cb);
1509            }
1510        }
1511
1512        // check & update map of what's occupied; used to discard overlapping/invalid items
1513        private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1514            long containerIndex = item.screenId;
1515            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1516                if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1517                    if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1518                            [(int) item.screenId][0] != null) {
1519                        Log.e(TAG, "Error loading shortcut into hotseat " + item
1520                                + " into position (" + item.screenId + ":" + item.cellX + ","
1521                                + item.cellY + ") occupied by "
1522                                + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1523                                [(int) item.screenId][0]);
1524                            return false;
1525                    }
1526                } else {
1527                    ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1528                    items[(int) item.screenId][0] = item;
1529                    occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
1530                    return true;
1531                }
1532            } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1533                // Skip further checking if it is not the hotseat or workspace container
1534                return true;
1535            }
1536
1537            if (!occupied.containsKey(item.screenId)) {
1538                ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1539                occupied.put(item.screenId, items);
1540            }
1541
1542            ItemInfo[][] screens = occupied.get(item.screenId);
1543            // Check if any workspace icons overlap with each other
1544            for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1545                for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
1546                    if (screens[x][y] != null) {
1547                        Log.e(TAG, "Error loading shortcut " + item
1548                            + " into cell (" + containerIndex + "-" + item.screenId + ":"
1549                            + x + "," + y
1550                            + ") occupied by "
1551                            + screens[x][y]);
1552                        return false;
1553                    }
1554                }
1555            }
1556            for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1557                for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
1558                    screens[x][y] = item;
1559                }
1560            }
1561
1562            return true;
1563        }
1564
1565        /** Returns whether this is an upgradge path */
1566        private boolean loadWorkspace() {
1567            final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1568
1569            final Context context = mContext;
1570            final ContentResolver contentResolver = context.getContentResolver();
1571            final PackageManager manager = context.getPackageManager();
1572            final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1573            final boolean isSafeMode = manager.isSafeMode();
1574
1575            // Make sure the default workspace is loaded, if needed
1576            mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1577
1578            // Check if we need to do any upgrade-path logic
1579            boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb();
1580
1581            synchronized (sBgLock) {
1582                sBgWorkspaceItems.clear();
1583                sBgAppWidgets.clear();
1584                sBgFolders.clear();
1585                sBgItemsIdMap.clear();
1586                sBgDbIconCache.clear();
1587                sBgWorkspaceScreens.clear();
1588
1589                final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
1590                final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
1591                final Cursor c = contentResolver.query(contentUri, null, null, null, null);
1592
1593                // +1 for the hotseat (it can be larger than the workspace)
1594                // Load workspace in reverse order to ensure that latest items are loaded first (and
1595                // before any earlier duplicates)
1596                final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
1597
1598                try {
1599                    final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1600                    final int intentIndex = c.getColumnIndexOrThrow
1601                            (LauncherSettings.Favorites.INTENT);
1602                    final int titleIndex = c.getColumnIndexOrThrow
1603                            (LauncherSettings.Favorites.TITLE);
1604                    final int iconTypeIndex = c.getColumnIndexOrThrow(
1605                            LauncherSettings.Favorites.ICON_TYPE);
1606                    final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1607                    final int iconPackageIndex = c.getColumnIndexOrThrow(
1608                            LauncherSettings.Favorites.ICON_PACKAGE);
1609                    final int iconResourceIndex = c.getColumnIndexOrThrow(
1610                            LauncherSettings.Favorites.ICON_RESOURCE);
1611                    final int containerIndex = c.getColumnIndexOrThrow(
1612                            LauncherSettings.Favorites.CONTAINER);
1613                    final int itemTypeIndex = c.getColumnIndexOrThrow(
1614                            LauncherSettings.Favorites.ITEM_TYPE);
1615                    final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1616                            LauncherSettings.Favorites.APPWIDGET_ID);
1617                    final int screenIndex = c.getColumnIndexOrThrow(
1618                            LauncherSettings.Favorites.SCREEN);
1619                    final int cellXIndex = c.getColumnIndexOrThrow
1620                            (LauncherSettings.Favorites.CELLX);
1621                    final int cellYIndex = c.getColumnIndexOrThrow
1622                            (LauncherSettings.Favorites.CELLY);
1623                    final int spanXIndex = c.getColumnIndexOrThrow
1624                            (LauncherSettings.Favorites.SPANX);
1625                    final int spanYIndex = c.getColumnIndexOrThrow(
1626                            LauncherSettings.Favorites.SPANY);
1627                    //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1628                    //final int displayModeIndex = c.getColumnIndexOrThrow(
1629                    //        LauncherSettings.Favorites.DISPLAY_MODE);
1630
1631                    ShortcutInfo info;
1632                    String intentDescription;
1633                    LauncherAppWidgetInfo appWidgetInfo;
1634                    int container;
1635                    long id;
1636                    Intent intent;
1637
1638                    while (!mStopped && c.moveToNext()) {
1639                        try {
1640                            int itemType = c.getInt(itemTypeIndex);
1641
1642                            switch (itemType) {
1643                            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1644                            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1645                                intentDescription = c.getString(intentIndex);
1646                                try {
1647                                    intent = Intent.parseUri(intentDescription, 0);
1648                                } catch (URISyntaxException e) {
1649                                    continue;
1650                                }
1651
1652                                if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1653                                    info = getShortcutInfo(manager, intent, context, c, iconIndex,
1654                                            titleIndex, mLabelCache);
1655                                } else {
1656                                    info = getShortcutInfo(c, context, iconTypeIndex,
1657                                            iconPackageIndex, iconResourceIndex, iconIndex,
1658                                            titleIndex);
1659
1660                                    // App shortcuts that used to be automatically added to Launcher
1661                                    // didn't always have the correct intent flags set, so do that
1662                                    // here
1663                                    if (intent.getAction() != null &&
1664                                        intent.getCategories() != null &&
1665                                        intent.getAction().equals(Intent.ACTION_MAIN) &&
1666                                        intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
1667                                        intent.addFlags(
1668                                            Intent.FLAG_ACTIVITY_NEW_TASK |
1669                                            Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1670                                    }
1671                                }
1672
1673                                if (info != null) {
1674                                    info.intent = intent;
1675                                    info.id = c.getLong(idIndex);
1676                                    container = c.getInt(containerIndex);
1677                                    info.container = container;
1678                                    info.screenId = c.getInt(screenIndex);
1679                                    info.cellX = c.getInt(cellXIndex);
1680                                    info.cellY = c.getInt(cellYIndex);
1681                                    // check & update map of what's occupied
1682                                    if (!checkItemPlacement(occupied, info)) {
1683                                        break;
1684                                    }
1685
1686                                    switch (container) {
1687                                    case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1688                                    case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1689                                        sBgWorkspaceItems.add(info);
1690                                        break;
1691                                    default:
1692                                        // Item is in a user folder
1693                                        FolderInfo folderInfo =
1694                                                findOrMakeFolder(sBgFolders, container);
1695                                        folderInfo.add(info);
1696                                        break;
1697                                    }
1698                                    sBgItemsIdMap.put(info.id, info);
1699
1700                                    // now that we've loaded everthing re-save it with the
1701                                    // icon in case it disappears somehow.
1702                                    queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1703                                } else {
1704                                    // Failed to load the shortcut, probably because the
1705                                    // activity manager couldn't resolve it (maybe the app
1706                                    // was uninstalled), or the db row was somehow screwed up.
1707                                    // Delete it.
1708                                    id = c.getLong(idIndex);
1709                                    Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1710                                    contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1711                                                id, false), null, null);
1712                                }
1713                                break;
1714
1715                            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1716                                id = c.getLong(idIndex);
1717                                FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1718
1719                                folderInfo.title = c.getString(titleIndex);
1720                                folderInfo.id = id;
1721                                container = c.getInt(containerIndex);
1722                                folderInfo.container = container;
1723                                folderInfo.screenId = c.getInt(screenIndex);
1724                                folderInfo.cellX = c.getInt(cellXIndex);
1725                                folderInfo.cellY = c.getInt(cellYIndex);
1726
1727                                // check & update map of what's occupied
1728                                if (!checkItemPlacement(occupied, folderInfo)) {
1729                                    break;
1730                                }
1731                                switch (container) {
1732                                    case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1733                                    case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1734                                        sBgWorkspaceItems.add(folderInfo);
1735                                        break;
1736                                }
1737
1738                                sBgItemsIdMap.put(folderInfo.id, folderInfo);
1739                                sBgFolders.put(folderInfo.id, folderInfo);
1740                                break;
1741
1742                            case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1743                                // Read all Launcher-specific widget details
1744                                int appWidgetId = c.getInt(appWidgetIdIndex);
1745                                id = c.getLong(idIndex);
1746
1747                                final AppWidgetProviderInfo provider =
1748                                        widgets.getAppWidgetInfo(appWidgetId);
1749
1750                                if (!isSafeMode && (provider == null || provider.provider == null ||
1751                                        provider.provider.getPackageName() == null)) {
1752                                    String log = "Deleting widget that isn't installed anymore: id="
1753                                        + id + " appWidgetId=" + appWidgetId;
1754                                    Log.e(TAG, log);
1755                                    Launcher.sDumpLogs.add(log);
1756                                    itemsToRemove.add(id);
1757                                } else {
1758                                    appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1759                                            provider.provider);
1760                                    appWidgetInfo.id = id;
1761                                    appWidgetInfo.screenId = c.getInt(screenIndex);
1762                                    appWidgetInfo.cellX = c.getInt(cellXIndex);
1763                                    appWidgetInfo.cellY = c.getInt(cellYIndex);
1764                                    appWidgetInfo.spanX = c.getInt(spanXIndex);
1765                                    appWidgetInfo.spanY = c.getInt(spanYIndex);
1766                                    int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1767                                    appWidgetInfo.minSpanX = minSpan[0];
1768                                    appWidgetInfo.minSpanY = minSpan[1];
1769
1770                                    container = c.getInt(containerIndex);
1771                                    if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1772                                        container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1773                                        Log.e(TAG, "Widget found where container != " +
1774                                            "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1775                                        continue;
1776                                    }
1777
1778                                    appWidgetInfo.container = c.getInt(containerIndex);
1779                                    // check & update map of what's occupied
1780                                    if (!checkItemPlacement(occupied, appWidgetInfo)) {
1781                                        break;
1782                                    }
1783                                    sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1784                                    sBgAppWidgets.add(appWidgetInfo);
1785                                }
1786                                break;
1787                            }
1788                        } catch (Exception e) {
1789                            Log.w(TAG, "Desktop items loading interrupted:", e);
1790                        }
1791                    }
1792                } finally {
1793                    if (c != null) {
1794                        c.close();
1795                    }
1796                }
1797
1798                if (itemsToRemove.size() > 0) {
1799                    ContentProviderClient client = contentResolver.acquireContentProviderClient(
1800                                    LauncherSettings.Favorites.CONTENT_URI);
1801                    // Remove dead items
1802                    for (long id : itemsToRemove) {
1803                        if (DEBUG_LOADERS) {
1804                            Log.d(TAG, "Removed id = " + id);
1805                        }
1806                        // Don't notify content observers
1807                        try {
1808                            client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1809                                    null, null);
1810                        } catch (RemoteException e) {
1811                            Log.w(TAG, "Could not remove id = " + id);
1812                        }
1813                    }
1814                }
1815
1816                if (loadedOldDb) {
1817                    long maxScreenId = 0;
1818                    // If we're importing we use the old screen order.
1819                    for (ItemInfo item: sBgItemsIdMap.values()) {
1820                        long screenId = item.screenId;
1821                        if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1822                                !sBgWorkspaceScreens.contains(screenId)) {
1823                            sBgWorkspaceScreens.add(screenId);
1824                            if (screenId > maxScreenId) {
1825                                maxScreenId = screenId;
1826                            }
1827                        }
1828                    }
1829                    Collections.sort(sBgWorkspaceScreens);
1830                    mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1831                    updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1832
1833                    // Update the max item id after we load an old db
1834                    long maxItemId = 0;
1835                    // If we're importing we use the old screen order.
1836                    for (ItemInfo item: sBgItemsIdMap.values()) {
1837                        maxItemId = Math.max(maxItemId, item.id);
1838                    }
1839                    LauncherAppState app = LauncherAppState.getInstance();
1840                    app.getLauncherProvider().updateMaxItemId(maxItemId);
1841                } else {
1842                    Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1843                    final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1844                    TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1845
1846                    try {
1847                        final int idIndex = sc.getColumnIndexOrThrow(
1848                                LauncherSettings.WorkspaceScreens._ID);
1849                        final int rankIndex = sc.getColumnIndexOrThrow(
1850                                LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1851                        while (sc.moveToNext()) {
1852                            try {
1853                                long screenId = sc.getLong(idIndex);
1854                                int rank = sc.getInt(rankIndex);
1855
1856                                orderedScreens.put(rank, screenId);
1857                            } catch (Exception e) {
1858                                Log.w(TAG, "Desktop items loading interrupted:", e);
1859                            }
1860                        }
1861                    } finally {
1862                        sc.close();
1863                    }
1864
1865                    Iterator<Integer> iter = orderedScreens.keySet().iterator();
1866                    while (iter.hasNext()) {
1867                        sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1868                    }
1869
1870                    // Remove any empty screens
1871                    ArrayList<Long> unusedScreens = new ArrayList<Long>();
1872                    unusedScreens.addAll(sBgWorkspaceScreens);
1873
1874                    for (ItemInfo item: sBgItemsIdMap.values()) {
1875                        long screenId = item.screenId;
1876
1877                        if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1878                                unusedScreens.contains(screenId)) {
1879                            unusedScreens.remove(screenId);
1880                        }
1881                    }
1882
1883                    // If there are any empty screens remove them, and update.
1884                    if (unusedScreens.size() != 0) {
1885                        sBgWorkspaceScreens.removeAll(unusedScreens);
1886                        updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1887                    }
1888                }
1889
1890                if (DEBUG_LOADERS) {
1891                    Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1892                    Log.d(TAG, "workspace layout: ");
1893                    int nScreens = occupied.size();
1894                    for (int y = 0; y < mCellCountY; y++) {
1895                        String line = "";
1896
1897                        Iterator<Long> iter = occupied.keySet().iterator();
1898                        while (iter.hasNext()) {
1899                            long screenId = iter.next();
1900                            if (screenId > 0) {
1901                                line += " | ";
1902                            }
1903                            for (int x = 0; x < mCellCountX; x++) {
1904                                line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
1905                            }
1906                        }
1907                        Log.d(TAG, "[ " + line + " ]");
1908                    }
1909                }
1910            }
1911            return loadedOldDb;
1912        }
1913
1914        /** Filters the set of items who are directly or indirectly (via another container) on the
1915         * specified screen. */
1916        private void filterCurrentWorkspaceItems(int currentScreen,
1917                ArrayList<ItemInfo> allWorkspaceItems,
1918                ArrayList<ItemInfo> currentScreenItems,
1919                ArrayList<ItemInfo> otherScreenItems) {
1920            // Purge any null ItemInfos
1921            Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1922            while (iter.hasNext()) {
1923                ItemInfo i = iter.next();
1924                if (i == null) {
1925                    iter.remove();
1926                }
1927            }
1928
1929            // If we aren't filtering on a screen, then the set of items to load is the full set of
1930            // items given.
1931            if (currentScreen < 0) {
1932                currentScreenItems.addAll(allWorkspaceItems);
1933            }
1934
1935            // Order the set of items by their containers first, this allows use to walk through the
1936            // list sequentially, build up a list of containers that are in the specified screen,
1937            // as well as all items in those containers.
1938            Set<Long> itemsOnScreen = new HashSet<Long>();
1939            Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1940                @Override
1941                public int compare(ItemInfo lhs, ItemInfo rhs) {
1942                    return (int) (lhs.container - rhs.container);
1943                }
1944            });
1945            for (ItemInfo info : allWorkspaceItems) {
1946                if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1947                    if (info.screenId == currentScreen) {
1948                        currentScreenItems.add(info);
1949                        itemsOnScreen.add(info.id);
1950                    } else {
1951                        otherScreenItems.add(info);
1952                    }
1953                } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1954                    currentScreenItems.add(info);
1955                    itemsOnScreen.add(info.id);
1956                } else {
1957                    if (itemsOnScreen.contains(info.container)) {
1958                        currentScreenItems.add(info);
1959                        itemsOnScreen.add(info.id);
1960                    } else {
1961                        otherScreenItems.add(info);
1962                    }
1963                }
1964            }
1965        }
1966
1967        /** Filters the set of widgets which are on the specified screen. */
1968        private void filterCurrentAppWidgets(int currentScreen,
1969                ArrayList<LauncherAppWidgetInfo> appWidgets,
1970                ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1971                ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1972            // If we aren't filtering on a screen, then the set of items to load is the full set of
1973            // widgets given.
1974            if (currentScreen < 0) {
1975                currentScreenWidgets.addAll(appWidgets);
1976            }
1977
1978            for (LauncherAppWidgetInfo widget : appWidgets) {
1979                if (widget == null) continue;
1980                if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1981                        widget.screenId == currentScreen) {
1982                    currentScreenWidgets.add(widget);
1983                } else {
1984                    otherScreenWidgets.add(widget);
1985                }
1986            }
1987        }
1988
1989        /** Filters the set of folders which are on the specified screen. */
1990        private void filterCurrentFolders(int currentScreen,
1991                HashMap<Long, ItemInfo> itemsIdMap,
1992                HashMap<Long, FolderInfo> folders,
1993                HashMap<Long, FolderInfo> currentScreenFolders,
1994                HashMap<Long, FolderInfo> otherScreenFolders) {
1995            // If we aren't filtering on a screen, then the set of items to load is the full set of
1996            // widgets given.
1997            if (currentScreen < 0) {
1998                currentScreenFolders.putAll(folders);
1999            }
2000
2001            for (long id : folders.keySet()) {
2002                ItemInfo info = itemsIdMap.get(id);
2003                FolderInfo folder = folders.get(id);
2004                if (info == null || folder == null) continue;
2005                if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2006                        info.screenId == currentScreen) {
2007                    currentScreenFolders.put(id, folder);
2008                } else {
2009                    otherScreenFolders.put(id, folder);
2010                }
2011            }
2012        }
2013
2014        /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2015         * right) */
2016        private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
2017            // XXX: review this
2018            Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
2019                @Override
2020                public int compare(ItemInfo lhs, ItemInfo rhs) {
2021                    int cellCountX = LauncherModel.getCellCountX();
2022                    int cellCountY = LauncherModel.getCellCountY();
2023                    int screenOffset = cellCountX * cellCountY;
2024                    int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
2025                    long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
2026                            lhs.cellY * cellCountX + lhs.cellX);
2027                    long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
2028                            rhs.cellY * cellCountX + rhs.cellX);
2029                    return (int) (lr - rr);
2030                }
2031            });
2032        }
2033
2034        private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2035                final ArrayList<Long> orderedScreens) {
2036
2037            final Runnable r = new Runnable() {
2038                @Override
2039                public void run() {
2040                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2041                    if (callbacks != null) {
2042                        callbacks.bindScreens(orderedScreens);
2043                    }
2044                }
2045            };
2046            runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2047        }
2048
2049        private void bindWorkspaceItems(final Callbacks oldCallbacks,
2050                final ArrayList<ItemInfo> workspaceItems,
2051                final ArrayList<LauncherAppWidgetInfo> appWidgets,
2052                final HashMap<Long, FolderInfo> folders,
2053                ArrayList<Runnable> deferredBindRunnables) {
2054
2055            final boolean postOnMainThread = (deferredBindRunnables != null);
2056
2057            // Bind the workspace items
2058            int N = workspaceItems.size();
2059            for (int i = 0; i < N; i += ITEMS_CHUNK) {
2060                final int start = i;
2061                final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
2062                final Runnable r = new Runnable() {
2063                    @Override
2064                    public void run() {
2065                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2066                        if (callbacks != null) {
2067                            callbacks.bindItems(workspaceItems, start, start+chunkSize,
2068                                    false);
2069                        }
2070                    }
2071                };
2072                if (postOnMainThread) {
2073                    deferredBindRunnables.add(r);
2074                } else {
2075                    runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2076                }
2077            }
2078
2079            // Bind the folders
2080            if (!folders.isEmpty()) {
2081                final Runnable r = new Runnable() {
2082                    public void run() {
2083                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2084                        if (callbacks != null) {
2085                            callbacks.bindFolders(folders);
2086                        }
2087                    }
2088                };
2089                if (postOnMainThread) {
2090                    deferredBindRunnables.add(r);
2091                } else {
2092                    runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2093                }
2094            }
2095
2096            // Bind the widgets, one at a time
2097            N = appWidgets.size();
2098            for (int i = 0; i < N; i++) {
2099                final LauncherAppWidgetInfo widget = appWidgets.get(i);
2100                final Runnable r = new Runnable() {
2101                    public void run() {
2102                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2103                        if (callbacks != null) {
2104                            callbacks.bindAppWidget(widget);
2105                        }
2106                    }
2107                };
2108                if (postOnMainThread) {
2109                    deferredBindRunnables.add(r);
2110                } else {
2111                    runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2112                }
2113            }
2114        }
2115
2116        /**
2117         * Binds all loaded data to actual views on the main thread.
2118         */
2119        private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
2120            final long t = SystemClock.uptimeMillis();
2121            Runnable r;
2122
2123            // Don't use these two variables in any of the callback runnables.
2124            // Otherwise we hold a reference to them.
2125            final Callbacks oldCallbacks = mCallbacks.get();
2126            if (oldCallbacks == null) {
2127                // This launcher has exited and nobody bothered to tell us.  Just bail.
2128                Log.w(TAG, "LoaderTask running with no launcher");
2129                return;
2130            }
2131
2132            final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2133            final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
2134                oldCallbacks.getCurrentWorkspaceScreen();
2135
2136            // Load all the items that are on the current page first (and in the process, unbind
2137            // all the existing workspace items before we call startBinding() below.
2138            unbindWorkspaceItemsOnMainThread();
2139            ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2140            ArrayList<LauncherAppWidgetInfo> appWidgets =
2141                    new ArrayList<LauncherAppWidgetInfo>();
2142            HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2143            HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
2144            ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
2145            synchronized (sBgLock) {
2146                workspaceItems.addAll(sBgWorkspaceItems);
2147                appWidgets.addAll(sBgAppWidgets);
2148                folders.putAll(sBgFolders);
2149                itemsIdMap.putAll(sBgItemsIdMap);
2150                orderedScreenIds.addAll(sBgWorkspaceScreens);
2151            }
2152
2153            ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2154            ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2155            ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2156                    new ArrayList<LauncherAppWidgetInfo>();
2157            ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2158                    new ArrayList<LauncherAppWidgetInfo>();
2159            HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2160            HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2161
2162            // Separate the items that are on the current screen, and all the other remaining items
2163            filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2164                    otherWorkspaceItems);
2165            filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2166                    otherAppWidgets);
2167            filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2168                    otherFolders);
2169            sortWorkspaceItemsSpatially(currentWorkspaceItems);
2170            sortWorkspaceItemsSpatially(otherWorkspaceItems);
2171
2172            // Tell the workspace that we're about to start binding items
2173            r = new Runnable() {
2174                public void run() {
2175                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2176                    if (callbacks != null) {
2177                        callbacks.startBinding();
2178                    }
2179                }
2180            };
2181            runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2182
2183            bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2184
2185            // Load items on the current page
2186            bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2187                    currentFolders, null);
2188            if (isLoadingSynchronously) {
2189                r = new Runnable() {
2190                    public void run() {
2191                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2192                        if (callbacks != null) {
2193                            callbacks.onPageBoundSynchronously(currentScreen);
2194                        }
2195                    }
2196                };
2197                runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2198            }
2199
2200            // Load all the remaining pages (if we are loading synchronously, we want to defer this
2201            // work until after the first render)
2202            mDeferredBindRunnables.clear();
2203            bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
2204                    (isLoadingSynchronously ? mDeferredBindRunnables : null));
2205
2206            // Tell the workspace that we're done binding items
2207            r = new Runnable() {
2208                public void run() {
2209                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2210                    if (callbacks != null) {
2211                        callbacks.finishBindingItems(isUpgradePath);
2212                    }
2213
2214                    // If we're profiling, ensure this is the last thing in the queue.
2215                    if (DEBUG_LOADERS) {
2216                        Log.d(TAG, "bound workspace in "
2217                            + (SystemClock.uptimeMillis()-t) + "ms");
2218                    }
2219
2220                    mIsLoadingAndBindingWorkspace = false;
2221                }
2222            };
2223            if (isLoadingSynchronously) {
2224                mDeferredBindRunnables.add(r);
2225            } else {
2226                runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2227            }
2228        }
2229
2230        private void loadAndBindAllApps() {
2231            if (DEBUG_LOADERS) {
2232                Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2233            }
2234            if (!mAllAppsLoaded) {
2235                loadAllApps();
2236                synchronized (LoaderTask.this) {
2237                    if (mStopped) {
2238                        return;
2239                    }
2240                    mAllAppsLoaded = true;
2241                }
2242            } else {
2243                onlyBindAllApps();
2244            }
2245        }
2246
2247        private void onlyBindAllApps() {
2248            final Callbacks oldCallbacks = mCallbacks.get();
2249            if (oldCallbacks == null) {
2250                // This launcher has exited and nobody bothered to tell us.  Just bail.
2251                Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2252                return;
2253            }
2254
2255            // shallow copy
2256            @SuppressWarnings("unchecked")
2257            final ArrayList<ApplicationInfo> list
2258                    = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
2259            Runnable r = new Runnable() {
2260                public void run() {
2261                    final long t = SystemClock.uptimeMillis();
2262                    final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2263                    if (callbacks != null) {
2264                        callbacks.bindAllApplications(list);
2265                    }
2266                    if (DEBUG_LOADERS) {
2267                        Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2268                                + (SystemClock.uptimeMillis()-t) + "ms");
2269                    }
2270                }
2271            };
2272            boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
2273            if (isRunningOnMainThread) {
2274                r.run();
2275            } else {
2276                mHandler.post(r);
2277            }
2278        }
2279
2280        private void loadAllApps() {
2281            final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2282
2283            // Don't use these two variables in any of the callback runnables.
2284            // Otherwise we hold a reference to them.
2285            final Callbacks oldCallbacks = mCallbacks.get();
2286            if (oldCallbacks == null) {
2287                // This launcher has exited and nobody bothered to tell us.  Just bail.
2288                Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
2289                return;
2290            }
2291
2292            final PackageManager packageManager = mContext.getPackageManager();
2293            final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2294            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2295
2296            // Clear the list of apps
2297            mBgAllAppsList.clear();
2298
2299            // Query for the set of apps
2300            final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2301            List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2302            if (DEBUG_LOADERS) {
2303                Log.d(TAG, "queryIntentActivities took "
2304                        + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2305                Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2306            }
2307            // Fail if we don't have any apps
2308            if (apps == null || apps.isEmpty()) {
2309                return;
2310            }
2311            // Sort the applications by name
2312            final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2313            Collections.sort(apps,
2314                    new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2315            if (DEBUG_LOADERS) {
2316                Log.d(TAG, "sort took "
2317                        + (SystemClock.uptimeMillis()-sortTime) + "ms");
2318            }
2319
2320            // Create the ApplicationInfos
2321            final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2322            for (int i = 0; i < apps.size(); i++) {
2323                // This builds the icon bitmaps.
2324                mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2325                        mIconCache, mLabelCache));
2326            }
2327
2328            final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2329            final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2330            mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2331
2332            // Post callback on main thread
2333            mHandler.post(new Runnable() {
2334                public void run() {
2335                    final long bindTime = SystemClock.uptimeMillis();
2336                    if (callbacks != null) {
2337                        callbacks.bindAllApplications(added);
2338                        if (DEBUG_LOADERS) {
2339                            Log.d(TAG, "bound " + added.size() + " apps in "
2340                                + (SystemClock.uptimeMillis() - bindTime) + "ms");
2341                        }
2342                    } else {
2343                        Log.i(TAG, "not binding apps: no Launcher activity");
2344                    }
2345                }
2346            });
2347
2348            if (DEBUG_LOADERS) {
2349                Log.d(TAG, "Icons processed in "
2350                        + (SystemClock.uptimeMillis() - loadTime) + "ms");
2351            }
2352        }
2353
2354        public void dumpState() {
2355            synchronized (sBgLock) {
2356                Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2357                Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2358                Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2359                Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2360                Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2361            }
2362        }
2363    }
2364
2365    void enqueuePackageUpdated(PackageUpdatedTask task) {
2366        sWorker.post(task);
2367    }
2368
2369    private class PackageUpdatedTask implements Runnable {
2370        int mOp;
2371        String[] mPackages;
2372
2373        public static final int OP_NONE = 0;
2374        public static final int OP_ADD = 1;
2375        public static final int OP_UPDATE = 2;
2376        public static final int OP_REMOVE = 3; // uninstlled
2377        public static final int OP_UNAVAILABLE = 4; // external media unmounted
2378
2379
2380        public PackageUpdatedTask(int op, String[] packages) {
2381            mOp = op;
2382            mPackages = packages;
2383        }
2384
2385        public void run() {
2386            final Context context = mApp.getContext();
2387
2388            final String[] packages = mPackages;
2389            final int N = packages.length;
2390            switch (mOp) {
2391                case OP_ADD:
2392                    for (int i=0; i<N; i++) {
2393                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
2394                        mBgAllAppsList.addPackage(context, packages[i]);
2395                    }
2396                    break;
2397                case OP_UPDATE:
2398                    for (int i=0; i<N; i++) {
2399                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
2400                        mBgAllAppsList.updatePackage(context, packages[i]);
2401                        WidgetPreviewLoader.removeFromDb(
2402                                mApp.getWidgetPreviewCacheDb(), packages[i]);
2403                    }
2404                    break;
2405                case OP_REMOVE:
2406                case OP_UNAVAILABLE:
2407                    for (int i=0; i<N; i++) {
2408                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
2409                        mBgAllAppsList.removePackage(packages[i]);
2410                        WidgetPreviewLoader.removeFromDb(
2411                                mApp.getWidgetPreviewCacheDb(), packages[i]);
2412                    }
2413                    break;
2414            }
2415
2416            ArrayList<ApplicationInfo> added = null;
2417            ArrayList<ApplicationInfo> modified = null;
2418            final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
2419
2420            if (mBgAllAppsList.added.size() > 0) {
2421                added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2422                mBgAllAppsList.added.clear();
2423            }
2424            if (mBgAllAppsList.modified.size() > 0) {
2425                modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2426                mBgAllAppsList.modified.clear();
2427            }
2428            if (mBgAllAppsList.removed.size() > 0) {
2429                removedApps.addAll(mBgAllAppsList.removed);
2430                mBgAllAppsList.removed.clear();
2431            }
2432
2433            final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2434            if (callbacks == null) {
2435                Log.w(TAG, "Nobody to tell about the new app.  Launcher is probably loading.");
2436                return;
2437            }
2438
2439            if (added != null) {
2440                // Ensure that we add all the workspace applications to the db
2441                final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
2442                Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2443                addAndBindAddedApps(context, addedInfos, cb);
2444            }
2445            if (modified != null) {
2446                final ArrayList<ApplicationInfo> modifiedFinal = modified;
2447
2448                // Update the launcher db to reflect the changes
2449                for (ApplicationInfo a : modifiedFinal) {
2450                    ArrayList<ItemInfo> infos =
2451                            getItemInfoForComponentName(a.componentName);
2452                    for (ItemInfo i : infos) {
2453                        if (isShortcutInfoUpdateable(i)) {
2454                            ShortcutInfo info = (ShortcutInfo) i;
2455                            info.title = a.title.toString();
2456                            updateItemInDatabase(context, info);
2457                        }
2458                    }
2459                }
2460
2461                mHandler.post(new Runnable() {
2462                    public void run() {
2463                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2464                        if (callbacks == cb && cb != null) {
2465                            callbacks.bindAppsUpdated(modifiedFinal);
2466                        }
2467                    }
2468                });
2469            }
2470            // If a package has been removed, or an app has been removed as a result of
2471            // an update (for example), make the removed callback.
2472            if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
2473                final boolean packageRemoved = (mOp == OP_REMOVE);
2474                final ArrayList<String> removedPackageNames =
2475                        new ArrayList<String>(Arrays.asList(packages));
2476
2477                // Update the launcher db to reflect the removal of apps
2478                if (packageRemoved) {
2479                    for (String pn : removedPackageNames) {
2480                        ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2481                        for (ItemInfo i : infos) {
2482                            deleteItemFromDatabase(context, i);
2483                        }
2484                    }
2485                } else {
2486                    for (ApplicationInfo a : removedApps) {
2487                        ArrayList<ItemInfo> infos =
2488                                getItemInfoForComponentName(a.componentName);
2489                        for (ItemInfo i : infos) {
2490                            deleteItemFromDatabase(context, i);
2491                        }
2492                    }
2493                }
2494
2495                mHandler.post(new Runnable() {
2496                    public void run() {
2497                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2498                        if (callbacks == cb && cb != null) {
2499                            callbacks.bindComponentsRemoved(removedPackageNames,
2500                                    removedApps, packageRemoved);
2501                        }
2502                    }
2503                });
2504            }
2505
2506            final ArrayList<Object> widgetsAndShortcuts =
2507                getSortedWidgetsAndShortcuts(context);
2508            mHandler.post(new Runnable() {
2509                @Override
2510                public void run() {
2511                    Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2512                    if (callbacks == cb && cb != null) {
2513                        callbacks.bindPackagesUpdated(widgetsAndShortcuts);
2514                    }
2515                }
2516            });
2517        }
2518    }
2519
2520    // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2521    public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2522        PackageManager packageManager = context.getPackageManager();
2523        final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2524        widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2525        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2526        widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2527        Collections.sort(widgetsAndShortcuts,
2528            new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2529        return widgetsAndShortcuts;
2530    }
2531
2532    /**
2533     * This is called from the code that adds shortcuts from the intent receiver.  This
2534     * doesn't have a Cursor, but
2535     */
2536    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
2537        return getShortcutInfo(manager, intent, context, null, -1, -1, null);
2538    }
2539
2540    /**
2541     * Make an ShortcutInfo object for a shortcut that is an application.
2542     *
2543     * If c is not null, then it will be used to fill in missing data like the title and icon.
2544     */
2545    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
2546            Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
2547        Bitmap icon = null;
2548        final ShortcutInfo info = new ShortcutInfo();
2549
2550        ComponentName componentName = intent.getComponent();
2551        if (componentName == null) {
2552            return null;
2553        }
2554
2555        try {
2556            PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2557            if (!pi.applicationInfo.enabled) {
2558                // If we return null here, the corresponding item will be removed from the launcher
2559                // db and will not appear in the workspace.
2560                return null;
2561            }
2562            info.initFlagsAndFirstInstallTime(pi);
2563        } catch (NameNotFoundException e) {
2564            Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
2565        }
2566
2567        // TODO: See if the PackageManager knows about this case.  If it doesn't
2568        // then return null & delete this.
2569
2570        // the resource -- This may implicitly give us back the fallback icon,
2571        // but don't worry about that.  All we're doing with usingFallbackIcon is
2572        // to avoid saving lots of copies of that in the database, and most apps
2573        // have icons anyway.
2574
2575        // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2576        // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2577        // via resolveActivity().
2578        ResolveInfo resolveInfo = null;
2579        ComponentName oldComponent = intent.getComponent();
2580        Intent newIntent = new Intent(intent.getAction(), null);
2581        newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2582        newIntent.setPackage(oldComponent.getPackageName());
2583        List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2584        for (ResolveInfo i : infos) {
2585            ComponentName cn = new ComponentName(i.activityInfo.packageName,
2586                    i.activityInfo.name);
2587            if (cn.equals(oldComponent)) {
2588                resolveInfo = i;
2589            }
2590        }
2591        if (resolveInfo == null) {
2592            resolveInfo = manager.resolveActivity(intent, 0);
2593        }
2594        if (resolveInfo != null) {
2595            icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
2596        }
2597        // the db
2598        if (icon == null) {
2599            if (c != null) {
2600                icon = getIconFromCursor(c, iconIndex, context);
2601            }
2602        }
2603        // the fallback icon
2604        if (icon == null) {
2605            icon = getFallbackIcon();
2606            info.usingFallbackIcon = true;
2607        }
2608        info.setIcon(icon);
2609
2610        // from the resource
2611        if (resolveInfo != null) {
2612            ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2613            if (labelCache != null && labelCache.containsKey(key)) {
2614                info.title = labelCache.get(key);
2615            } else {
2616                info.title = resolveInfo.activityInfo.loadLabel(manager);
2617                if (labelCache != null) {
2618                    labelCache.put(key, info.title);
2619                }
2620            }
2621        }
2622        // from the db
2623        if (info.title == null) {
2624            if (c != null) {
2625                info.title =  c.getString(titleIndex);
2626            }
2627        }
2628        // fall back to the class name of the activity
2629        if (info.title == null) {
2630            info.title = componentName.getClassName();
2631        }
2632        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2633        return info;
2634    }
2635
2636    static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2637            ItemInfoFilter f) {
2638        HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2639        for (ItemInfo i : infos) {
2640            if (i instanceof ShortcutInfo) {
2641                ShortcutInfo info = (ShortcutInfo) i;
2642                ComponentName cn = info.intent.getComponent();
2643                if (cn != null && f.filterItem(null, info, cn)) {
2644                    filtered.add(info);
2645                }
2646            } else if (i instanceof FolderInfo) {
2647                FolderInfo info = (FolderInfo) i;
2648                for (ShortcutInfo s : info.contents) {
2649                    ComponentName cn = s.intent.getComponent();
2650                    if (cn != null && f.filterItem(info, s, cn)) {
2651                        filtered.add(s);
2652                    }
2653                }
2654            } else if (i instanceof LauncherAppWidgetInfo) {
2655                LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2656                ComponentName cn = info.providerName;
2657                if (cn != null && f.filterItem(null, info, cn)) {
2658                    filtered.add(info);
2659                }
2660            }
2661        }
2662        return new ArrayList<ItemInfo>(filtered);
2663    }
2664
2665    private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2666        HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2667        ItemInfoFilter filter  = new ItemInfoFilter() {
2668            @Override
2669            public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2670                return cn.getPackageName().equals(pn);
2671            }
2672        };
2673        return filterItemInfos(sBgItemsIdMap.values(), filter);
2674    }
2675
2676    private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2677        HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2678        ItemInfoFilter filter  = new ItemInfoFilter() {
2679            @Override
2680            public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2681                return cn.equals(cname);
2682            }
2683        };
2684        return filterItemInfos(sBgItemsIdMap.values(), filter);
2685    }
2686
2687    public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2688        if (i instanceof ShortcutInfo) {
2689            ShortcutInfo info = (ShortcutInfo) i;
2690            // We need to check for ACTION_MAIN otherwise getComponent() might
2691            // return null for some shortcuts (for instance, for shortcuts to
2692            // web pages.)
2693            Intent intent = info.intent;
2694            ComponentName name = intent.getComponent();
2695            if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2696                    Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2697                return true;
2698            }
2699        }
2700        return false;
2701    }
2702
2703    /**
2704     * Make an ShortcutInfo object for a shortcut that isn't an application.
2705     */
2706    private ShortcutInfo getShortcutInfo(Cursor c, Context context,
2707            int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2708            int titleIndex) {
2709
2710        Bitmap icon = null;
2711        final ShortcutInfo info = new ShortcutInfo();
2712        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
2713
2714        // TODO: If there's an explicit component and we can't install that, delete it.
2715
2716        info.title = c.getString(titleIndex);
2717
2718        int iconType = c.getInt(iconTypeIndex);
2719        switch (iconType) {
2720        case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2721            String packageName = c.getString(iconPackageIndex);
2722            String resourceName = c.getString(iconResourceIndex);
2723            PackageManager packageManager = context.getPackageManager();
2724            info.customIcon = false;
2725            // the resource
2726            try {
2727                Resources resources = packageManager.getResourcesForApplication(packageName);
2728                if (resources != null) {
2729                    final int id = resources.getIdentifier(resourceName, null, null);
2730                    icon = Utilities.createIconBitmap(
2731                            mIconCache.getFullResIcon(resources, id), context);
2732                }
2733            } catch (Exception e) {
2734                // drop this.  we have other places to look for icons
2735            }
2736            // the db
2737            if (icon == null) {
2738                icon = getIconFromCursor(c, iconIndex, context);
2739            }
2740            // the fallback icon
2741            if (icon == null) {
2742                icon = getFallbackIcon();
2743                info.usingFallbackIcon = true;
2744            }
2745            break;
2746        case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
2747            icon = getIconFromCursor(c, iconIndex, context);
2748            if (icon == null) {
2749                icon = getFallbackIcon();
2750                info.customIcon = false;
2751                info.usingFallbackIcon = true;
2752            } else {
2753                info.customIcon = true;
2754            }
2755            break;
2756        default:
2757            icon = getFallbackIcon();
2758            info.usingFallbackIcon = true;
2759            info.customIcon = false;
2760            break;
2761        }
2762        info.setIcon(icon);
2763        return info;
2764    }
2765
2766    Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
2767        @SuppressWarnings("all") // suppress dead code warning
2768        final boolean debug = false;
2769        if (debug) {
2770            Log.d(TAG, "getIconFromCursor app="
2771                    + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2772        }
2773        byte[] data = c.getBlob(iconIndex);
2774        try {
2775            return Utilities.createIconBitmap(
2776                    BitmapFactory.decodeByteArray(data, 0, data.length), context);
2777        } catch (Exception e) {
2778            return null;
2779        }
2780    }
2781
2782    ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2783            int cellX, int cellY, boolean notify) {
2784        final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
2785        if (info == null) {
2786            return null;
2787        }
2788        addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
2789
2790        return info;
2791    }
2792
2793    /**
2794     * Attempts to find an AppWidgetProviderInfo that matches the given component.
2795     */
2796    AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2797            ComponentName component) {
2798        List<AppWidgetProviderInfo> widgets =
2799            AppWidgetManager.getInstance(context).getInstalledProviders();
2800        for (AppWidgetProviderInfo info : widgets) {
2801            if (info.provider.equals(component)) {
2802                return info;
2803            }
2804        }
2805        return null;
2806    }
2807
2808    /**
2809     * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2810     */
2811    List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2812        final PackageManager packageManager = context.getPackageManager();
2813        final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2814            new ArrayList<WidgetMimeTypeHandlerData>();
2815
2816        final Intent supportsIntent =
2817            new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2818        supportsIntent.setType(mimeType);
2819
2820        // Create a set of widget configuration components that we can test against
2821        final List<AppWidgetProviderInfo> widgets =
2822            AppWidgetManager.getInstance(context).getInstalledProviders();
2823        final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2824            new HashMap<ComponentName, AppWidgetProviderInfo>();
2825        for (AppWidgetProviderInfo info : widgets) {
2826            configurationComponentToWidget.put(info.configure, info);
2827        }
2828
2829        // Run through each of the intents that can handle this type of clip data, and cross
2830        // reference them with the components that are actual configuration components
2831        final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2832                PackageManager.MATCH_DEFAULT_ONLY);
2833        for (ResolveInfo info : activities) {
2834            final ActivityInfo activityInfo = info.activityInfo;
2835            final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2836                    activityInfo.name);
2837            if (configurationComponentToWidget.containsKey(infoComponent)) {
2838                supportedConfigurationActivities.add(
2839                        new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2840                                configurationComponentToWidget.get(infoComponent)));
2841            }
2842        }
2843        return supportedConfigurationActivities;
2844    }
2845
2846    ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
2847        Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2848        String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2849        Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2850
2851        if (intent == null) {
2852            // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2853            Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2854            return null;
2855        }
2856
2857        Bitmap icon = null;
2858        boolean customIcon = false;
2859        ShortcutIconResource iconResource = null;
2860
2861        if (bitmap != null && bitmap instanceof Bitmap) {
2862            icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
2863            customIcon = true;
2864        } else {
2865            Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2866            if (extra != null && extra instanceof ShortcutIconResource) {
2867                try {
2868                    iconResource = (ShortcutIconResource) extra;
2869                    final PackageManager packageManager = context.getPackageManager();
2870                    Resources resources = packageManager.getResourcesForApplication(
2871                            iconResource.packageName);
2872                    final int id = resources.getIdentifier(iconResource.resourceName, null, null);
2873                    icon = Utilities.createIconBitmap(
2874                            mIconCache.getFullResIcon(resources, id), context);
2875                } catch (Exception e) {
2876                    Log.w(TAG, "Could not load shortcut icon: " + extra);
2877                }
2878            }
2879        }
2880
2881        final ShortcutInfo info = new ShortcutInfo();
2882
2883        if (icon == null) {
2884            if (fallbackIcon != null) {
2885                icon = fallbackIcon;
2886            } else {
2887                icon = getFallbackIcon();
2888                info.usingFallbackIcon = true;
2889            }
2890        }
2891        info.setIcon(icon);
2892
2893        info.title = name;
2894        info.intent = intent;
2895        info.customIcon = customIcon;
2896        info.iconResource = iconResource;
2897
2898        return info;
2899    }
2900
2901    boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2902            int iconIndex) {
2903        // If apps can't be on SD, don't even bother.
2904        if (!mAppsCanBeOnExternalStorage) {
2905            return false;
2906        }
2907        // If this icon doesn't have a custom icon, check to see
2908        // what's stored in the DB, and if it doesn't match what
2909        // we're going to show, store what we are going to show back
2910        // into the DB.  We do this so when we're loading, if the
2911        // package manager can't find an icon (for example because
2912        // the app is on SD) then we can use that instead.
2913        if (!info.customIcon && !info.usingFallbackIcon) {
2914            cache.put(info, c.getBlob(iconIndex));
2915            return true;
2916        }
2917        return false;
2918    }
2919    void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2920        boolean needSave = false;
2921        try {
2922            if (data != null) {
2923                Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2924                Bitmap loaded = info.getIcon(mIconCache);
2925                needSave = !saved.sameAs(loaded);
2926            } else {
2927                needSave = true;
2928            }
2929        } catch (Exception e) {
2930            needSave = true;
2931        }
2932        if (needSave) {
2933            Log.d(TAG, "going to save icon bitmap for info=" + info);
2934            // This is slower than is ideal, but this only happens once
2935            // or when the app is updated with a new icon.
2936            updateItemInDatabase(context, info);
2937        }
2938    }
2939
2940    /**
2941     * Return an existing FolderInfo object if we have encountered this ID previously,
2942     * or make a new one.
2943     */
2944    private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
2945        // See if a placeholder was created for us already
2946        FolderInfo folderInfo = folders.get(id);
2947        if (folderInfo == null) {
2948            // No placeholder -- create a new instance
2949            folderInfo = new FolderInfo();
2950            folders.put(id, folderInfo);
2951        }
2952        return folderInfo;
2953    }
2954
2955    public static final Comparator<ApplicationInfo> getAppNameComparator() {
2956        final Collator collator = Collator.getInstance();
2957        return new Comparator<ApplicationInfo>() {
2958            public final int compare(ApplicationInfo a, ApplicationInfo b) {
2959                int result = collator.compare(a.title.toString(), b.title.toString());
2960                if (result == 0) {
2961                    result = a.componentName.compareTo(b.componentName);
2962                }
2963                return result;
2964            }
2965        };
2966    }
2967    public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2968            = new Comparator<ApplicationInfo>() {
2969        public final int compare(ApplicationInfo a, ApplicationInfo b) {
2970            if (a.firstInstallTime < b.firstInstallTime) return 1;
2971            if (a.firstInstallTime > b.firstInstallTime) return -1;
2972            return 0;
2973        }
2974    };
2975    public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2976        final Collator collator = Collator.getInstance();
2977        return new Comparator<AppWidgetProviderInfo>() {
2978            public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2979                return collator.compare(a.label.toString(), b.label.toString());
2980            }
2981        };
2982    }
2983    static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2984        if (info.activityInfo != null) {
2985            return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2986        } else {
2987            return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2988        }
2989    }
2990    public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
2991        private Collator mCollator;
2992        private PackageManager mPackageManager;
2993        private HashMap<Object, CharSequence> mLabelCache;
2994        ShortcutNameComparator(PackageManager pm) {
2995            mPackageManager = pm;
2996            mLabelCache = new HashMap<Object, CharSequence>();
2997            mCollator = Collator.getInstance();
2998        }
2999        ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3000            mPackageManager = pm;
3001            mLabelCache = labelCache;
3002            mCollator = Collator.getInstance();
3003        }
3004        public final int compare(ResolveInfo a, ResolveInfo b) {
3005            CharSequence labelA, labelB;
3006            ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3007            ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3008            if (mLabelCache.containsKey(keyA)) {
3009                labelA = mLabelCache.get(keyA);
3010            } else {
3011                labelA = a.loadLabel(mPackageManager).toString();
3012
3013                mLabelCache.put(keyA, labelA);
3014            }
3015            if (mLabelCache.containsKey(keyB)) {
3016                labelB = mLabelCache.get(keyB);
3017            } else {
3018                labelB = b.loadLabel(mPackageManager).toString();
3019
3020                mLabelCache.put(keyB, labelB);
3021            }
3022            return mCollator.compare(labelA, labelB);
3023        }
3024    };
3025    public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
3026        private Collator mCollator;
3027        private PackageManager mPackageManager;
3028        private HashMap<Object, String> mLabelCache;
3029        WidgetAndShortcutNameComparator(PackageManager pm) {
3030            mPackageManager = pm;
3031            mLabelCache = new HashMap<Object, String>();
3032            mCollator = Collator.getInstance();
3033        }
3034        public final int compare(Object a, Object b) {
3035            String labelA, labelB;
3036            if (mLabelCache.containsKey(a)) {
3037                labelA = mLabelCache.get(a);
3038            } else {
3039                labelA = (a instanceof AppWidgetProviderInfo) ?
3040                    ((AppWidgetProviderInfo) a).label :
3041                    ((ResolveInfo) a).loadLabel(mPackageManager).toString();
3042                mLabelCache.put(a, labelA);
3043            }
3044            if (mLabelCache.containsKey(b)) {
3045                labelB = mLabelCache.get(b);
3046            } else {
3047                labelB = (b instanceof AppWidgetProviderInfo) ?
3048                    ((AppWidgetProviderInfo) b).label :
3049                    ((ResolveInfo) b).loadLabel(mPackageManager).toString();
3050                mLabelCache.put(b, labelB);
3051            }
3052            return mCollator.compare(labelA, labelB);
3053        }
3054    };
3055
3056    public void dumpState() {
3057        Log.d(TAG, "mCallbacks=" + mCallbacks);
3058        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3059        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3060        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3061        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
3062        if (mLoaderTask != null) {
3063            mLoaderTask.dumpState();
3064        } else {
3065            Log.d(TAG, "mLoaderTask=null");
3066        }
3067    }
3068}
3069