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