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