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