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