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