LauncherModel.java revision 1323b4856a2a822af77293cadeda9910a5d1ba0e
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 mAppsCanBeOnRemoveableStorage;
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        mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
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<ItemInfo> added = new ArrayList<ItemInfo>();
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                                id = c.getLong(idIndex);
1646                                intentDescription = c.getString(intentIndex);
1647                                try {
1648                                    intent = Intent.parseUri(intentDescription, 0);
1649                                    ComponentName cn = intent.getComponent();
1650                                    if (!isValidPackageComponent(manager, cn)) {
1651                                        if (!mAppsCanBeOnRemoveableStorage) {
1652                                            // Log the invalid package, and remove it from the db
1653                                            Uri uri = LauncherSettings.Favorites.getContentUri(id,
1654                                                    false);
1655                                            contentResolver.delete(uri, null, null);
1656                                            Log.e(TAG, "Invalid package removed: " + cn);
1657                                        } else {
1658                                            // If apps can be on external storage, then we just
1659                                            // leave them for the user to remove (maybe add
1660                                            // visual treatment to it)
1661                                            Log.e(TAG, "Invalid package found: " + cn);
1662                                        }
1663                                        continue;
1664                                    }
1665                                } catch (URISyntaxException e) {
1666                                    continue;
1667                                }
1668
1669                                if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1670                                    info = getShortcutInfo(manager, intent, context, c, iconIndex,
1671                                            titleIndex, mLabelCache);
1672                                } else {
1673                                    info = getShortcutInfo(c, context, iconTypeIndex,
1674                                            iconPackageIndex, iconResourceIndex, iconIndex,
1675                                            titleIndex);
1676
1677                                    // App shortcuts that used to be automatically added to Launcher
1678                                    // didn't always have the correct intent flags set, so do that
1679                                    // here
1680                                    if (intent.getAction() != null &&
1681                                        intent.getCategories() != null &&
1682                                        intent.getAction().equals(Intent.ACTION_MAIN) &&
1683                                        intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
1684                                        intent.addFlags(
1685                                            Intent.FLAG_ACTIVITY_NEW_TASK |
1686                                            Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1687                                    }
1688                                }
1689
1690                                if (info != null) {
1691                                    info.id = id;
1692                                    info.intent = intent;
1693                                    container = c.getInt(containerIndex);
1694                                    info.container = container;
1695                                    info.screenId = c.getInt(screenIndex);
1696                                    info.cellX = c.getInt(cellXIndex);
1697                                    info.cellY = c.getInt(cellYIndex);
1698                                    // check & update map of what's occupied
1699                                    if (!checkItemPlacement(occupied, info)) {
1700                                        break;
1701                                    }
1702
1703                                    switch (container) {
1704                                    case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1705                                    case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1706                                        sBgWorkspaceItems.add(info);
1707                                        break;
1708                                    default:
1709                                        // Item is in a user folder
1710                                        FolderInfo folderInfo =
1711                                                findOrMakeFolder(sBgFolders, container);
1712                                        folderInfo.add(info);
1713                                        break;
1714                                    }
1715                                    sBgItemsIdMap.put(info.id, info);
1716
1717                                    // now that we've loaded everthing re-save it with the
1718                                    // icon in case it disappears somehow.
1719                                    queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1720                                } else {
1721                                    throw new RuntimeException("Unexpected null ShortcutInfo");
1722                                }
1723                                break;
1724
1725                            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1726                                id = c.getLong(idIndex);
1727                                FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1728
1729                                folderInfo.title = c.getString(titleIndex);
1730                                folderInfo.id = id;
1731                                container = c.getInt(containerIndex);
1732                                folderInfo.container = container;
1733                                folderInfo.screenId = c.getInt(screenIndex);
1734                                folderInfo.cellX = c.getInt(cellXIndex);
1735                                folderInfo.cellY = c.getInt(cellYIndex);
1736
1737                                // check & update map of what's occupied
1738                                if (!checkItemPlacement(occupied, folderInfo)) {
1739                                    break;
1740                                }
1741                                switch (container) {
1742                                    case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1743                                    case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1744                                        sBgWorkspaceItems.add(folderInfo);
1745                                        break;
1746                                }
1747
1748                                sBgItemsIdMap.put(folderInfo.id, folderInfo);
1749                                sBgFolders.put(folderInfo.id, folderInfo);
1750                                break;
1751
1752                            case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1753                                // Read all Launcher-specific widget details
1754                                int appWidgetId = c.getInt(appWidgetIdIndex);
1755                                id = c.getLong(idIndex);
1756
1757                                final AppWidgetProviderInfo provider =
1758                                        widgets.getAppWidgetInfo(appWidgetId);
1759
1760                                if (!isSafeMode && (provider == null || provider.provider == null ||
1761                                        provider.provider.getPackageName() == null)) {
1762                                    String log = "Deleting widget that isn't installed anymore: id="
1763                                        + id + " appWidgetId=" + appWidgetId;
1764                                    Log.e(TAG, log);
1765                                    Launcher.sDumpLogs.add(log);
1766                                    itemsToRemove.add(id);
1767                                } else {
1768                                    appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1769                                            provider.provider);
1770                                    appWidgetInfo.id = id;
1771                                    appWidgetInfo.screenId = c.getInt(screenIndex);
1772                                    appWidgetInfo.cellX = c.getInt(cellXIndex);
1773                                    appWidgetInfo.cellY = c.getInt(cellYIndex);
1774                                    appWidgetInfo.spanX = c.getInt(spanXIndex);
1775                                    appWidgetInfo.spanY = c.getInt(spanYIndex);
1776                                    int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1777                                    appWidgetInfo.minSpanX = minSpan[0];
1778                                    appWidgetInfo.minSpanY = minSpan[1];
1779
1780                                    container = c.getInt(containerIndex);
1781                                    if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1782                                        container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1783                                        Log.e(TAG, "Widget found where container != " +
1784                                            "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1785                                        continue;
1786                                    }
1787
1788                                    appWidgetInfo.container = c.getInt(containerIndex);
1789                                    // check & update map of what's occupied
1790                                    if (!checkItemPlacement(occupied, appWidgetInfo)) {
1791                                        break;
1792                                    }
1793                                    sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1794                                    sBgAppWidgets.add(appWidgetInfo);
1795                                }
1796                                break;
1797                            }
1798                        } catch (Exception e) {
1799                            Log.w(TAG, "Desktop items loading interrupted:", e);
1800                        }
1801                    }
1802                } finally {
1803                    if (c != null) {
1804                        c.close();
1805                    }
1806                }
1807
1808                if (itemsToRemove.size() > 0) {
1809                    ContentProviderClient client = contentResolver.acquireContentProviderClient(
1810                                    LauncherSettings.Favorites.CONTENT_URI);
1811                    // Remove dead items
1812                    for (long id : itemsToRemove) {
1813                        if (DEBUG_LOADERS) {
1814                            Log.d(TAG, "Removed id = " + id);
1815                        }
1816                        // Don't notify content observers
1817                        try {
1818                            client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1819                                    null, null);
1820                        } catch (RemoteException e) {
1821                            Log.w(TAG, "Could not remove id = " + id);
1822                        }
1823                    }
1824                }
1825
1826                if (loadedOldDb) {
1827                    long maxScreenId = 0;
1828                    // If we're importing we use the old screen order.
1829                    for (ItemInfo item: sBgItemsIdMap.values()) {
1830                        long screenId = item.screenId;
1831                        if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1832                                !sBgWorkspaceScreens.contains(screenId)) {
1833                            sBgWorkspaceScreens.add(screenId);
1834                            if (screenId > maxScreenId) {
1835                                maxScreenId = screenId;
1836                            }
1837                        }
1838                    }
1839                    Collections.sort(sBgWorkspaceScreens);
1840                    mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1841                    updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1842
1843                    // Update the max item id after we load an old db
1844                    long maxItemId = 0;
1845                    // If we're importing we use the old screen order.
1846                    for (ItemInfo item: sBgItemsIdMap.values()) {
1847                        maxItemId = Math.max(maxItemId, item.id);
1848                    }
1849                    LauncherAppState app = LauncherAppState.getInstance();
1850                    app.getLauncherProvider().updateMaxItemId(maxItemId);
1851                } else {
1852                    Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1853                    final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1854                    TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1855
1856                    try {
1857                        final int idIndex = sc.getColumnIndexOrThrow(
1858                                LauncherSettings.WorkspaceScreens._ID);
1859                        final int rankIndex = sc.getColumnIndexOrThrow(
1860                                LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1861                        while (sc.moveToNext()) {
1862                            try {
1863                                long screenId = sc.getLong(idIndex);
1864                                int rank = sc.getInt(rankIndex);
1865
1866                                orderedScreens.put(rank, screenId);
1867                            } catch (Exception e) {
1868                                Log.w(TAG, "Desktop items loading interrupted:", e);
1869                            }
1870                        }
1871                    } finally {
1872                        sc.close();
1873                    }
1874
1875                    Iterator<Integer> iter = orderedScreens.keySet().iterator();
1876                    while (iter.hasNext()) {
1877                        sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1878                    }
1879
1880                    // Remove any empty screens
1881                    ArrayList<Long> unusedScreens = new ArrayList<Long>();
1882                    unusedScreens.addAll(sBgWorkspaceScreens);
1883
1884                    for (ItemInfo item: sBgItemsIdMap.values()) {
1885                        long screenId = item.screenId;
1886
1887                        if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1888                                unusedScreens.contains(screenId)) {
1889                            unusedScreens.remove(screenId);
1890                        }
1891                    }
1892
1893                    // If there are any empty screens remove them, and update.
1894                    if (unusedScreens.size() != 0) {
1895                        sBgWorkspaceScreens.removeAll(unusedScreens);
1896                        updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1897                    }
1898                }
1899
1900                if (DEBUG_LOADERS) {
1901                    Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1902                    Log.d(TAG, "workspace layout: ");
1903                    int nScreens = occupied.size();
1904                    for (int y = 0; y < mCellCountY; y++) {
1905                        String line = "";
1906
1907                        Iterator<Long> iter = occupied.keySet().iterator();
1908                        while (iter.hasNext()) {
1909                            long screenId = iter.next();
1910                            if (screenId > 0) {
1911                                line += " | ";
1912                            }
1913                            for (int x = 0; x < mCellCountX; x++) {
1914                                line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
1915                            }
1916                        }
1917                        Log.d(TAG, "[ " + line + " ]");
1918                    }
1919                }
1920            }
1921            return loadedOldDb;
1922        }
1923
1924        /** Filters the set of items who are directly or indirectly (via another container) on the
1925         * specified screen. */
1926        private void filterCurrentWorkspaceItems(int currentScreen,
1927                ArrayList<ItemInfo> allWorkspaceItems,
1928                ArrayList<ItemInfo> currentScreenItems,
1929                ArrayList<ItemInfo> otherScreenItems) {
1930            // Purge any null ItemInfos
1931            Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1932            while (iter.hasNext()) {
1933                ItemInfo i = iter.next();
1934                if (i == null) {
1935                    iter.remove();
1936                }
1937            }
1938
1939            // If we aren't filtering on a screen, then the set of items to load is the full set of
1940            // items given.
1941            if (currentScreen < 0) {
1942                currentScreenItems.addAll(allWorkspaceItems);
1943            }
1944
1945            // Order the set of items by their containers first, this allows use to walk through the
1946            // list sequentially, build up a list of containers that are in the specified screen,
1947            // as well as all items in those containers.
1948            Set<Long> itemsOnScreen = new HashSet<Long>();
1949            Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1950                @Override
1951                public int compare(ItemInfo lhs, ItemInfo rhs) {
1952                    return (int) (lhs.container - rhs.container);
1953                }
1954            });
1955            for (ItemInfo info : allWorkspaceItems) {
1956                if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1957                    if (info.screenId == currentScreen) {
1958                        currentScreenItems.add(info);
1959                        itemsOnScreen.add(info.id);
1960                    } else {
1961                        otherScreenItems.add(info);
1962                    }
1963                } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1964                    currentScreenItems.add(info);
1965                    itemsOnScreen.add(info.id);
1966                } else {
1967                    if (itemsOnScreen.contains(info.container)) {
1968                        currentScreenItems.add(info);
1969                        itemsOnScreen.add(info.id);
1970                    } else {
1971                        otherScreenItems.add(info);
1972                    }
1973                }
1974            }
1975        }
1976
1977        /** Filters the set of widgets which are on the specified screen. */
1978        private void filterCurrentAppWidgets(int currentScreen,
1979                ArrayList<LauncherAppWidgetInfo> appWidgets,
1980                ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1981                ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1982            // If we aren't filtering on a screen, then the set of items to load is the full set of
1983            // widgets given.
1984            if (currentScreen < 0) {
1985                currentScreenWidgets.addAll(appWidgets);
1986            }
1987
1988            for (LauncherAppWidgetInfo widget : appWidgets) {
1989                if (widget == null) continue;
1990                if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1991                        widget.screenId == currentScreen) {
1992                    currentScreenWidgets.add(widget);
1993                } else {
1994                    otherScreenWidgets.add(widget);
1995                }
1996            }
1997        }
1998
1999        /** Filters the set of folders which are on the specified screen. */
2000        private void filterCurrentFolders(int currentScreen,
2001                HashMap<Long, ItemInfo> itemsIdMap,
2002                HashMap<Long, FolderInfo> folders,
2003                HashMap<Long, FolderInfo> currentScreenFolders,
2004                HashMap<Long, FolderInfo> otherScreenFolders) {
2005            // If we aren't filtering on a screen, then the set of items to load is the full set of
2006            // widgets given.
2007            if (currentScreen < 0) {
2008                currentScreenFolders.putAll(folders);
2009            }
2010
2011            for (long id : folders.keySet()) {
2012                ItemInfo info = itemsIdMap.get(id);
2013                FolderInfo folder = folders.get(id);
2014                if (info == null || folder == null) continue;
2015                if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2016                        info.screenId == currentScreen) {
2017                    currentScreenFolders.put(id, folder);
2018                } else {
2019                    otherScreenFolders.put(id, folder);
2020                }
2021            }
2022        }
2023
2024        /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2025         * right) */
2026        private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
2027            // XXX: review this
2028            Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
2029                @Override
2030                public int compare(ItemInfo lhs, ItemInfo rhs) {
2031                    int cellCountX = LauncherModel.getCellCountX();
2032                    int cellCountY = LauncherModel.getCellCountY();
2033                    int screenOffset = cellCountX * cellCountY;
2034                    int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
2035                    long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
2036                            lhs.cellY * cellCountX + lhs.cellX);
2037                    long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
2038                            rhs.cellY * cellCountX + rhs.cellX);
2039                    return (int) (lr - rr);
2040                }
2041            });
2042        }
2043
2044        private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2045                final ArrayList<Long> orderedScreens) {
2046
2047            final Runnable r = new Runnable() {
2048                @Override
2049                public void run() {
2050                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2051                    if (callbacks != null) {
2052                        callbacks.bindScreens(orderedScreens);
2053                    }
2054                }
2055            };
2056            runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2057        }
2058
2059        private void bindWorkspaceItems(final Callbacks oldCallbacks,
2060                final ArrayList<ItemInfo> workspaceItems,
2061                final ArrayList<LauncherAppWidgetInfo> appWidgets,
2062                final HashMap<Long, FolderInfo> folders,
2063                ArrayList<Runnable> deferredBindRunnables) {
2064
2065            final boolean postOnMainThread = (deferredBindRunnables != null);
2066
2067            // Bind the workspace items
2068            int N = workspaceItems.size();
2069            for (int i = 0; i < N; i += ITEMS_CHUNK) {
2070                final int start = i;
2071                final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
2072                final Runnable r = new Runnable() {
2073                    @Override
2074                    public void run() {
2075                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2076                        if (callbacks != null) {
2077                            callbacks.bindItems(workspaceItems, start, start+chunkSize,
2078                                    false);
2079                        }
2080                    }
2081                };
2082                if (postOnMainThread) {
2083                    deferredBindRunnables.add(r);
2084                } else {
2085                    runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2086                }
2087            }
2088
2089            // Bind the folders
2090            if (!folders.isEmpty()) {
2091                final Runnable r = new Runnable() {
2092                    public void run() {
2093                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2094                        if (callbacks != null) {
2095                            callbacks.bindFolders(folders);
2096                        }
2097                    }
2098                };
2099                if (postOnMainThread) {
2100                    deferredBindRunnables.add(r);
2101                } else {
2102                    runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2103                }
2104            }
2105
2106            // Bind the widgets, one at a time
2107            N = appWidgets.size();
2108            for (int i = 0; i < N; i++) {
2109                final LauncherAppWidgetInfo widget = appWidgets.get(i);
2110                final Runnable r = new Runnable() {
2111                    public void run() {
2112                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2113                        if (callbacks != null) {
2114                            callbacks.bindAppWidget(widget);
2115                        }
2116                    }
2117                };
2118                if (postOnMainThread) {
2119                    deferredBindRunnables.add(r);
2120                } else {
2121                    runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2122                }
2123            }
2124        }
2125
2126        /**
2127         * Binds all loaded data to actual views on the main thread.
2128         */
2129        private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
2130            final long t = SystemClock.uptimeMillis();
2131            Runnable r;
2132
2133            // Don't use these two variables in any of the callback runnables.
2134            // Otherwise we hold a reference to them.
2135            final Callbacks oldCallbacks = mCallbacks.get();
2136            if (oldCallbacks == null) {
2137                // This launcher has exited and nobody bothered to tell us.  Just bail.
2138                Log.w(TAG, "LoaderTask running with no launcher");
2139                return;
2140            }
2141
2142            final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2143            final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
2144                oldCallbacks.getCurrentWorkspaceScreen();
2145
2146            // Load all the items that are on the current page first (and in the process, unbind
2147            // all the existing workspace items before we call startBinding() below.
2148            unbindWorkspaceItemsOnMainThread();
2149            ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2150            ArrayList<LauncherAppWidgetInfo> appWidgets =
2151                    new ArrayList<LauncherAppWidgetInfo>();
2152            HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2153            HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
2154            ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
2155            synchronized (sBgLock) {
2156                workspaceItems.addAll(sBgWorkspaceItems);
2157                appWidgets.addAll(sBgAppWidgets);
2158                folders.putAll(sBgFolders);
2159                itemsIdMap.putAll(sBgItemsIdMap);
2160                orderedScreenIds.addAll(sBgWorkspaceScreens);
2161            }
2162
2163            ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2164            ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2165            ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2166                    new ArrayList<LauncherAppWidgetInfo>();
2167            ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2168                    new ArrayList<LauncherAppWidgetInfo>();
2169            HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2170            HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2171
2172            // Separate the items that are on the current screen, and all the other remaining items
2173            filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2174                    otherWorkspaceItems);
2175            filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2176                    otherAppWidgets);
2177            filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2178                    otherFolders);
2179            sortWorkspaceItemsSpatially(currentWorkspaceItems);
2180            sortWorkspaceItemsSpatially(otherWorkspaceItems);
2181
2182            // Tell the workspace that we're about to start binding items
2183            r = new Runnable() {
2184                public void run() {
2185                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2186                    if (callbacks != null) {
2187                        callbacks.startBinding();
2188                    }
2189                }
2190            };
2191            runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2192
2193            bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2194
2195            // Load items on the current page
2196            bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2197                    currentFolders, null);
2198            if (isLoadingSynchronously) {
2199                r = new Runnable() {
2200                    public void run() {
2201                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2202                        if (callbacks != null) {
2203                            callbacks.onPageBoundSynchronously(currentScreen);
2204                        }
2205                    }
2206                };
2207                runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2208            }
2209
2210            // Load all the remaining pages (if we are loading synchronously, we want to defer this
2211            // work until after the first render)
2212            mDeferredBindRunnables.clear();
2213            bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
2214                    (isLoadingSynchronously ? mDeferredBindRunnables : null));
2215
2216            // Tell the workspace that we're done binding items
2217            r = new Runnable() {
2218                public void run() {
2219                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2220                    if (callbacks != null) {
2221                        callbacks.finishBindingItems(isUpgradePath);
2222                    }
2223
2224                    // If we're profiling, ensure this is the last thing in the queue.
2225                    if (DEBUG_LOADERS) {
2226                        Log.d(TAG, "bound workspace in "
2227                            + (SystemClock.uptimeMillis()-t) + "ms");
2228                    }
2229
2230                    mIsLoadingAndBindingWorkspace = false;
2231                }
2232            };
2233            if (isLoadingSynchronously) {
2234                mDeferredBindRunnables.add(r);
2235            } else {
2236                runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2237            }
2238        }
2239
2240        private void loadAndBindAllApps() {
2241            if (DEBUG_LOADERS) {
2242                Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2243            }
2244            if (!mAllAppsLoaded) {
2245                loadAllApps();
2246                synchronized (LoaderTask.this) {
2247                    if (mStopped) {
2248                        return;
2249                    }
2250                    mAllAppsLoaded = true;
2251                }
2252            } else {
2253                onlyBindAllApps();
2254            }
2255        }
2256
2257        private void onlyBindAllApps() {
2258            final Callbacks oldCallbacks = mCallbacks.get();
2259            if (oldCallbacks == null) {
2260                // This launcher has exited and nobody bothered to tell us.  Just bail.
2261                Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2262                return;
2263            }
2264
2265            // shallow copy
2266            @SuppressWarnings("unchecked")
2267            final ArrayList<ApplicationInfo> list
2268                    = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
2269            Runnable r = new Runnable() {
2270                public void run() {
2271                    final long t = SystemClock.uptimeMillis();
2272                    final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2273                    if (callbacks != null) {
2274                        callbacks.bindAllApplications(list);
2275                    }
2276                    if (DEBUG_LOADERS) {
2277                        Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2278                                + (SystemClock.uptimeMillis()-t) + "ms");
2279                    }
2280                }
2281            };
2282            boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
2283            if (isRunningOnMainThread) {
2284                r.run();
2285            } else {
2286                mHandler.post(r);
2287            }
2288        }
2289
2290        private void loadAllApps() {
2291            final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2292
2293            // Don't use these two variables in any of the callback runnables.
2294            // Otherwise we hold a reference to them.
2295            final Callbacks oldCallbacks = mCallbacks.get();
2296            if (oldCallbacks == null) {
2297                // This launcher has exited and nobody bothered to tell us.  Just bail.
2298                Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
2299                return;
2300            }
2301
2302            final PackageManager packageManager = mContext.getPackageManager();
2303            final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2304            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2305
2306            // Clear the list of apps
2307            mBgAllAppsList.clear();
2308
2309            // Query for the set of apps
2310            final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2311            List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2312            if (DEBUG_LOADERS) {
2313                Log.d(TAG, "queryIntentActivities took "
2314                        + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2315                Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2316            }
2317            // Fail if we don't have any apps
2318            if (apps == null || apps.isEmpty()) {
2319                return;
2320            }
2321            // Sort the applications by name
2322            final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2323            Collections.sort(apps,
2324                    new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2325            if (DEBUG_LOADERS) {
2326                Log.d(TAG, "sort took "
2327                        + (SystemClock.uptimeMillis()-sortTime) + "ms");
2328            }
2329
2330            // Create the ApplicationInfos
2331            final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2332            for (int i = 0; i < apps.size(); i++) {
2333                // This builds the icon bitmaps.
2334                mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2335                        mIconCache, mLabelCache));
2336            }
2337
2338            final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2339            final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2340            mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2341
2342            // Post callback on main thread
2343            mHandler.post(new Runnable() {
2344                public void run() {
2345                    final long bindTime = SystemClock.uptimeMillis();
2346                    if (callbacks != null) {
2347                        callbacks.bindAllApplications(added);
2348                        if (DEBUG_LOADERS) {
2349                            Log.d(TAG, "bound " + added.size() + " apps in "
2350                                + (SystemClock.uptimeMillis() - bindTime) + "ms");
2351                        }
2352                    } else {
2353                        Log.i(TAG, "not binding apps: no Launcher activity");
2354                    }
2355                }
2356            });
2357
2358            if (DEBUG_LOADERS) {
2359                Log.d(TAG, "Icons processed in "
2360                        + (SystemClock.uptimeMillis() - loadTime) + "ms");
2361            }
2362        }
2363
2364        public void dumpState() {
2365            synchronized (sBgLock) {
2366                Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2367                Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2368                Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2369                Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2370                Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2371            }
2372        }
2373    }
2374
2375    void enqueuePackageUpdated(PackageUpdatedTask task) {
2376        sWorker.post(task);
2377    }
2378
2379    private class PackageUpdatedTask implements Runnable {
2380        int mOp;
2381        String[] mPackages;
2382
2383        public static final int OP_NONE = 0;
2384        public static final int OP_ADD = 1;
2385        public static final int OP_UPDATE = 2;
2386        public static final int OP_REMOVE = 3; // uninstlled
2387        public static final int OP_UNAVAILABLE = 4; // external media unmounted
2388
2389
2390        public PackageUpdatedTask(int op, String[] packages) {
2391            mOp = op;
2392            mPackages = packages;
2393        }
2394
2395        public void run() {
2396            final Context context = mApp.getContext();
2397
2398            final String[] packages = mPackages;
2399            final int N = packages.length;
2400            switch (mOp) {
2401                case OP_ADD:
2402                    for (int i=0; i<N; i++) {
2403                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
2404                        mBgAllAppsList.addPackage(context, packages[i]);
2405                    }
2406                    break;
2407                case OP_UPDATE:
2408                    for (int i=0; i<N; i++) {
2409                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
2410                        mBgAllAppsList.updatePackage(context, packages[i]);
2411                        WidgetPreviewLoader.removeFromDb(
2412                                mApp.getWidgetPreviewCacheDb(), packages[i]);
2413                    }
2414                    break;
2415                case OP_REMOVE:
2416                case OP_UNAVAILABLE:
2417                    for (int i=0; i<N; i++) {
2418                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
2419                        mBgAllAppsList.removePackage(packages[i]);
2420                        WidgetPreviewLoader.removeFromDb(
2421                                mApp.getWidgetPreviewCacheDb(), packages[i]);
2422                    }
2423                    break;
2424            }
2425
2426            ArrayList<ApplicationInfo> added = null;
2427            ArrayList<ApplicationInfo> modified = null;
2428            final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
2429
2430            if (mBgAllAppsList.added.size() > 0) {
2431                added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2432                mBgAllAppsList.added.clear();
2433            }
2434            if (mBgAllAppsList.modified.size() > 0) {
2435                modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2436                mBgAllAppsList.modified.clear();
2437            }
2438            if (mBgAllAppsList.removed.size() > 0) {
2439                removedApps.addAll(mBgAllAppsList.removed);
2440                mBgAllAppsList.removed.clear();
2441            }
2442
2443            final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2444            if (callbacks == null) {
2445                Log.w(TAG, "Nobody to tell about the new app.  Launcher is probably loading.");
2446                return;
2447            }
2448
2449            if (added != null) {
2450                // Ensure that we add all the workspace applications to the db
2451                final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
2452                Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2453                addAndBindAddedApps(context, addedInfos, cb);
2454            }
2455            if (modified != null) {
2456                final ArrayList<ApplicationInfo> modifiedFinal = modified;
2457
2458                // Update the launcher db to reflect the changes
2459                for (ApplicationInfo a : modifiedFinal) {
2460                    ArrayList<ItemInfo> infos =
2461                            getItemInfoForComponentName(a.componentName);
2462                    for (ItemInfo i : infos) {
2463                        if (isShortcutInfoUpdateable(i)) {
2464                            ShortcutInfo info = (ShortcutInfo) i;
2465                            info.title = a.title.toString();
2466                            updateItemInDatabase(context, info);
2467                        }
2468                    }
2469                }
2470
2471                mHandler.post(new Runnable() {
2472                    public void run() {
2473                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2474                        if (callbacks == cb && cb != null) {
2475                            callbacks.bindAppsUpdated(modifiedFinal);
2476                        }
2477                    }
2478                });
2479            }
2480            // If a package has been removed, or an app has been removed as a result of
2481            // an update (for example), make the removed callback.
2482            if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
2483                final boolean packageRemoved = (mOp == OP_REMOVE);
2484                final ArrayList<String> removedPackageNames =
2485                        new ArrayList<String>(Arrays.asList(packages));
2486
2487                // Update the launcher db to reflect the removal of apps
2488                if (packageRemoved) {
2489                    for (String pn : removedPackageNames) {
2490                        ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2491                        for (ItemInfo i : infos) {
2492                            deleteItemFromDatabase(context, i);
2493                        }
2494                    }
2495                } else {
2496                    for (ApplicationInfo a : removedApps) {
2497                        ArrayList<ItemInfo> infos =
2498                                getItemInfoForComponentName(a.componentName);
2499                        for (ItemInfo i : infos) {
2500                            deleteItemFromDatabase(context, i);
2501                        }
2502                    }
2503                }
2504
2505                mHandler.post(new Runnable() {
2506                    public void run() {
2507                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2508                        if (callbacks == cb && cb != null) {
2509                            callbacks.bindComponentsRemoved(removedPackageNames,
2510                                    removedApps, packageRemoved);
2511                        }
2512                    }
2513                });
2514            }
2515
2516            final ArrayList<Object> widgetsAndShortcuts =
2517                getSortedWidgetsAndShortcuts(context);
2518            mHandler.post(new Runnable() {
2519                @Override
2520                public void run() {
2521                    Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2522                    if (callbacks == cb && cb != null) {
2523                        callbacks.bindPackagesUpdated(widgetsAndShortcuts);
2524                    }
2525                }
2526            });
2527        }
2528    }
2529
2530    // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2531    public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2532        PackageManager packageManager = context.getPackageManager();
2533        final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2534        widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2535        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2536        widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2537        Collections.sort(widgetsAndShortcuts,
2538            new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2539        return widgetsAndShortcuts;
2540    }
2541
2542    private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
2543        if (cn == null) {
2544            return false;
2545        }
2546
2547        try {
2548            return (pm.getActivityInfo(cn, 0) != null);
2549        } catch (NameNotFoundException e) {
2550            return false;
2551        }
2552    }
2553
2554    /**
2555     * This is called from the code that adds shortcuts from the intent receiver.  This
2556     * doesn't have a Cursor, but
2557     */
2558    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
2559        return getShortcutInfo(manager, intent, context, null, -1, -1, null);
2560    }
2561
2562    /**
2563     * Make an ShortcutInfo object for a shortcut that is an application.
2564     *
2565     * If c is not null, then it will be used to fill in missing data like the title and icon.
2566     */
2567    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
2568            Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
2569        ComponentName componentName = intent.getComponent();
2570        final ShortcutInfo info = new ShortcutInfo();
2571        if (!isValidPackageComponent(manager, componentName)) {
2572            Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
2573            return null;
2574        } else {
2575            try {
2576                PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2577                info.initFlagsAndFirstInstallTime(pi);
2578            } catch (NameNotFoundException e) {
2579                Log.d(TAG, "getPackInfo failed for package " +
2580                        componentName.getPackageName());
2581            }
2582        }
2583
2584        // TODO: See if the PackageManager knows about this case.  If it doesn't
2585        // then return null & delete this.
2586
2587        // the resource -- This may implicitly give us back the fallback icon,
2588        // but don't worry about that.  All we're doing with usingFallbackIcon is
2589        // to avoid saving lots of copies of that in the database, and most apps
2590        // have icons anyway.
2591
2592        // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2593        // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2594        // via resolveActivity().
2595        Bitmap icon = null;
2596        ResolveInfo resolveInfo = null;
2597        ComponentName oldComponent = intent.getComponent();
2598        Intent newIntent = new Intent(intent.getAction(), null);
2599        newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2600        newIntent.setPackage(oldComponent.getPackageName());
2601        List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2602        for (ResolveInfo i : infos) {
2603            ComponentName cn = new ComponentName(i.activityInfo.packageName,
2604                    i.activityInfo.name);
2605            if (cn.equals(oldComponent)) {
2606                resolveInfo = i;
2607            }
2608        }
2609        if (resolveInfo == null) {
2610            resolveInfo = manager.resolveActivity(intent, 0);
2611        }
2612        if (resolveInfo != null) {
2613            icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
2614        }
2615        // the db
2616        if (icon == null) {
2617            if (c != null) {
2618                icon = getIconFromCursor(c, iconIndex, context);
2619            }
2620        }
2621        // the fallback icon
2622        if (icon == null) {
2623            icon = getFallbackIcon();
2624            info.usingFallbackIcon = true;
2625        }
2626        info.setIcon(icon);
2627
2628        // from the resource
2629        if (resolveInfo != null) {
2630            ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2631            if (labelCache != null && labelCache.containsKey(key)) {
2632                info.title = labelCache.get(key);
2633            } else {
2634                info.title = resolveInfo.activityInfo.loadLabel(manager);
2635                if (labelCache != null) {
2636                    labelCache.put(key, info.title);
2637                }
2638            }
2639        }
2640        // from the db
2641        if (info.title == null) {
2642            if (c != null) {
2643                info.title =  c.getString(titleIndex);
2644            }
2645        }
2646        // fall back to the class name of the activity
2647        if (info.title == null) {
2648            info.title = componentName.getClassName();
2649        }
2650        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2651        return info;
2652    }
2653
2654    static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2655            ItemInfoFilter f) {
2656        HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2657        for (ItemInfo i : infos) {
2658            if (i instanceof ShortcutInfo) {
2659                ShortcutInfo info = (ShortcutInfo) i;
2660                ComponentName cn = info.intent.getComponent();
2661                if (cn != null && f.filterItem(null, info, cn)) {
2662                    filtered.add(info);
2663                }
2664            } else if (i instanceof FolderInfo) {
2665                FolderInfo info = (FolderInfo) i;
2666                for (ShortcutInfo s : info.contents) {
2667                    ComponentName cn = s.intent.getComponent();
2668                    if (cn != null && f.filterItem(info, s, cn)) {
2669                        filtered.add(s);
2670                    }
2671                }
2672            } else if (i instanceof LauncherAppWidgetInfo) {
2673                LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2674                ComponentName cn = info.providerName;
2675                if (cn != null && f.filterItem(null, info, cn)) {
2676                    filtered.add(info);
2677                }
2678            }
2679        }
2680        return new ArrayList<ItemInfo>(filtered);
2681    }
2682
2683    private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2684        HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2685        ItemInfoFilter filter  = new ItemInfoFilter() {
2686            @Override
2687            public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2688                return cn.getPackageName().equals(pn);
2689            }
2690        };
2691        return filterItemInfos(sBgItemsIdMap.values(), filter);
2692    }
2693
2694    private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2695        HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2696        ItemInfoFilter filter  = new ItemInfoFilter() {
2697            @Override
2698            public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2699                return cn.equals(cname);
2700            }
2701        };
2702        return filterItemInfos(sBgItemsIdMap.values(), filter);
2703    }
2704
2705    public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2706        if (i instanceof ShortcutInfo) {
2707            ShortcutInfo info = (ShortcutInfo) i;
2708            // We need to check for ACTION_MAIN otherwise getComponent() might
2709            // return null for some shortcuts (for instance, for shortcuts to
2710            // web pages.)
2711            Intent intent = info.intent;
2712            ComponentName name = intent.getComponent();
2713            if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2714                    Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2715                return true;
2716            }
2717        }
2718        return false;
2719    }
2720
2721    /**
2722     * Make an ShortcutInfo object for a shortcut that isn't an application.
2723     */
2724    private ShortcutInfo getShortcutInfo(Cursor c, Context context,
2725            int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2726            int titleIndex) {
2727
2728        Bitmap icon = null;
2729        final ShortcutInfo info = new ShortcutInfo();
2730        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
2731
2732        // TODO: If there's an explicit component and we can't install that, delete it.
2733
2734        info.title = c.getString(titleIndex);
2735
2736        int iconType = c.getInt(iconTypeIndex);
2737        switch (iconType) {
2738        case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2739            String packageName = c.getString(iconPackageIndex);
2740            String resourceName = c.getString(iconResourceIndex);
2741            PackageManager packageManager = context.getPackageManager();
2742            info.customIcon = false;
2743            // the resource
2744            try {
2745                Resources resources = packageManager.getResourcesForApplication(packageName);
2746                if (resources != null) {
2747                    final int id = resources.getIdentifier(resourceName, null, null);
2748                    icon = Utilities.createIconBitmap(
2749                            mIconCache.getFullResIcon(resources, id), context);
2750                }
2751            } catch (Exception e) {
2752                // drop this.  we have other places to look for icons
2753            }
2754            // the db
2755            if (icon == null) {
2756                icon = getIconFromCursor(c, iconIndex, context);
2757            }
2758            // the fallback icon
2759            if (icon == null) {
2760                icon = getFallbackIcon();
2761                info.usingFallbackIcon = true;
2762            }
2763            break;
2764        case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
2765            icon = getIconFromCursor(c, iconIndex, context);
2766            if (icon == null) {
2767                icon = getFallbackIcon();
2768                info.customIcon = false;
2769                info.usingFallbackIcon = true;
2770            } else {
2771                info.customIcon = true;
2772            }
2773            break;
2774        default:
2775            icon = getFallbackIcon();
2776            info.usingFallbackIcon = true;
2777            info.customIcon = false;
2778            break;
2779        }
2780        info.setIcon(icon);
2781        return info;
2782    }
2783
2784    Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
2785        @SuppressWarnings("all") // suppress dead code warning
2786        final boolean debug = false;
2787        if (debug) {
2788            Log.d(TAG, "getIconFromCursor app="
2789                    + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2790        }
2791        byte[] data = c.getBlob(iconIndex);
2792        try {
2793            return Utilities.createIconBitmap(
2794                    BitmapFactory.decodeByteArray(data, 0, data.length), context);
2795        } catch (Exception e) {
2796            return null;
2797        }
2798    }
2799
2800    ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2801            int cellX, int cellY, boolean notify) {
2802        final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
2803        if (info == null) {
2804            return null;
2805        }
2806        addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
2807
2808        return info;
2809    }
2810
2811    /**
2812     * Attempts to find an AppWidgetProviderInfo that matches the given component.
2813     */
2814    AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2815            ComponentName component) {
2816        List<AppWidgetProviderInfo> widgets =
2817            AppWidgetManager.getInstance(context).getInstalledProviders();
2818        for (AppWidgetProviderInfo info : widgets) {
2819            if (info.provider.equals(component)) {
2820                return info;
2821            }
2822        }
2823        return null;
2824    }
2825
2826    /**
2827     * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2828     */
2829    List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2830        final PackageManager packageManager = context.getPackageManager();
2831        final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2832            new ArrayList<WidgetMimeTypeHandlerData>();
2833
2834        final Intent supportsIntent =
2835            new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2836        supportsIntent.setType(mimeType);
2837
2838        // Create a set of widget configuration components that we can test against
2839        final List<AppWidgetProviderInfo> widgets =
2840            AppWidgetManager.getInstance(context).getInstalledProviders();
2841        final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2842            new HashMap<ComponentName, AppWidgetProviderInfo>();
2843        for (AppWidgetProviderInfo info : widgets) {
2844            configurationComponentToWidget.put(info.configure, info);
2845        }
2846
2847        // Run through each of the intents that can handle this type of clip data, and cross
2848        // reference them with the components that are actual configuration components
2849        final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2850                PackageManager.MATCH_DEFAULT_ONLY);
2851        for (ResolveInfo info : activities) {
2852            final ActivityInfo activityInfo = info.activityInfo;
2853            final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2854                    activityInfo.name);
2855            if (configurationComponentToWidget.containsKey(infoComponent)) {
2856                supportedConfigurationActivities.add(
2857                        new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2858                                configurationComponentToWidget.get(infoComponent)));
2859            }
2860        }
2861        return supportedConfigurationActivities;
2862    }
2863
2864    ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
2865        Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2866        String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2867        Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2868
2869        if (intent == null) {
2870            // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2871            Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2872            return null;
2873        }
2874
2875        Bitmap icon = null;
2876        boolean customIcon = false;
2877        ShortcutIconResource iconResource = null;
2878
2879        if (bitmap != null && bitmap instanceof Bitmap) {
2880            icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
2881            customIcon = true;
2882        } else {
2883            Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2884            if (extra != null && extra instanceof ShortcutIconResource) {
2885                try {
2886                    iconResource = (ShortcutIconResource) extra;
2887                    final PackageManager packageManager = context.getPackageManager();
2888                    Resources resources = packageManager.getResourcesForApplication(
2889                            iconResource.packageName);
2890                    final int id = resources.getIdentifier(iconResource.resourceName, null, null);
2891                    icon = Utilities.createIconBitmap(
2892                            mIconCache.getFullResIcon(resources, id), context);
2893                } catch (Exception e) {
2894                    Log.w(TAG, "Could not load shortcut icon: " + extra);
2895                }
2896            }
2897        }
2898
2899        final ShortcutInfo info = new ShortcutInfo();
2900
2901        if (icon == null) {
2902            if (fallbackIcon != null) {
2903                icon = fallbackIcon;
2904            } else {
2905                icon = getFallbackIcon();
2906                info.usingFallbackIcon = true;
2907            }
2908        }
2909        info.setIcon(icon);
2910
2911        info.title = name;
2912        info.intent = intent;
2913        info.customIcon = customIcon;
2914        info.iconResource = iconResource;
2915
2916        return info;
2917    }
2918
2919    boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2920            int iconIndex) {
2921        // If apps can't be on SD, don't even bother.
2922        if (!mAppsCanBeOnRemoveableStorage) {
2923            return false;
2924        }
2925        // If this icon doesn't have a custom icon, check to see
2926        // what's stored in the DB, and if it doesn't match what
2927        // we're going to show, store what we are going to show back
2928        // into the DB.  We do this so when we're loading, if the
2929        // package manager can't find an icon (for example because
2930        // the app is on SD) then we can use that instead.
2931        if (!info.customIcon && !info.usingFallbackIcon) {
2932            cache.put(info, c.getBlob(iconIndex));
2933            return true;
2934        }
2935        return false;
2936    }
2937    void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2938        boolean needSave = false;
2939        try {
2940            if (data != null) {
2941                Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2942                Bitmap loaded = info.getIcon(mIconCache);
2943                needSave = !saved.sameAs(loaded);
2944            } else {
2945                needSave = true;
2946            }
2947        } catch (Exception e) {
2948            needSave = true;
2949        }
2950        if (needSave) {
2951            Log.d(TAG, "going to save icon bitmap for info=" + info);
2952            // This is slower than is ideal, but this only happens once
2953            // or when the app is updated with a new icon.
2954            updateItemInDatabase(context, info);
2955        }
2956    }
2957
2958    /**
2959     * Return an existing FolderInfo object if we have encountered this ID previously,
2960     * or make a new one.
2961     */
2962    private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
2963        // See if a placeholder was created for us already
2964        FolderInfo folderInfo = folders.get(id);
2965        if (folderInfo == null) {
2966            // No placeholder -- create a new instance
2967            folderInfo = new FolderInfo();
2968            folders.put(id, folderInfo);
2969        }
2970        return folderInfo;
2971    }
2972
2973    public static final Comparator<ApplicationInfo> getAppNameComparator() {
2974        final Collator collator = Collator.getInstance();
2975        return new Comparator<ApplicationInfo>() {
2976            public final int compare(ApplicationInfo a, ApplicationInfo b) {
2977                int result = collator.compare(a.title.toString(), b.title.toString());
2978                if (result == 0) {
2979                    result = a.componentName.compareTo(b.componentName);
2980                }
2981                return result;
2982            }
2983        };
2984    }
2985    public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2986            = new Comparator<ApplicationInfo>() {
2987        public final int compare(ApplicationInfo a, ApplicationInfo b) {
2988            if (a.firstInstallTime < b.firstInstallTime) return 1;
2989            if (a.firstInstallTime > b.firstInstallTime) return -1;
2990            return 0;
2991        }
2992    };
2993    public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2994        final Collator collator = Collator.getInstance();
2995        return new Comparator<AppWidgetProviderInfo>() {
2996            public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2997                return collator.compare(a.label.toString(), b.label.toString());
2998            }
2999        };
3000    }
3001    static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3002        if (info.activityInfo != null) {
3003            return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3004        } else {
3005            return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3006        }
3007    }
3008    public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
3009        private Collator mCollator;
3010        private PackageManager mPackageManager;
3011        private HashMap<Object, CharSequence> mLabelCache;
3012        ShortcutNameComparator(PackageManager pm) {
3013            mPackageManager = pm;
3014            mLabelCache = new HashMap<Object, CharSequence>();
3015            mCollator = Collator.getInstance();
3016        }
3017        ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3018            mPackageManager = pm;
3019            mLabelCache = labelCache;
3020            mCollator = Collator.getInstance();
3021        }
3022        public final int compare(ResolveInfo a, ResolveInfo b) {
3023            CharSequence labelA, labelB;
3024            ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3025            ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3026            if (mLabelCache.containsKey(keyA)) {
3027                labelA = mLabelCache.get(keyA);
3028            } else {
3029                labelA = a.loadLabel(mPackageManager).toString();
3030
3031                mLabelCache.put(keyA, labelA);
3032            }
3033            if (mLabelCache.containsKey(keyB)) {
3034                labelB = mLabelCache.get(keyB);
3035            } else {
3036                labelB = b.loadLabel(mPackageManager).toString();
3037
3038                mLabelCache.put(keyB, labelB);
3039            }
3040            return mCollator.compare(labelA, labelB);
3041        }
3042    };
3043    public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
3044        private Collator mCollator;
3045        private PackageManager mPackageManager;
3046        private HashMap<Object, String> mLabelCache;
3047        WidgetAndShortcutNameComparator(PackageManager pm) {
3048            mPackageManager = pm;
3049            mLabelCache = new HashMap<Object, String>();
3050            mCollator = Collator.getInstance();
3051        }
3052        public final int compare(Object a, Object b) {
3053            String labelA, labelB;
3054            if (mLabelCache.containsKey(a)) {
3055                labelA = mLabelCache.get(a);
3056            } else {
3057                labelA = (a instanceof AppWidgetProviderInfo) ?
3058                    ((AppWidgetProviderInfo) a).label :
3059                    ((ResolveInfo) a).loadLabel(mPackageManager).toString();
3060                mLabelCache.put(a, labelA);
3061            }
3062            if (mLabelCache.containsKey(b)) {
3063                labelB = mLabelCache.get(b);
3064            } else {
3065                labelB = (b instanceof AppWidgetProviderInfo) ?
3066                    ((AppWidgetProviderInfo) b).label :
3067                    ((ResolveInfo) b).loadLabel(mPackageManager).toString();
3068                mLabelCache.put(b, labelB);
3069            }
3070            return mCollator.compare(labelA, labelB);
3071        }
3072    };
3073
3074    public void dumpState() {
3075        Log.d(TAG, "mCallbacks=" + mCallbacks);
3076        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3077        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3078        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3079        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
3080        if (mLoaderTask != null) {
3081            mLoaderTask.dumpState();
3082        } else {
3083            Log.d(TAG, "mLoaderTask=null");
3084        }
3085    }
3086}
3087