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