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