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