LauncherModel.java revision 452b4db5ce5206f050733a39fe95acad11617814
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.launcher2;
18
19import android.app.SearchManager;
20import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
22import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.ContentProviderClient;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
29import android.content.Intent.ShortcutIconResource;
30import android.content.pm.ActivityInfo;
31import android.content.pm.PackageInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
36import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
39import android.graphics.BitmapFactory;
40import android.net.Uri;
41import android.os.Environment;
42import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.Parcelable;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.util.Log;
49
50import com.android.launcher.R;
51import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
52
53import java.lang.ref.WeakReference;
54import java.net.URISyntaxException;
55import java.text.Collator;
56import java.util.ArrayList;
57import java.util.Collections;
58import java.util.Comparator;
59import java.util.HashMap;
60import java.util.List;
61
62/**
63 * Maintains in-memory state of the Launcher. It is expected that there should be only one
64 * LauncherModel object held in a static. Also provide APIs for updating the database state
65 * for the Launcher.
66 */
67public class LauncherModel extends BroadcastReceiver {
68    static final boolean DEBUG_LOADERS = false;
69    static final String TAG = "Launcher.Model";
70
71    private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
72    private final boolean mAppsCanBeOnExternalStorage;
73    private int mBatchSize; // 0 is all apps at once
74    private int mAllAppsLoadDelay; // milliseconds between batches
75
76    private final LauncherApplication mApp;
77    private final Object mLock = new Object();
78    private DeferredHandler mHandler = new DeferredHandler();
79    private LoaderTask mLoaderTask;
80
81    private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
82    static {
83        sWorkerThread.start();
84    }
85    private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
86
87    // We start off with everything not loaded.  After that, we assume that
88    // our monitoring of the package manager provides all updates and we never
89    // need to do a requery.  These are only ever touched from the loader thread.
90    private boolean mWorkspaceLoaded;
91    private boolean mAllAppsLoaded;
92
93    private WeakReference<Callbacks> mCallbacks;
94
95    // < only access in worker thread >
96    private AllAppsList mAllAppsList;
97
98    // sItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
99    // LauncherModel to their ids
100    static final HashMap<Long, ItemInfo> sItemsIdMap = new HashMap<Long, ItemInfo>();
101
102    // sItems is passed to bindItems, which expects a list of all folders and shortcuts created by
103    //       LauncherModel that are directly on the home screen (however, no widgets or shortcuts
104    //       within folders).
105    static final ArrayList<ItemInfo> sWorkspaceItems = new ArrayList<ItemInfo>();
106
107    // sAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
108    static final ArrayList<LauncherAppWidgetInfo> sAppWidgets =
109        new ArrayList<LauncherAppWidgetInfo>();
110
111    // sFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
112    static final HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
113
114    // sDbIconCache is the set of ItemInfos that need to have their icons updated in the database
115    static final HashMap<Object, byte[]> sDbIconCache = new HashMap<Object, byte[]>();
116
117    // </ only access in worker thread >
118
119    private IconCache mIconCache;
120    private Bitmap mDefaultIcon;
121
122    private static int mCellCountX;
123    private static int mCellCountY;
124
125    protected int mPreviousConfigMcc;
126
127    public interface Callbacks {
128        public boolean setLoadOnResume();
129        public int getCurrentWorkspaceScreen();
130        public void startBinding();
131        public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
132        public void bindFolders(HashMap<Long,FolderInfo> folders);
133        public void finishBindingItems();
134        public void bindAppWidget(LauncherAppWidgetInfo info);
135        public void bindAllApplications(ArrayList<ApplicationInfo> apps);
136        public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
137        public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
138        public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent);
139        public void bindPackagesUpdated();
140        public boolean isAllAppsVisible();
141        public boolean isAllAppsButtonRank(int rank);
142        public void bindSearchablesChanged();
143    }
144
145    LauncherModel(LauncherApplication app, IconCache iconCache) {
146        mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
147        mApp = app;
148        mAllAppsList = new AllAppsList(iconCache);
149        mIconCache = iconCache;
150
151        mDefaultIcon = Utilities.createIconBitmap(
152                mIconCache.getFullResDefaultActivityIcon(), app);
153
154        final Resources res = app.getResources();
155        mAllAppsLoadDelay = res.getInteger(R.integer.config_allAppsBatchLoadDelay);
156        mBatchSize = res.getInteger(R.integer.config_allAppsBatchSize);
157        Configuration config = res.getConfiguration();
158        mPreviousConfigMcc = config.mcc;
159    }
160
161    public Bitmap getFallbackIcon() {
162        return Bitmap.createBitmap(mDefaultIcon);
163    }
164
165    public void unbindWorkspaceItems() {
166        sWorker.post(new Runnable() {
167            @Override
168            public void run() {
169                unbindWorkspaceItemsOnMainThread();
170            }
171        });
172    }
173
174    /** Unbinds all the sWorkspaceItems on the main thread, and return a copy of sWorkspaceItems
175     * that is save to reference from the main thread. */
176    private ArrayList<ItemInfo> unbindWorkspaceItemsOnMainThread() {
177        // Ensure that we don't use the same workspace items data structure on the main thread
178        // by making a copy of workspace items first.
179        final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(sWorkspaceItems);
180        final ArrayList<ItemInfo> appWidgets = new ArrayList<ItemInfo>(sAppWidgets);
181        mHandler.post(new Runnable() {
182            @Override
183            public void run() {
184               for (ItemInfo item : workspaceItems) {
185                   item.unbind();
186               }
187               for (ItemInfo item : appWidgets) {
188                   item.unbind();
189               }
190            }
191        });
192
193        return workspaceItems;
194    }
195
196    /**
197     * Adds an item to the DB if it was not created previously, or move it to a new
198     * <container, screen, cellX, cellY>
199     */
200    static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
201            int screen, int cellX, int cellY) {
202        if (item.container == ItemInfo.NO_ID) {
203            // From all apps
204            addItemToDatabase(context, item, container, screen, cellX, cellY, false);
205        } else {
206            // From somewhere else
207            moveItemInDatabase(context, item, container, screen, cellX, cellY);
208        }
209    }
210
211    static void updateItemInDatabaseHelper(Context context, final ContentValues values,
212            final ItemInfo item, final String callingFunction) {
213        final long itemId = item.id;
214        final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
215        final ContentResolver cr = context.getContentResolver();
216
217        Runnable r = new Runnable() {
218            public void run() {
219                cr.update(uri, values, null, null);
220
221                ItemInfo modelItem = sItemsIdMap.get(itemId);
222                if (item != modelItem) {
223                    // the modelItem needs to match up perfectly with item if our model is to be
224                    // consistent with the database-- for now, just require modelItem == item
225                    String msg = "item: " + ((item != null) ? item.toString() : "null") +
226                        "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
227                        "Error: ItemInfo passed to " + callingFunction + " doesn't match original";
228                    throw new RuntimeException(msg);
229                }
230
231                // Items are added/removed from the corresponding FolderInfo elsewhere, such
232                // as in Workspace.onDrop. Here, we just add/remove them from the list of items
233                // that are on the desktop, as appropriate
234                if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
235                        modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
236                    if (!sWorkspaceItems.contains(modelItem)) {
237                        sWorkspaceItems.add(modelItem);
238                    }
239                } else {
240                    sWorkspaceItems.remove(modelItem);
241                }
242            }
243        };
244
245        if (sWorkerThread.getThreadId() == Process.myTid()) {
246            r.run();
247        } else {
248            sWorker.post(r);
249        }
250    }
251
252    /**
253     * Move an item in the DB to a new <container, screen, cellX, cellY>
254     */
255    static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
256            final int screen, final int cellX, final int cellY) {
257        item.container = container;
258        item.cellX = cellX;
259        item.cellY = cellY;
260
261        // We store hotseat items in canonical form which is this orientation invariant position
262        // in the hotseat
263        if (context instanceof Launcher && screen < 0 &&
264                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
265            item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
266        } else {
267            item.screen = screen;
268        }
269
270        final ContentValues values = new ContentValues();
271        values.put(LauncherSettings.Favorites.CONTAINER, item.container);
272        values.put(LauncherSettings.Favorites.CELLX, item.cellX);
273        values.put(LauncherSettings.Favorites.CELLY, item.cellY);
274        values.put(LauncherSettings.Favorites.SCREEN, item.screen);
275
276        updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
277    }
278
279    /**
280     * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
281     */
282    static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
283            final int screen, final int cellX, final int cellY, final int spanX, final int spanY) {
284        item.container = container;
285        item.cellX = cellX;
286        item.cellY = cellY;
287        item.spanX = spanX;
288        item.spanY = spanY;
289
290        // We store hotseat items in canonical form which is this orientation invariant position
291        // in the hotseat
292        if (context instanceof Launcher && screen < 0 &&
293                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
294            item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
295        } else {
296            item.screen = screen;
297        }
298
299        final ContentValues values = new ContentValues();
300        values.put(LauncherSettings.Favorites.CONTAINER, item.container);
301        values.put(LauncherSettings.Favorites.CELLX, item.cellX);
302        values.put(LauncherSettings.Favorites.CELLY, item.cellY);
303        values.put(LauncherSettings.Favorites.SPANX, item.spanX);
304        values.put(LauncherSettings.Favorites.SPANY, item.spanY);
305        values.put(LauncherSettings.Favorites.SCREEN, item.screen);
306
307        updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
308    }
309
310    /**
311     * Update an item to the database in a specified container.
312     */
313    static void updateItemInDatabase(Context context, final ItemInfo item) {
314        final ContentValues values = new ContentValues();
315        item.onAddToDatabase(values);
316        item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
317        updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
318    }
319
320    /**
321     * Returns true if the shortcuts already exists in the database.
322     * we identify a shortcut by its title and intent.
323     */
324    static boolean shortcutExists(Context context, String title, Intent intent) {
325        final ContentResolver cr = context.getContentResolver();
326        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
327            new String[] { "title", "intent" }, "title=? and intent=?",
328            new String[] { title, intent.toUri(0) }, null);
329        boolean result = false;
330        try {
331            result = c.moveToFirst();
332        } finally {
333            c.close();
334        }
335        return result;
336    }
337
338    /**
339     * Returns an ItemInfo array containing all the items in the LauncherModel.
340     * The ItemInfo.id is not set through this function.
341     */
342    static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
343        ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
344        final ContentResolver cr = context.getContentResolver();
345        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
346                LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
347                LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
348                LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
349
350        final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
351        final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
352        final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
353        final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
354        final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
355        final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
356        final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
357
358        try {
359            while (c.moveToNext()) {
360                ItemInfo item = new ItemInfo();
361                item.cellX = c.getInt(cellXIndex);
362                item.cellY = c.getInt(cellYIndex);
363                item.spanX = c.getInt(spanXIndex);
364                item.spanY = c.getInt(spanYIndex);
365                item.container = c.getInt(containerIndex);
366                item.itemType = c.getInt(itemTypeIndex);
367                item.screen = c.getInt(screenIndex);
368
369                items.add(item);
370            }
371        } catch (Exception e) {
372            items.clear();
373        } finally {
374            c.close();
375        }
376
377        return items;
378    }
379
380    /**
381     * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
382     */
383    FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
384        final ContentResolver cr = context.getContentResolver();
385        Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
386                "_id=? and (itemType=? or itemType=?)",
387                new String[] { String.valueOf(id),
388                        String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
389
390        try {
391            if (c.moveToFirst()) {
392                final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
393                final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
394                final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
395                final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
396                final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
397                final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
398
399                FolderInfo folderInfo = null;
400                switch (c.getInt(itemTypeIndex)) {
401                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
402                        folderInfo = findOrMakeFolder(folderList, id);
403                        break;
404                }
405
406                folderInfo.title = c.getString(titleIndex);
407                folderInfo.id = id;
408                folderInfo.container = c.getInt(containerIndex);
409                folderInfo.screen = c.getInt(screenIndex);
410                folderInfo.cellX = c.getInt(cellXIndex);
411                folderInfo.cellY = c.getInt(cellYIndex);
412
413                return folderInfo;
414            }
415        } finally {
416            c.close();
417        }
418
419        return null;
420    }
421
422    /**
423     * Add an item to the database in a specified container. Sets the container, screen, cellX and
424     * cellY fields of the item. Also assigns an ID to the item.
425     */
426    static void addItemToDatabase(Context context, final ItemInfo item, final long container,
427            final int screen, final int cellX, final int cellY, final boolean notify) {
428        item.container = container;
429        item.cellX = cellX;
430        item.cellY = cellY;
431        // We store hotseat items in canonical form which is this orientation invariant position
432        // in the hotseat
433        if (context instanceof Launcher && screen < 0 &&
434                container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
435            item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
436        } else {
437            item.screen = screen;
438        }
439
440        final ContentValues values = new ContentValues();
441        final ContentResolver cr = context.getContentResolver();
442        item.onAddToDatabase(values);
443
444        LauncherApplication app = (LauncherApplication) context.getApplicationContext();
445        item.id = app.getLauncherProvider().generateNewId();
446        values.put(LauncherSettings.Favorites._ID, item.id);
447        item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
448
449        Runnable r = new Runnable() {
450            public void run() {
451                cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
452                        LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
453
454                if (sItemsIdMap.containsKey(item.id)) {
455                    // we should not be adding new items in the db with the same id
456                    throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
457                        "addItemToDatabase already exists." + item.toString());
458                }
459                sItemsIdMap.put(item.id, item);
460                switch (item.itemType) {
461                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
462                        sFolders.put(item.id, (FolderInfo) item);
463                        // Fall through
464                    case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
465                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
466                        if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
467                                item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
468                            sWorkspaceItems.add(item);
469                        }
470                        break;
471                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
472                        sAppWidgets.add((LauncherAppWidgetInfo) item);
473                        break;
474                }
475            }
476        };
477
478        if (sWorkerThread.getThreadId() == Process.myTid()) {
479            r.run();
480        } else {
481            sWorker.post(r);
482        }
483    }
484
485    /**
486     * Creates a new unique child id, for a given cell span across all layouts.
487     */
488    static int getCellLayoutChildId(
489            long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
490        return (((int) container & 0xFF) << 24)
491                | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
492    }
493
494    static int getCellCountX() {
495        return mCellCountX;
496    }
497
498    static int getCellCountY() {
499        return mCellCountY;
500    }
501
502    /**
503     * Updates the model orientation helper to take into account the current layout dimensions
504     * when performing local/canonical coordinate transformations.
505     */
506    static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
507        mCellCountX = shortAxisCellCount;
508        mCellCountY = longAxisCellCount;
509    }
510
511    /**
512     * Removes the specified item from the database
513     * @param context
514     * @param item
515     */
516    static void deleteItemFromDatabase(Context context, final ItemInfo item) {
517        final ContentResolver cr = context.getContentResolver();
518        final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
519        Runnable r = new Runnable() {
520            public void run() {
521                cr.delete(uriToDelete, null, null);
522                switch (item.itemType) {
523                    case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
524                        sFolders.remove(item.id);
525                        sWorkspaceItems.remove(item);
526                        break;
527                    case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
528                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
529                        sWorkspaceItems.remove(item);
530                        break;
531                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
532                        sAppWidgets.remove((LauncherAppWidgetInfo) item);
533                        break;
534                }
535                sItemsIdMap.remove(item.id);
536                sDbIconCache.remove(item);
537            }
538        };
539        if (sWorkerThread.getThreadId() == Process.myTid()) {
540            r.run();
541        } else {
542            sWorker.post(r);
543        }
544    }
545
546    /**
547     * Remove the contents of the specified folder from the database
548     */
549    static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
550        final ContentResolver cr = context.getContentResolver();
551
552        Runnable r = new Runnable() {
553            public void run() {
554                cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
555                sItemsIdMap.remove(info.id);
556                sFolders.remove(info.id);
557                sDbIconCache.remove(info);
558                sWorkspaceItems.remove(info);
559
560                cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
561                        LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
562                for (ItemInfo childInfo : info.contents) {
563                    sItemsIdMap.remove(childInfo.id);
564                    sDbIconCache.remove(childInfo);
565                }
566            }
567        };
568        if (sWorkerThread.getThreadId() == Process.myTid()) {
569            r.run();
570        } else {
571            sWorker.post(r);
572        }
573    }
574
575    /**
576     * Set this as the current Launcher activity object for the loader.
577     */
578    public void initialize(Callbacks callbacks) {
579        synchronized (mLock) {
580            mCallbacks = new WeakReference<Callbacks>(callbacks);
581        }
582    }
583
584    /**
585     * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
586     * ACTION_PACKAGE_CHANGED.
587     */
588    @Override
589    public void onReceive(Context context, Intent intent) {
590        if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
591
592        final String action = intent.getAction();
593
594        if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
595                || Intent.ACTION_PACKAGE_REMOVED.equals(action)
596                || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
597            final String packageName = intent.getData().getSchemeSpecificPart();
598            final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
599
600            int op = PackageUpdatedTask.OP_NONE;
601
602            if (packageName == null || packageName.length() == 0) {
603                // they sent us a bad intent
604                return;
605            }
606
607            if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
608                op = PackageUpdatedTask.OP_UPDATE;
609            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
610                if (!replacing) {
611                    op = PackageUpdatedTask.OP_REMOVE;
612                }
613                // else, we are replacing the package, so a PACKAGE_ADDED will be sent
614                // later, we will update the package at this time
615            } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
616                if (!replacing) {
617                    op = PackageUpdatedTask.OP_ADD;
618                } else {
619                    op = PackageUpdatedTask.OP_UPDATE;
620                }
621            }
622
623            if (op != PackageUpdatedTask.OP_NONE) {
624                enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
625            }
626
627        } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
628            // First, schedule to add these apps back in.
629            String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
630            enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
631            // Then, rebind everything.
632            startLoaderFromBackground();
633        } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
634            String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
635            enqueuePackageUpdated(new PackageUpdatedTask(
636                        PackageUpdatedTask.OP_UNAVAILABLE, packages));
637        } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
638            // If we have changed locale we need to clear out the labels in all apps/workspace.
639            forceReload();
640        } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
641             // Check if configuration change was an mcc/mnc change which would affect app resources
642             // and we would need to clear out the labels in all apps/workspace. Same handling as
643             // above for ACTION_LOCALE_CHANGED
644             Configuration currentConfig = context.getResources().getConfiguration();
645             if (mPreviousConfigMcc != currentConfig.mcc) {
646                   Log.d(TAG, "Reload apps on config change. curr_mcc:"
647                       + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
648                   forceReload();
649             }
650             // Update previousConfig
651             mPreviousConfigMcc = currentConfig.mcc;
652        } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
653                   SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
654            if (mCallbacks != null) {
655                Callbacks callbacks = mCallbacks.get();
656                if (callbacks != null) {
657                    callbacks.bindSearchablesChanged();
658                }
659            }
660        }
661    }
662
663    private void forceReload() {
664        resetLoadedState(true, true);
665
666        // Do this here because if the launcher activity is running it will be restarted.
667        // If it's not running startLoaderFromBackground will merely tell it that it needs
668        // to reload.
669        startLoaderFromBackground();
670    }
671
672    public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
673        synchronized (mLock) {
674            // Stop any existing loaders first, so they don't set mAllAppsLoaded or
675            // mWorkspaceLoaded to true later
676            stopLoaderLocked();
677            if (resetAllAppsLoaded) mAllAppsLoaded = false;
678            if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
679        }
680    }
681
682    /**
683     * When the launcher is in the background, it's possible for it to miss paired
684     * configuration changes.  So whenever we trigger the loader from the background
685     * tell the launcher that it needs to re-run the loader when it comes back instead
686     * of doing it now.
687     */
688    public void startLoaderFromBackground() {
689        boolean runLoader = false;
690        if (mCallbacks != null) {
691            Callbacks callbacks = mCallbacks.get();
692            if (callbacks != null) {
693                // Only actually run the loader if they're not paused.
694                if (!callbacks.setLoadOnResume()) {
695                    runLoader = true;
696                }
697            }
698        }
699        if (runLoader) {
700            startLoader(false);
701        }
702    }
703
704    // If there is already a loader task running, tell it to stop.
705    // returns true if isLaunching() was true on the old task
706    private boolean stopLoaderLocked() {
707        boolean isLaunching = false;
708        LoaderTask oldTask = mLoaderTask;
709        if (oldTask != null) {
710            if (oldTask.isLaunching()) {
711                isLaunching = true;
712            }
713            oldTask.stopLocked();
714        }
715        return isLaunching;
716    }
717
718    public void startLoader(boolean isLaunching) {
719        synchronized (mLock) {
720            if (DEBUG_LOADERS) {
721                Log.d(TAG, "startLoader isLaunching=" + isLaunching);
722            }
723
724            // Don't bother to start the thread if we know it's not going to do anything
725            if (mCallbacks != null && mCallbacks.get() != null) {
726                // If there is already one running, tell it to stop.
727                // also, don't downgrade isLaunching if we're already running
728                isLaunching = isLaunching || stopLoaderLocked();
729                mLoaderTask = new LoaderTask(mApp, isLaunching);
730                sWorkerThread.setPriority(Thread.NORM_PRIORITY);
731                sWorker.post(mLoaderTask);
732            }
733        }
734    }
735
736    public void stopLoader() {
737        synchronized (mLock) {
738            if (mLoaderTask != null) {
739                mLoaderTask.stopLocked();
740            }
741        }
742    }
743
744    public boolean isAllAppsLoaded() {
745        return mAllAppsLoaded;
746    }
747
748    /**
749     * Runnable for the thread that loads the contents of the launcher:
750     *   - workspace icons
751     *   - widgets
752     *   - all apps icons
753     */
754    private class LoaderTask implements Runnable {
755        private Context mContext;
756        private Thread mWaitThread;
757        private boolean mIsLaunching;
758        private boolean mStopped;
759        private boolean mLoadAndBindStepFinished;
760        private HashMap<Object, CharSequence> mLabelCache;
761
762        LoaderTask(Context context, boolean isLaunching) {
763            mContext = context;
764            mIsLaunching = isLaunching;
765            mLabelCache = new HashMap<Object, CharSequence>();
766        }
767
768        boolean isLaunching() {
769            return mIsLaunching;
770        }
771
772        private void loadAndBindWorkspace() {
773            // Load the workspace
774            if (DEBUG_LOADERS) {
775                Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
776            }
777
778            if (!mWorkspaceLoaded) {
779                loadWorkspace();
780                synchronized (LoaderTask.this) {
781                    if (mStopped) {
782                        return;
783                    }
784                    mWorkspaceLoaded = true;
785                }
786            }
787
788            // Bind the workspace
789            bindWorkspace();
790        }
791
792        private void waitForIdle() {
793            // Wait until the either we're stopped or the other threads are done.
794            // This way we don't start loading all apps until the workspace has settled
795            // down.
796            synchronized (LoaderTask.this) {
797                final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
798
799                mHandler.postIdle(new Runnable() {
800                        public void run() {
801                            synchronized (LoaderTask.this) {
802                                mLoadAndBindStepFinished = true;
803                                if (DEBUG_LOADERS) {
804                                    Log.d(TAG, "done with previous binding step");
805                                }
806                                LoaderTask.this.notify();
807                            }
808                        }
809                    });
810
811                while (!mStopped && !mLoadAndBindStepFinished) {
812                    try {
813                        this.wait();
814                    } catch (InterruptedException ex) {
815                        // Ignore
816                    }
817                }
818                if (DEBUG_LOADERS) {
819                    Log.d(TAG, "waited "
820                            + (SystemClock.uptimeMillis()-workspaceWaitTime)
821                            + "ms for previous step to finish binding");
822                }
823            }
824        }
825
826        public void run() {
827            // Optimize for end-user experience: if the Launcher is up and // running with the
828            // All Apps interface in the foreground, load All Apps first. Otherwise, load the
829            // workspace first (default).
830            final Callbacks cbk = mCallbacks.get();
831            final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
832
833            keep_running: {
834                // Elevate priority when Home launches for the first time to avoid
835                // starving at boot time. Staring at a blank home is not cool.
836                synchronized (mLock) {
837                    if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
838                            (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
839                    android.os.Process.setThreadPriority(mIsLaunching
840                            ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
841                }
842                if (loadWorkspaceFirst) {
843                    if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
844                    loadAndBindWorkspace();
845                } else {
846                    if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
847                    loadAndBindAllApps();
848                }
849
850                if (mStopped) {
851                    break keep_running;
852                }
853
854                // Whew! Hard work done.  Slow us down, and wait until the UI thread has
855                // settled down.
856                synchronized (mLock) {
857                    if (mIsLaunching) {
858                        if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
859                        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
860                    }
861                }
862                waitForIdle();
863
864                // second step
865                if (loadWorkspaceFirst) {
866                    if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
867                    loadAndBindAllApps();
868                } else {
869                    if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
870                    loadAndBindWorkspace();
871                }
872
873                // Restore the default thread priority after we are done loading items
874                synchronized (mLock) {
875                    android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
876                }
877            }
878
879
880            // Update the saved icons if necessary
881            if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
882            for (Object key : sDbIconCache.keySet()) {
883                updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
884            }
885            sDbIconCache.clear();
886
887            // Clear out this reference, otherwise we end up holding it until all of the
888            // callback runnables are done.
889            mContext = null;
890
891            synchronized (mLock) {
892                // If we are still the last one to be scheduled, remove ourselves.
893                if (mLoaderTask == this) {
894                    mLoaderTask = null;
895                }
896            }
897        }
898
899        public void stopLocked() {
900            synchronized (LoaderTask.this) {
901                mStopped = true;
902                this.notify();
903            }
904        }
905
906        /**
907         * Gets the callbacks object.  If we've been stopped, or if the launcher object
908         * has somehow been garbage collected, return null instead.  Pass in the Callbacks
909         * object that was around when the deferred message was scheduled, and if there's
910         * a new Callbacks object around then also return null.  This will save us from
911         * calling onto it with data that will be ignored.
912         */
913        Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
914            synchronized (mLock) {
915                if (mStopped) {
916                    return null;
917                }
918
919                if (mCallbacks == null) {
920                    return null;
921                }
922
923                final Callbacks callbacks = mCallbacks.get();
924                if (callbacks != oldCallbacks) {
925                    return null;
926                }
927                if (callbacks == null) {
928                    Log.w(TAG, "no mCallbacks");
929                    return null;
930                }
931
932                return callbacks;
933            }
934        }
935
936        // check & update map of what's occupied; used to discard overlapping/invalid items
937        private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
938            int containerIndex = item.screen;
939            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
940                // Return early if we detect that an item is under the hotseat button
941                if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
942                    return false;
943                }
944
945                // We use the last index to refer to the hotseat and the screen as the rank, so
946                // test and update the occupied state accordingly
947                if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
948                    Log.e(TAG, "Error loading shortcut into hotseat " + item
949                        + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
950                        + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
951                    return false;
952                } else {
953                    occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
954                    return true;
955                }
956            } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
957                // Skip further checking if it is not the hotseat or workspace container
958                return true;
959            }
960
961            // Check if any workspace icons overlap with each other
962            for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
963                for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
964                    if (occupied[containerIndex][x][y] != null) {
965                        Log.e(TAG, "Error loading shortcut " + item
966                            + " into cell (" + containerIndex + "-" + item.screen + ":"
967                            + x + "," + y
968                            + ") occupied by "
969                            + occupied[containerIndex][x][y]);
970                        return false;
971                    }
972                }
973            }
974            for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
975                for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
976                    occupied[containerIndex][x][y] = item;
977                }
978            }
979
980            return true;
981        }
982
983        private void loadWorkspace() {
984            final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
985
986            final Context context = mContext;
987            final ContentResolver contentResolver = context.getContentResolver();
988            final PackageManager manager = context.getPackageManager();
989            final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
990            final boolean isSafeMode = manager.isSafeMode();
991
992            // Make sure the default workspace is loaded, if needed
993            mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary();
994
995            sWorkspaceItems.clear();
996            sAppWidgets.clear();
997            sFolders.clear();
998            sItemsIdMap.clear();
999            sDbIconCache.clear();
1000
1001            final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
1002
1003            final Cursor c = contentResolver.query(
1004                    LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
1005
1006            // +1 for the hotseat (it can be larger than the workspace)
1007            // Load workspace in reverse order to ensure that latest items are loaded first (and
1008            // before any earlier duplicates)
1009            final ItemInfo occupied[][][] =
1010                    new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
1011
1012            try {
1013                final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1014                final int intentIndex = c.getColumnIndexOrThrow
1015                        (LauncherSettings.Favorites.INTENT);
1016                final int titleIndex = c.getColumnIndexOrThrow
1017                        (LauncherSettings.Favorites.TITLE);
1018                final int iconTypeIndex = c.getColumnIndexOrThrow(
1019                        LauncherSettings.Favorites.ICON_TYPE);
1020                final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1021                final int iconPackageIndex = c.getColumnIndexOrThrow(
1022                        LauncherSettings.Favorites.ICON_PACKAGE);
1023                final int iconResourceIndex = c.getColumnIndexOrThrow(
1024                        LauncherSettings.Favorites.ICON_RESOURCE);
1025                final int containerIndex = c.getColumnIndexOrThrow(
1026                        LauncherSettings.Favorites.CONTAINER);
1027                final int itemTypeIndex = c.getColumnIndexOrThrow(
1028                        LauncherSettings.Favorites.ITEM_TYPE);
1029                final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1030                        LauncherSettings.Favorites.APPWIDGET_ID);
1031                final int screenIndex = c.getColumnIndexOrThrow(
1032                        LauncherSettings.Favorites.SCREEN);
1033                final int cellXIndex = c.getColumnIndexOrThrow
1034                        (LauncherSettings.Favorites.CELLX);
1035                final int cellYIndex = c.getColumnIndexOrThrow
1036                        (LauncherSettings.Favorites.CELLY);
1037                final int spanXIndex = c.getColumnIndexOrThrow
1038                        (LauncherSettings.Favorites.SPANX);
1039                final int spanYIndex = c.getColumnIndexOrThrow(
1040                        LauncherSettings.Favorites.SPANY);
1041                //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1042                //final int displayModeIndex = c.getColumnIndexOrThrow(
1043                //        LauncherSettings.Favorites.DISPLAY_MODE);
1044
1045                ShortcutInfo info;
1046                String intentDescription;
1047                LauncherAppWidgetInfo appWidgetInfo;
1048                int container;
1049                long id;
1050                Intent intent;
1051
1052                while (!mStopped && c.moveToNext()) {
1053                    try {
1054                        int itemType = c.getInt(itemTypeIndex);
1055
1056                        switch (itemType) {
1057                        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1058                        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1059                            intentDescription = c.getString(intentIndex);
1060                            try {
1061                                intent = Intent.parseUri(intentDescription, 0);
1062                            } catch (URISyntaxException e) {
1063                                continue;
1064                            }
1065
1066                            if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1067                                info = getShortcutInfo(manager, intent, context, c, iconIndex,
1068                                        titleIndex, mLabelCache);
1069                            } else {
1070                                info = getShortcutInfo(c, context, iconTypeIndex,
1071                                        iconPackageIndex, iconResourceIndex, iconIndex,
1072                                        titleIndex);
1073
1074                                // App shortcuts that used to be automatically added to Launcher
1075                                // didn't always have the correct intent flags set, so do that here
1076                                if (intent.getAction().equals(Intent.ACTION_MAIN) &&
1077                                        intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
1078                                    intent.addFlags(
1079                                        Intent.FLAG_ACTIVITY_NEW_TASK |
1080                                        Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1081                                }
1082                            }
1083
1084                            if (info != null) {
1085                                info.intent = intent;
1086                                info.id = c.getLong(idIndex);
1087                                container = c.getInt(containerIndex);
1088                                info.container = container;
1089                                info.screen = c.getInt(screenIndex);
1090                                info.cellX = c.getInt(cellXIndex);
1091                                info.cellY = c.getInt(cellYIndex);
1092
1093                                // check & update map of what's occupied
1094                                if (!checkItemPlacement(occupied, info)) {
1095                                    break;
1096                                }
1097
1098                                switch (container) {
1099                                case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1100                                case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1101                                    sWorkspaceItems.add(info);
1102                                    break;
1103                                default:
1104                                    // Item is in a user folder
1105                                    FolderInfo folderInfo =
1106                                            findOrMakeFolder(sFolders, container);
1107                                    folderInfo.add(info);
1108                                    break;
1109                                }
1110                                sItemsIdMap.put(info.id, info);
1111
1112                                // now that we've loaded everthing re-save it with the
1113                                // icon in case it disappears somehow.
1114                                queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
1115                            } else {
1116                                // Failed to load the shortcut, probably because the
1117                                // activity manager couldn't resolve it (maybe the app
1118                                // was uninstalled), or the db row was somehow screwed up.
1119                                // Delete it.
1120                                id = c.getLong(idIndex);
1121                                Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1122                                contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1123                                            id, false), null, null);
1124                            }
1125                            break;
1126
1127                        case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1128                            id = c.getLong(idIndex);
1129                            FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
1130
1131                            folderInfo.title = c.getString(titleIndex);
1132                            folderInfo.id = id;
1133                            container = c.getInt(containerIndex);
1134                            folderInfo.container = container;
1135                            folderInfo.screen = c.getInt(screenIndex);
1136                            folderInfo.cellX = c.getInt(cellXIndex);
1137                            folderInfo.cellY = c.getInt(cellYIndex);
1138
1139                            // check & update map of what's occupied
1140                            if (!checkItemPlacement(occupied, folderInfo)) {
1141                                break;
1142                            }
1143                            switch (container) {
1144                                case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1145                                case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1146                                    sWorkspaceItems.add(folderInfo);
1147                                    break;
1148                            }
1149
1150                            sItemsIdMap.put(folderInfo.id, folderInfo);
1151                            sFolders.put(folderInfo.id, folderInfo);
1152                            break;
1153
1154                        case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1155                            // Read all Launcher-specific widget details
1156                            int appWidgetId = c.getInt(appWidgetIdIndex);
1157                            id = c.getLong(idIndex);
1158
1159                            final AppWidgetProviderInfo provider =
1160                                    widgets.getAppWidgetInfo(appWidgetId);
1161
1162                            if (!isSafeMode && (provider == null || provider.provider == null ||
1163                                    provider.provider.getPackageName() == null)) {
1164                                String log = "Deleting widget that isn't installed anymore: id="
1165                                    + id + " appWidgetId=" + appWidgetId;
1166                                Log.e(TAG, log);
1167                                Launcher.sDumpLogs.add(log);
1168                                itemsToRemove.add(id);
1169                            } else {
1170                                appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1171                                        provider.provider);
1172                                appWidgetInfo.id = id;
1173                                appWidgetInfo.screen = c.getInt(screenIndex);
1174                                appWidgetInfo.cellX = c.getInt(cellXIndex);
1175                                appWidgetInfo.cellY = c.getInt(cellYIndex);
1176                                appWidgetInfo.spanX = c.getInt(spanXIndex);
1177                                appWidgetInfo.spanY = c.getInt(spanYIndex);
1178                                int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1179                                appWidgetInfo.minSpanX = minSpan[0];
1180                                appWidgetInfo.minSpanY = minSpan[1];
1181
1182                                container = c.getInt(containerIndex);
1183                                if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1184                                    container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1185                                    Log.e(TAG, "Widget found where container "
1186                                        + "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1187                                    continue;
1188                                }
1189                                appWidgetInfo.container = c.getInt(containerIndex);
1190
1191                                // check & update map of what's occupied
1192                                if (!checkItemPlacement(occupied, appWidgetInfo)) {
1193                                    break;
1194                                }
1195                                sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1196                                sAppWidgets.add(appWidgetInfo);
1197                            }
1198                            break;
1199                        }
1200                    } catch (Exception e) {
1201                        Log.w(TAG, "Desktop items loading interrupted:", e);
1202                    }
1203                }
1204            } finally {
1205                c.close();
1206            }
1207
1208            if (itemsToRemove.size() > 0) {
1209                ContentProviderClient client = contentResolver.acquireContentProviderClient(
1210                                LauncherSettings.Favorites.CONTENT_URI);
1211                // Remove dead items
1212                for (long id : itemsToRemove) {
1213                    if (DEBUG_LOADERS) {
1214                        Log.d(TAG, "Removed id = " + id);
1215                    }
1216                    // Don't notify content observers
1217                    try {
1218                        client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1219                                null, null);
1220                    } catch (RemoteException e) {
1221                        Log.w(TAG, "Could not remove id = " + id);
1222                    }
1223                }
1224            }
1225
1226            if (DEBUG_LOADERS) {
1227                Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1228                Log.d(TAG, "workspace layout: ");
1229                for (int y = 0; y < mCellCountY; y++) {
1230                    String line = "";
1231                    for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
1232                        if (s > 0) {
1233                            line += " | ";
1234                        }
1235                        for (int x = 0; x < mCellCountX; x++) {
1236                            line += ((occupied[s][x][y] != null) ? "#" : ".");
1237                        }
1238                    }
1239                    Log.d(TAG, "[ " + line + " ]");
1240                }
1241            }
1242        }
1243
1244        /**
1245         * Read everything out of our database.
1246         */
1247        private void bindWorkspace() {
1248            final long t = SystemClock.uptimeMillis();
1249
1250            // Don't use these two variables in any of the callback runnables.
1251            // Otherwise we hold a reference to them.
1252            final Callbacks oldCallbacks = mCallbacks.get();
1253            if (oldCallbacks == null) {
1254                // This launcher has exited and nobody bothered to tell us.  Just bail.
1255                Log.w(TAG, "LoaderTask running with no launcher");
1256                return;
1257            }
1258
1259            // Get the list of workspace items to load and unbind the existing ShortcutInfos
1260            // before we call startBinding() below.
1261            final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
1262            final ArrayList<ItemInfo> tmpWorkspaceItems = unbindWorkspaceItemsOnMainThread();
1263            // Order the items for loading as follows: current workspace, hotseat, everything else
1264            Collections.sort(tmpWorkspaceItems, new Comparator<ItemInfo>() {
1265                @Override
1266                public int compare(ItemInfo lhs, ItemInfo rhs) {
1267                    int cellCountX = LauncherModel.getCellCountX();
1268                    int cellCountY = LauncherModel.getCellCountY();
1269                    int screenOffset = cellCountX * cellCountY;
1270                    int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
1271                    long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
1272                            lhs.cellY * cellCountX + lhs.cellX);
1273                    long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
1274                            rhs.cellY * cellCountX + rhs.cellX);
1275                    return (int) (lr - rr);
1276                }
1277            });
1278            // Precondition: the items are ordered by page, screen
1279            final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
1280            for (ItemInfo ii : tmpWorkspaceItems) {
1281                // Prepend the current items, hotseat items, append everything else
1282                if (ii.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1283                        ii.screen == currentScreen) {
1284                    workspaceItems.add(0, ii);
1285                } else if (ii.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1286                    workspaceItems.add(0, ii);
1287                } else {
1288                    workspaceItems.add(ii);
1289                }
1290            }
1291
1292            // Tell the workspace that we're about to start firing items at it
1293            mHandler.post(new Runnable() {
1294                public void run() {
1295                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1296                    if (callbacks != null) {
1297                        callbacks.startBinding();
1298                    }
1299                }
1300            });
1301
1302            // Add the items to the workspace.
1303            int N = workspaceItems.size();
1304            for (int i=0; i<N; i+=ITEMS_CHUNK) {
1305                final int start = i;
1306                final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
1307                mHandler.post(new Runnable() {
1308                    public void run() {
1309                        Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1310                        if (callbacks != null) {
1311                            callbacks.bindItems(workspaceItems, start, start+chunkSize);
1312                        }
1313                    }
1314                });
1315            }
1316            // Ensure that we don't use the same folders data structure on the main thread
1317            final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders);
1318            mHandler.post(new Runnable() {
1319                public void run() {
1320                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1321                    if (callbacks != null) {
1322                        callbacks.bindFolders(folders);
1323                    }
1324                }
1325            });
1326            // Wait until the queue goes empty.
1327            mHandler.post(new Runnable() {
1328                public void run() {
1329                    if (DEBUG_LOADERS) {
1330                        Log.d(TAG, "Going to start binding widgets soon.");
1331                    }
1332                }
1333            });
1334            // Bind the widgets, one at a time.
1335            // WARNING: this is calling into the workspace from the background thread,
1336            // but since getCurrentScreen() just returns the int, we should be okay.  This
1337            // is just a hint for the order, and if it's wrong, we'll be okay.
1338            // TODO: instead, we should have that push the current screen into here.
1339            N = sAppWidgets.size();
1340            // once for the current screen
1341            for (int i=0; i<N; i++) {
1342                final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
1343                if (widget.screen == currentScreen) {
1344                    mHandler.post(new Runnable() {
1345                        public void run() {
1346                            Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1347                            if (callbacks != null) {
1348                                callbacks.bindAppWidget(widget);
1349                            }
1350                        }
1351                    });
1352                }
1353            }
1354            // once for the other screens
1355            for (int i=0; i<N; i++) {
1356                final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
1357                if (widget.screen != currentScreen) {
1358                    mHandler.post(new Runnable() {
1359                        public void run() {
1360                            Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1361                            if (callbacks != null) {
1362                                callbacks.bindAppWidget(widget);
1363                            }
1364                        }
1365                    });
1366                }
1367            }
1368            // Tell the workspace that we're done.
1369            mHandler.post(new Runnable() {
1370                public void run() {
1371                    Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1372                    if (callbacks != null) {
1373                        callbacks.finishBindingItems();
1374                    }
1375                }
1376            });
1377            // If we're profiling, this is the last thing in the queue.
1378            mHandler.post(new Runnable() {
1379                public void run() {
1380                    if (DEBUG_LOADERS) {
1381                        Log.d(TAG, "bound workspace in "
1382                            + (SystemClock.uptimeMillis()-t) + "ms");
1383                    }
1384                }
1385            });
1386        }
1387
1388        private void loadAndBindAllApps() {
1389            if (DEBUG_LOADERS) {
1390                Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
1391            }
1392            if (!mAllAppsLoaded) {
1393                loadAllAppsByBatch();
1394                synchronized (LoaderTask.this) {
1395                    if (mStopped) {
1396                        return;
1397                    }
1398                    mAllAppsLoaded = true;
1399                }
1400            } else {
1401                onlyBindAllApps();
1402            }
1403        }
1404
1405        private void onlyBindAllApps() {
1406            final Callbacks oldCallbacks = mCallbacks.get();
1407            if (oldCallbacks == null) {
1408                // This launcher has exited and nobody bothered to tell us.  Just bail.
1409                Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1410                return;
1411            }
1412
1413            // shallow copy
1414            @SuppressWarnings("unchecked")
1415            final ArrayList<ApplicationInfo> list
1416                    = (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
1417            mHandler.post(new Runnable() {
1418                public void run() {
1419                    final long t = SystemClock.uptimeMillis();
1420                    final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1421                    if (callbacks != null) {
1422                        callbacks.bindAllApplications(list);
1423                    }
1424                    if (DEBUG_LOADERS) {
1425                        Log.d(TAG, "bound all " + list.size() + " apps from cache in "
1426                                + (SystemClock.uptimeMillis()-t) + "ms");
1427                    }
1428                }
1429            });
1430
1431        }
1432
1433        private void loadAllAppsByBatch() {
1434            final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1435
1436            // Don't use these two variables in any of the callback runnables.
1437            // Otherwise we hold a reference to them.
1438            final Callbacks oldCallbacks = mCallbacks.get();
1439            if (oldCallbacks == null) {
1440                // This launcher has exited and nobody bothered to tell us.  Just bail.
1441                Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
1442                return;
1443            }
1444
1445            final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1446            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1447
1448            final PackageManager packageManager = mContext.getPackageManager();
1449            List<ResolveInfo> apps = null;
1450
1451            int N = Integer.MAX_VALUE;
1452
1453            int startIndex;
1454            int i=0;
1455            int batchSize = -1;
1456            while (i < N && !mStopped) {
1457                if (i == 0) {
1458                    mAllAppsList.clear();
1459                    final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1460                    apps = packageManager.queryIntentActivities(mainIntent, 0);
1461                    if (DEBUG_LOADERS) {
1462                        Log.d(TAG, "queryIntentActivities took "
1463                                + (SystemClock.uptimeMillis()-qiaTime) + "ms");
1464                    }
1465                    if (apps == null) {
1466                        return;
1467                    }
1468                    N = apps.size();
1469                    if (DEBUG_LOADERS) {
1470                        Log.d(TAG, "queryIntentActivities got " + N + " apps");
1471                    }
1472                    if (N == 0) {
1473                        // There are no apps?!?
1474                        return;
1475                    }
1476                    if (mBatchSize == 0) {
1477                        batchSize = N;
1478                    } else {
1479                        batchSize = mBatchSize;
1480                    }
1481
1482                    final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1483                    Collections.sort(apps,
1484                            new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
1485                    if (DEBUG_LOADERS) {
1486                        Log.d(TAG, "sort took "
1487                                + (SystemClock.uptimeMillis()-sortTime) + "ms");
1488                    }
1489                }
1490
1491                final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1492
1493                startIndex = i;
1494                for (int j=0; i<N && j<batchSize; j++) {
1495                    // This builds the icon bitmaps.
1496                    mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
1497                            mIconCache, mLabelCache));
1498                    i++;
1499                }
1500
1501                final boolean first = i <= batchSize;
1502                final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1503                final ArrayList<ApplicationInfo> added = mAllAppsList.added;
1504                mAllAppsList.added = new ArrayList<ApplicationInfo>();
1505
1506                mHandler.post(new Runnable() {
1507                    public void run() {
1508                        final long t = SystemClock.uptimeMillis();
1509                        if (callbacks != null) {
1510                            if (first) {
1511                                callbacks.bindAllApplications(added);
1512                            } else {
1513                                callbacks.bindAppsAdded(added);
1514                            }
1515                            if (DEBUG_LOADERS) {
1516                                Log.d(TAG, "bound " + added.size() + " apps in "
1517                                    + (SystemClock.uptimeMillis() - t) + "ms");
1518                            }
1519                        } else {
1520                            Log.i(TAG, "not binding apps: no Launcher activity");
1521                        }
1522                    }
1523                });
1524
1525                if (DEBUG_LOADERS) {
1526                    Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
1527                            + (SystemClock.uptimeMillis()-t2) + "ms");
1528                }
1529
1530                if (mAllAppsLoadDelay > 0 && i < N) {
1531                    try {
1532                        if (DEBUG_LOADERS) {
1533                            Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
1534                        }
1535                        Thread.sleep(mAllAppsLoadDelay);
1536                    } catch (InterruptedException exc) { }
1537                }
1538            }
1539
1540            if (DEBUG_LOADERS) {
1541                Log.d(TAG, "cached all " + N + " apps in "
1542                        + (SystemClock.uptimeMillis()-t) + "ms"
1543                        + (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
1544            }
1545        }
1546
1547        public void dumpState() {
1548            Log.d(TAG, "mLoaderTask.mContext=" + mContext);
1549            Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
1550            Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
1551            Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
1552            Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
1553            Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
1554        }
1555    }
1556
1557    void enqueuePackageUpdated(PackageUpdatedTask task) {
1558        sWorker.post(task);
1559    }
1560
1561    private class PackageUpdatedTask implements Runnable {
1562        int mOp;
1563        String[] mPackages;
1564
1565        public static final int OP_NONE = 0;
1566        public static final int OP_ADD = 1;
1567        public static final int OP_UPDATE = 2;
1568        public static final int OP_REMOVE = 3; // uninstlled
1569        public static final int OP_UNAVAILABLE = 4; // external media unmounted
1570
1571
1572        public PackageUpdatedTask(int op, String[] packages) {
1573            mOp = op;
1574            mPackages = packages;
1575        }
1576
1577        public void run() {
1578            final Context context = mApp;
1579
1580            final String[] packages = mPackages;
1581            final int N = packages.length;
1582            switch (mOp) {
1583                case OP_ADD:
1584                    for (int i=0; i<N; i++) {
1585                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
1586                        mAllAppsList.addPackage(context, packages[i]);
1587                    }
1588                    break;
1589                case OP_UPDATE:
1590                    for (int i=0; i<N; i++) {
1591                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
1592                        mAllAppsList.updatePackage(context, packages[i]);
1593                    }
1594                    break;
1595                case OP_REMOVE:
1596                case OP_UNAVAILABLE:
1597                    for (int i=0; i<N; i++) {
1598                        if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
1599                        mAllAppsList.removePackage(packages[i]);
1600                    }
1601                    break;
1602            }
1603
1604            ArrayList<ApplicationInfo> added = null;
1605            ArrayList<ApplicationInfo> removed = null;
1606            ArrayList<ApplicationInfo> modified = null;
1607
1608            if (mAllAppsList.added.size() > 0) {
1609                added = mAllAppsList.added;
1610                mAllAppsList.added = new ArrayList<ApplicationInfo>();
1611            }
1612            if (mAllAppsList.removed.size() > 0) {
1613                removed = mAllAppsList.removed;
1614                mAllAppsList.removed = new ArrayList<ApplicationInfo>();
1615                for (ApplicationInfo info: removed) {
1616                    mIconCache.remove(info.intent.getComponent());
1617                }
1618            }
1619            if (mAllAppsList.modified.size() > 0) {
1620                modified = mAllAppsList.modified;
1621                mAllAppsList.modified = new ArrayList<ApplicationInfo>();
1622            }
1623
1624            final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
1625            if (callbacks == null) {
1626                Log.w(TAG, "Nobody to tell about the new app.  Launcher is probably loading.");
1627                return;
1628            }
1629
1630            if (added != null) {
1631                final ArrayList<ApplicationInfo> addedFinal = added;
1632                mHandler.post(new Runnable() {
1633                    public void run() {
1634                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1635                        if (callbacks == cb && cb != null) {
1636                            callbacks.bindAppsAdded(addedFinal);
1637                        }
1638                    }
1639                });
1640            }
1641            if (modified != null) {
1642                final ArrayList<ApplicationInfo> modifiedFinal = modified;
1643                mHandler.post(new Runnable() {
1644                    public void run() {
1645                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1646                        if (callbacks == cb && cb != null) {
1647                            callbacks.bindAppsUpdated(modifiedFinal);
1648                        }
1649                    }
1650                });
1651            }
1652            if (removed != null) {
1653                final boolean permanent = mOp != OP_UNAVAILABLE;
1654                final ArrayList<ApplicationInfo> removedFinal = removed;
1655                mHandler.post(new Runnable() {
1656                    public void run() {
1657                        Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1658                        if (callbacks == cb && cb != null) {
1659                            callbacks.bindAppsRemoved(removedFinal, permanent);
1660                        }
1661                    }
1662                });
1663            }
1664
1665            mHandler.post(new Runnable() {
1666                @Override
1667                public void run() {
1668                    Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1669                    if (callbacks == cb && cb != null) {
1670                        callbacks.bindPackagesUpdated();
1671                    }
1672                }
1673            });
1674        }
1675    }
1676
1677    /**
1678     * Returns all the Workspace ShortcutInfos associated with a particular package.
1679     * @param intent
1680     * @return
1681     */
1682    ArrayList<ShortcutInfo> getShortcutInfosForPackage(String packageName) {
1683        ArrayList<ShortcutInfo> infos = new ArrayList<ShortcutInfo>();
1684        for (ItemInfo i : sWorkspaceItems) {
1685            if (i instanceof ShortcutInfo) {
1686                ShortcutInfo info = (ShortcutInfo) i;
1687                if (info.intent.getComponent().getPackageName().equals(packageName)) {
1688                    infos.add(info);
1689                }
1690            }
1691        }
1692        return infos;
1693    }
1694
1695    /**
1696     * This is called from the code that adds shortcuts from the intent receiver.  This
1697     * doesn't have a Cursor, but
1698     */
1699    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
1700        return getShortcutInfo(manager, intent, context, null, -1, -1, null);
1701    }
1702
1703    /**
1704     * Make an ShortcutInfo object for a shortcut that is an application.
1705     *
1706     * If c is not null, then it will be used to fill in missing data like the title and icon.
1707     */
1708    public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
1709            Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
1710        Bitmap icon = null;
1711        final ShortcutInfo info = new ShortcutInfo();
1712
1713        ComponentName componentName = intent.getComponent();
1714        if (componentName == null) {
1715            return null;
1716        }
1717
1718        try {
1719            PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
1720            if (!pi.applicationInfo.enabled) {
1721                // If we return null here, the corresponding item will be removed from the launcher
1722                // db and will not appear in the workspace.
1723                return null;
1724            }
1725        } catch (NameNotFoundException e) {
1726            Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
1727        }
1728
1729        // TODO: See if the PackageManager knows about this case.  If it doesn't
1730        // then return null & delete this.
1731
1732        // the resource -- This may implicitly give us back the fallback icon,
1733        // but don't worry about that.  All we're doing with usingFallbackIcon is
1734        // to avoid saving lots of copies of that in the database, and most apps
1735        // have icons anyway.
1736
1737        // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
1738        // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
1739        // via resolveActivity().
1740        ResolveInfo resolveInfo = null;
1741        ComponentName oldComponent = intent.getComponent();
1742        Intent newIntent = new Intent(intent.getAction(), null);
1743        newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1744        newIntent.setPackage(oldComponent.getPackageName());
1745        List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
1746        for (ResolveInfo i : infos) {
1747            ComponentName cn = new ComponentName(i.activityInfo.packageName,
1748                    i.activityInfo.name);
1749            if (cn.equals(oldComponent)) {
1750                resolveInfo = i;
1751            }
1752        }
1753        if (resolveInfo == null) {
1754            resolveInfo = manager.resolveActivity(intent, 0);
1755        }
1756        if (resolveInfo != null) {
1757            icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
1758        }
1759        // the db
1760        if (icon == null) {
1761            if (c != null) {
1762                icon = getIconFromCursor(c, iconIndex, context);
1763            }
1764        }
1765        // the fallback icon
1766        if (icon == null) {
1767            icon = getFallbackIcon();
1768            info.usingFallbackIcon = true;
1769        }
1770        info.setIcon(icon);
1771
1772        // from the resource
1773        if (resolveInfo != null) {
1774            ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
1775            if (labelCache != null && labelCache.containsKey(key)) {
1776                info.title = labelCache.get(key);
1777            } else {
1778                info.title = resolveInfo.activityInfo.loadLabel(manager);
1779                if (labelCache != null) {
1780                    labelCache.put(key, info.title);
1781                }
1782            }
1783        }
1784        // from the db
1785        if (info.title == null) {
1786            if (c != null) {
1787                info.title =  c.getString(titleIndex);
1788            }
1789        }
1790        // fall back to the class name of the activity
1791        if (info.title == null) {
1792            info.title = componentName.getClassName();
1793        }
1794        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
1795        return info;
1796    }
1797
1798    /**
1799     * Make an ShortcutInfo object for a shortcut that isn't an application.
1800     */
1801    private ShortcutInfo getShortcutInfo(Cursor c, Context context,
1802            int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
1803            int titleIndex) {
1804
1805        Bitmap icon = null;
1806        final ShortcutInfo info = new ShortcutInfo();
1807        info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1808
1809        // TODO: If there's an explicit component and we can't install that, delete it.
1810
1811        info.title = c.getString(titleIndex);
1812
1813        int iconType = c.getInt(iconTypeIndex);
1814        switch (iconType) {
1815        case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
1816            String packageName = c.getString(iconPackageIndex);
1817            String resourceName = c.getString(iconResourceIndex);
1818            PackageManager packageManager = context.getPackageManager();
1819            info.customIcon = false;
1820            // the resource
1821            try {
1822                Resources resources = packageManager.getResourcesForApplication(packageName);
1823                if (resources != null) {
1824                    final int id = resources.getIdentifier(resourceName, null, null);
1825                    icon = Utilities.createIconBitmap(
1826                            mIconCache.getFullResIcon(resources, id), context);
1827                }
1828            } catch (Exception e) {
1829                // drop this.  we have other places to look for icons
1830            }
1831            // the db
1832            if (icon == null) {
1833                icon = getIconFromCursor(c, iconIndex, context);
1834            }
1835            // the fallback icon
1836            if (icon == null) {
1837                icon = getFallbackIcon();
1838                info.usingFallbackIcon = true;
1839            }
1840            break;
1841        case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
1842            icon = getIconFromCursor(c, iconIndex, context);
1843            if (icon == null) {
1844                icon = getFallbackIcon();
1845                info.customIcon = false;
1846                info.usingFallbackIcon = true;
1847            } else {
1848                info.customIcon = true;
1849            }
1850            break;
1851        default:
1852            icon = getFallbackIcon();
1853            info.usingFallbackIcon = true;
1854            info.customIcon = false;
1855            break;
1856        }
1857        info.setIcon(icon);
1858        return info;
1859    }
1860
1861    Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
1862        @SuppressWarnings("all") // suppress dead code warning
1863        final boolean debug = false;
1864        if (debug) {
1865            Log.d(TAG, "getIconFromCursor app="
1866                    + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
1867        }
1868        byte[] data = c.getBlob(iconIndex);
1869        try {
1870            return Utilities.createIconBitmap(
1871                    BitmapFactory.decodeByteArray(data, 0, data.length), context);
1872        } catch (Exception e) {
1873            return null;
1874        }
1875    }
1876
1877    ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
1878            int cellX, int cellY, boolean notify) {
1879        final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
1880        if (info == null) {
1881            return null;
1882        }
1883        addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
1884
1885        return info;
1886    }
1887
1888    /**
1889     * Attempts to find an AppWidgetProviderInfo that matches the given component.
1890     */
1891    AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
1892            ComponentName component) {
1893        List<AppWidgetProviderInfo> widgets =
1894            AppWidgetManager.getInstance(context).getInstalledProviders();
1895        for (AppWidgetProviderInfo info : widgets) {
1896            if (info.provider.equals(component)) {
1897                return info;
1898            }
1899        }
1900        return null;
1901    }
1902
1903    /**
1904     * Returns a list of all the widgets that can handle configuration with a particular mimeType.
1905     */
1906    List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
1907        final PackageManager packageManager = context.getPackageManager();
1908        final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
1909            new ArrayList<WidgetMimeTypeHandlerData>();
1910
1911        final Intent supportsIntent =
1912            new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
1913        supportsIntent.setType(mimeType);
1914
1915        // Create a set of widget configuration components that we can test against
1916        final List<AppWidgetProviderInfo> widgets =
1917            AppWidgetManager.getInstance(context).getInstalledProviders();
1918        final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
1919            new HashMap<ComponentName, AppWidgetProviderInfo>();
1920        for (AppWidgetProviderInfo info : widgets) {
1921            configurationComponentToWidget.put(info.configure, info);
1922        }
1923
1924        // Run through each of the intents that can handle this type of clip data, and cross
1925        // reference them with the components that are actual configuration components
1926        final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
1927                PackageManager.MATCH_DEFAULT_ONLY);
1928        for (ResolveInfo info : activities) {
1929            final ActivityInfo activityInfo = info.activityInfo;
1930            final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
1931                    activityInfo.name);
1932            if (configurationComponentToWidget.containsKey(infoComponent)) {
1933                supportedConfigurationActivities.add(
1934                        new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
1935                                configurationComponentToWidget.get(infoComponent)));
1936            }
1937        }
1938        return supportedConfigurationActivities;
1939    }
1940
1941    ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
1942        Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
1943        String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1944        Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
1945
1946        if (intent == null) {
1947            // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
1948            Log.e(TAG, "Can't construct ShorcutInfo with null intent");
1949            return null;
1950        }
1951
1952        Bitmap icon = null;
1953        boolean customIcon = false;
1954        ShortcutIconResource iconResource = null;
1955
1956        if (bitmap != null && bitmap instanceof Bitmap) {
1957            icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
1958            customIcon = true;
1959        } else {
1960            Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
1961            if (extra != null && extra instanceof ShortcutIconResource) {
1962                try {
1963                    iconResource = (ShortcutIconResource) extra;
1964                    final PackageManager packageManager = context.getPackageManager();
1965                    Resources resources = packageManager.getResourcesForApplication(
1966                            iconResource.packageName);
1967                    final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1968                    icon = Utilities.createIconBitmap(
1969                            mIconCache.getFullResIcon(resources, id), context);
1970                } catch (Exception e) {
1971                    Log.w(TAG, "Could not load shortcut icon: " + extra);
1972                }
1973            }
1974        }
1975
1976        final ShortcutInfo info = new ShortcutInfo();
1977
1978        if (icon == null) {
1979            if (fallbackIcon != null) {
1980                icon = fallbackIcon;
1981            } else {
1982                icon = getFallbackIcon();
1983                info.usingFallbackIcon = true;
1984            }
1985        }
1986        info.setIcon(icon);
1987
1988        info.title = name;
1989        info.intent = intent;
1990        info.customIcon = customIcon;
1991        info.iconResource = iconResource;
1992
1993        return info;
1994    }
1995
1996    boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
1997            int iconIndex) {
1998        // If apps can't be on SD, don't even bother.
1999        if (!mAppsCanBeOnExternalStorage) {
2000            return false;
2001        }
2002        // If this icon doesn't have a custom icon, check to see
2003        // what's stored in the DB, and if it doesn't match what
2004        // we're going to show, store what we are going to show back
2005        // into the DB.  We do this so when we're loading, if the
2006        // package manager can't find an icon (for example because
2007        // the app is on SD) then we can use that instead.
2008        if (!info.customIcon && !info.usingFallbackIcon) {
2009            cache.put(info, c.getBlob(iconIndex));
2010            return true;
2011        }
2012        return false;
2013    }
2014    void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2015        boolean needSave = false;
2016        try {
2017            if (data != null) {
2018                Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2019                Bitmap loaded = info.getIcon(mIconCache);
2020                needSave = !saved.sameAs(loaded);
2021            } else {
2022                needSave = true;
2023            }
2024        } catch (Exception e) {
2025            needSave = true;
2026        }
2027        if (needSave) {
2028            Log.d(TAG, "going to save icon bitmap for info=" + info);
2029            // This is slower than is ideal, but this only happens once
2030            // or when the app is updated with a new icon.
2031            updateItemInDatabase(context, info);
2032        }
2033    }
2034
2035    /**
2036     * Return an existing FolderInfo object if we have encountered this ID previously,
2037     * or make a new one.
2038     */
2039    private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
2040        // See if a placeholder was created for us already
2041        FolderInfo folderInfo = folders.get(id);
2042        if (folderInfo == null) {
2043            // No placeholder -- create a new instance
2044            folderInfo = new FolderInfo();
2045            folders.put(id, folderInfo);
2046        }
2047        return folderInfo;
2048    }
2049
2050    private static final Collator sCollator = Collator.getInstance();
2051    public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
2052            = new Comparator<ApplicationInfo>() {
2053        public final int compare(ApplicationInfo a, ApplicationInfo b) {
2054            int result = sCollator.compare(a.title.toString(), b.title.toString());
2055            if (result == 0) {
2056                result = a.componentName.compareTo(b.componentName);
2057            }
2058            return result;
2059        }
2060    };
2061    public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2062            = new Comparator<ApplicationInfo>() {
2063        public final int compare(ApplicationInfo a, ApplicationInfo b) {
2064            if (a.firstInstallTime < b.firstInstallTime) return 1;
2065            if (a.firstInstallTime > b.firstInstallTime) return -1;
2066            return 0;
2067        }
2068    };
2069    public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
2070            = new Comparator<AppWidgetProviderInfo>() {
2071        public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2072            return sCollator.compare(a.label.toString(), b.label.toString());
2073        }
2074    };
2075    static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2076        if (info.activityInfo != null) {
2077            return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2078        } else {
2079            return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2080        }
2081    }
2082    public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
2083        private PackageManager mPackageManager;
2084        private HashMap<Object, CharSequence> mLabelCache;
2085        ShortcutNameComparator(PackageManager pm) {
2086            mPackageManager = pm;
2087            mLabelCache = new HashMap<Object, CharSequence>();
2088        }
2089        ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2090            mPackageManager = pm;
2091            mLabelCache = labelCache;
2092        }
2093        public final int compare(ResolveInfo a, ResolveInfo b) {
2094            CharSequence labelA, labelB;
2095            ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2096            ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2097            if (mLabelCache.containsKey(keyA)) {
2098                labelA = mLabelCache.get(keyA);
2099            } else {
2100                labelA = a.loadLabel(mPackageManager).toString();
2101
2102                mLabelCache.put(keyA, labelA);
2103            }
2104            if (mLabelCache.containsKey(keyB)) {
2105                labelB = mLabelCache.get(keyB);
2106            } else {
2107                labelB = b.loadLabel(mPackageManager).toString();
2108
2109                mLabelCache.put(keyB, labelB);
2110            }
2111            return sCollator.compare(labelA, labelB);
2112        }
2113    };
2114    public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
2115        private PackageManager mPackageManager;
2116        private HashMap<Object, String> mLabelCache;
2117        WidgetAndShortcutNameComparator(PackageManager pm) {
2118            mPackageManager = pm;
2119            mLabelCache = new HashMap<Object, String>();
2120        }
2121        public final int compare(Object a, Object b) {
2122            String labelA, labelB;
2123            if (mLabelCache.containsKey(a)) {
2124                labelA = mLabelCache.get(a);
2125            } else {
2126                labelA = (a instanceof AppWidgetProviderInfo) ?
2127                    ((AppWidgetProviderInfo) a).label :
2128                    ((ResolveInfo) a).loadLabel(mPackageManager).toString();
2129                mLabelCache.put(a, labelA);
2130            }
2131            if (mLabelCache.containsKey(b)) {
2132                labelB = mLabelCache.get(b);
2133            } else {
2134                labelB = (b instanceof AppWidgetProviderInfo) ?
2135                    ((AppWidgetProviderInfo) b).label :
2136                    ((ResolveInfo) b).loadLabel(mPackageManager).toString();
2137                mLabelCache.put(b, labelB);
2138            }
2139            return sCollator.compare(labelA, labelB);
2140        }
2141    };
2142
2143    public void dumpState() {
2144        Log.d(TAG, "mCallbacks=" + mCallbacks);
2145        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
2146        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
2147        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
2148        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
2149        if (mLoaderTask != null) {
2150            mLoaderTask.dumpState();
2151        } else {
2152            Log.d(TAG, "mLoaderTask=null");
2153        }
2154    }
2155}
2156