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