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