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