LauncherModel.java revision 64359a53dc827797917a8d9a0697a91996789801
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.launcher3; 18 19import android.app.SearchManager; 20import android.appwidget.AppWidgetManager; 21import android.appwidget.AppWidgetProviderInfo; 22import android.content.*; 23import android.content.Intent.ShortcutIconResource; 24import android.content.pm.ActivityInfo; 25import android.content.pm.PackageInfo; 26import android.content.pm.PackageManager; 27import android.content.pm.PackageManager.NameNotFoundException; 28import android.content.pm.ResolveInfo; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.database.Cursor; 32import android.graphics.Bitmap; 33import android.graphics.BitmapFactory; 34import android.net.Uri; 35import android.os.Environment; 36import android.os.Handler; 37import android.os.HandlerThread; 38import android.os.Parcelable; 39import android.os.Process; 40import android.os.RemoteException; 41import android.os.SystemClock; 42import android.util.Log; 43import android.util.Pair; 44import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData; 45 46import java.lang.ref.WeakReference; 47import java.net.URISyntaxException; 48import java.text.Collator; 49import java.util.ArrayList; 50import java.util.Arrays; 51import java.util.Collection; 52import java.util.Collections; 53import java.util.Comparator; 54import java.util.HashMap; 55import java.util.HashSet; 56import java.util.Iterator; 57import java.util.List; 58import java.util.Set; 59import java.util.TreeMap; 60 61/** 62 * Maintains in-memory state of the Launcher. It is expected that there should be only one 63 * LauncherModel object held in a static. Also provide APIs for updating the database state 64 * for the Launcher. 65 */ 66public class LauncherModel extends BroadcastReceiver { 67 static final boolean DEBUG_LOADERS = false; 68 static final String TAG = "Launcher.Model"; 69 70 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons 71 private final boolean mAppsCanBeOnExternalStorage; 72 73 private final LauncherAppState mApp; 74 private final Object mLock = new Object(); 75 private DeferredHandler mHandler = new DeferredHandler(); 76 private LoaderTask mLoaderTask; 77 private boolean mIsLoaderTaskRunning; 78 private volatile boolean mFlushingWorkerThread; 79 80 // Specific runnable types that are run on the main thread deferred handler, this allows us to 81 // clear all queued binding runnables when the Launcher activity is destroyed. 82 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0; 83 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1; 84 85 86 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); 87 static { 88 sWorkerThread.start(); 89 } 90 private static final Handler sWorker = new Handler(sWorkerThread.getLooper()); 91 92 // We start off with everything not loaded. After that, we assume that 93 // our monitoring of the package manager provides all updates and we never 94 // need to do a requery. These are only ever touched from the loader thread. 95 private boolean mWorkspaceLoaded; 96 private boolean mAllAppsLoaded; 97 98 // When we are loading pages synchronously, we can't just post the binding of items on the side 99 // pages as this delays the rotation process. Instead, we wait for a callback from the first 100 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start 101 // a normal load, we also clear this set of Runnables. 102 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>(); 103 104 private WeakReference<Callbacks> mCallbacks; 105 106 // < only access in worker thread > 107 private AllAppsList mBgAllAppsList; 108 109 // The lock that must be acquired before referencing any static bg data structures. Unlike 110 // other locks, this one can generally be held long-term because we never expect any of these 111 // static data structures to be referenced outside of the worker thread except on the first 112 // load after configuration change. 113 static final Object sBgLock = new Object(); 114 115 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by 116 // LauncherModel to their ids 117 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>(); 118 119 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts 120 // created by LauncherModel that are directly on the home screen (however, no widgets or 121 // shortcuts within folders). 122 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>(); 123 124 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() 125 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets = 126 new ArrayList<LauncherAppWidgetInfo>(); 127 128 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() 129 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>(); 130 131 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database 132 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>(); 133 134 // sBgWorkspaceScreens is the ordered set of workspace screens. 135 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>(); 136 137 // </ only access in worker thread > 138 139 private IconCache mIconCache; 140 private Bitmap mDefaultIcon; 141 142 private static int mCellCountX; 143 private static int mCellCountY; 144 145 protected int mPreviousConfigMcc; 146 147 public interface Callbacks { 148 public boolean setLoadOnResume(); 149 public int getCurrentWorkspaceScreen(); 150 public void startBinding(); 151 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end, 152 boolean forceAnimateIcons); 153 public void bindScreens(ArrayList<Long> orderedScreenIds); 154 public void bindAddScreens(ArrayList<Long> orderedScreenIds); 155 public void bindFolders(HashMap<Long,FolderInfo> folders); 156 public void finishBindingItems(boolean upgradePath); 157 public void bindAppWidget(LauncherAppWidgetInfo info); 158 public void bindAllApplications(ArrayList<ApplicationInfo> apps); 159 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); 160 public void bindComponentsRemoved(ArrayList<String> packageNames, 161 ArrayList<ApplicationInfo> appInfos, 162 boolean matchPackageNamesOnly); 163 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts); 164 public void bindSearchablesChanged(); 165 public void onPageBoundSynchronously(int page); 166 } 167 168 public interface ItemInfoFilter { 169 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn); 170 } 171 172 LauncherModel(LauncherAppState app, IconCache iconCache) { 173 final Context context = app.getContext(); 174 175 mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated(); 176 mApp = app; 177 mBgAllAppsList = new AllAppsList(iconCache); 178 mIconCache = iconCache; 179 180 mDefaultIcon = Utilities.createIconBitmap( 181 mIconCache.getFullResDefaultActivityIcon(), context); 182 183 final Resources res = context.getResources(); 184 Configuration config = res.getConfiguration(); 185 mPreviousConfigMcc = config.mcc; 186 } 187 188 /** Runs the specified runnable immediately if called from the main thread, otherwise it is 189 * posted on the main thread handler. */ 190 private void runOnMainThread(Runnable r) { 191 runOnMainThread(r, 0); 192 } 193 private void runOnMainThread(Runnable r, int type) { 194 if (sWorkerThread.getThreadId() == Process.myTid()) { 195 // If we are on the worker thread, post onto the main handler 196 mHandler.post(r); 197 } else { 198 r.run(); 199 } 200 } 201 202 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is 203 * posted on the worker thread handler. */ 204 private static void runOnWorkerThread(Runnable r) { 205 if (sWorkerThread.getThreadId() == Process.myTid()) { 206 r.run(); 207 } else { 208 // If we are not on the worker thread, then post to the worker handler 209 sWorker.post(r); 210 } 211 } 212 213 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy, 214 long screen) { 215 final int xCount = LauncherModel.getCellCountX(); 216 final int yCount = LauncherModel.getCellCountY(); 217 boolean[][] occupied = new boolean[xCount][yCount]; 218 219 int cellX, cellY, spanX, spanY; 220 for (int i = 0; i < items.size(); ++i) { 221 final ItemInfo item = items.get(i); 222 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 223 if (item.screenId == screen) { 224 cellX = item.cellX; 225 cellY = item.cellY; 226 spanX = item.spanX; 227 spanY = item.spanY; 228 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) { 229 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) { 230 occupied[x][y] = true; 231 } 232 } 233 } 234 } 235 } 236 237 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied); 238 } 239 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name, 240 Intent launchIntent) { 241 // Lock on the app so that we don't try and get the items while apps are being added 242 LauncherAppState app = LauncherAppState.getInstance(); 243 LauncherModel model = app.getModel(); 244 boolean found = false; 245 synchronized (app) { 246 if (sWorkerThread.getThreadId() != Process.myTid()) { 247 // Flush the LauncherModel worker thread, so that if we just did another 248 // processInstallShortcut, we give it time for its shortcut to get added to the 249 // database (getItemsInLocalCoordinates reads the database) 250 model.flushWorkerThread(); 251 } 252 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context); 253 254 // Try adding to the workspace screens incrementally, starting at the default or center 255 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1)) 256 for (int screen = 0; screen < sBgWorkspaceScreens.size() && !found; screen++) { 257 int[] tmpCoordinates = new int[2]; 258 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates, 259 sBgWorkspaceScreens.get(screen))) { 260 // Update the Launcher db 261 return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates); 262 } 263 } 264 } 265 // XXX: Create a new page and add it to the first spot 266 return null; 267 } 268 269 public void addAndBindAddedApps(final Context context, final ArrayList<ApplicationInfo> added, 270 final Callbacks callbacks) { 271 // Process the newly added applications and add them to the database first 272 Runnable r = new Runnable() { 273 public void run() { 274 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>(); 275 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>(); 276 277 synchronized(sBgLock) { 278 Iterator<ApplicationInfo> iter = added.iterator(); 279 while (iter.hasNext()) { 280 ApplicationInfo a = iter.next(); 281 final String name = a.title.toString(); 282 final Intent launchIntent = a.intent; 283 284 // Short-circuit this logic if the icon exists somewhere on the workspace 285 if (LauncherModel.shortcutExists(context, name, launchIntent)) { 286 continue; 287 } 288 289 // Add this icon to the db, creating a new page if necessary 290 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context, 291 name, launchIntent); 292 if (coords == null) { 293 // If we can't find a valid position, then just add a new screen. 294 // This takes time so we need to re-queue the add until the new 295 // page is added. 296 LauncherAppState appState = LauncherAppState.getInstance(); 297 LauncherProvider lp = appState.getLauncherProvider(); 298 long screenId = lp.generateNewScreenId(); 299 // Update the model 300 sBgWorkspaceScreens.add(screenId); 301 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); 302 // Save the screen id for binding in the workspace 303 addedWorkspaceScreensFinal.add(screenId); 304 // Find the coordinate again 305 coords = LauncherModel.findNextAvailableIconSpace(context, 306 a.title.toString(), a.intent); 307 } 308 if (coords == null) { 309 throw new RuntimeException("Coordinates should not be null"); 310 } 311 312 final ShortcutInfo shortcutInfo = a.makeShortcut(); 313 // Add the shortcut to the db 314 addItemToDatabase(context, shortcutInfo, 315 LauncherSettings.Favorites.CONTAINER_DESKTOP, 316 coords.first, coords.second[0], coords.second[1], false); 317 // Save the ShortcutInfo for binding in the workspace 318 addedShortcutsFinal.add(shortcutInfo); 319 } 320 } 321 322 runOnMainThread(new Runnable() { 323 public void run() { 324 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; 325 if (callbacks == cb && cb != null) { 326 callbacks.bindAddScreens(addedWorkspaceScreensFinal); 327 callbacks.bindItems(addedShortcutsFinal, 0, 328 addedShortcutsFinal.size(), true); 329 } 330 } 331 }); 332 } 333 }; 334 runOnWorkerThread(r); 335 } 336 337 public Bitmap getFallbackIcon() { 338 return Bitmap.createBitmap(mDefaultIcon); 339 } 340 341 public void unbindItemInfosAndClearQueuedBindRunnables() { 342 if (sWorkerThread.getThreadId() == Process.myTid()) { 343 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " + 344 "main thread"); 345 } 346 347 // Clear any deferred bind runnables 348 mDeferredBindRunnables.clear(); 349 // Remove any queued bind runnables 350 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE); 351 // Unbind all the workspace items 352 unbindWorkspaceItemsOnMainThread(); 353 } 354 355 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */ 356 void unbindWorkspaceItemsOnMainThread() { 357 // Ensure that we don't use the same workspace items data structure on the main thread 358 // by making a copy of workspace items first. 359 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>(); 360 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>(); 361 synchronized (sBgLock) { 362 tmpWorkspaceItems.addAll(sBgWorkspaceItems); 363 tmpAppWidgets.addAll(sBgAppWidgets); 364 } 365 Runnable r = new Runnable() { 366 @Override 367 public void run() { 368 for (ItemInfo item : tmpWorkspaceItems) { 369 item.unbind(); 370 } 371 for (ItemInfo item : tmpAppWidgets) { 372 item.unbind(); 373 } 374 } 375 }; 376 runOnMainThread(r); 377 } 378 379 /** 380 * Adds an item to the DB if it was not created previously, or move it to a new 381 * <container, screen, cellX, cellY> 382 */ 383 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, 384 long screenId, int cellX, int cellY) { 385 if (item.container == ItemInfo.NO_ID) { 386 // From all apps 387 addItemToDatabase(context, item, container, screenId, cellX, cellY, false); 388 } else { 389 // From somewhere else 390 moveItemInDatabase(context, item, container, screenId, cellX, cellY); 391 } 392 } 393 394 static void checkItemInfoLocked( 395 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) { 396 ItemInfo modelItem = sBgItemsIdMap.get(itemId); 397 if (modelItem != null && item != modelItem) { 398 // check all the data is consistent 399 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) { 400 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem; 401 ShortcutInfo shortcut = (ShortcutInfo) item; 402 if (modelShortcut.title.toString().equals(shortcut.title.toString()) && 403 modelShortcut.intent.filterEquals(shortcut.intent) && 404 modelShortcut.id == shortcut.id && 405 modelShortcut.itemType == shortcut.itemType && 406 modelShortcut.container == shortcut.container && 407 modelShortcut.screenId == shortcut.screenId && 408 modelShortcut.cellX == shortcut.cellX && 409 modelShortcut.cellY == shortcut.cellY && 410 modelShortcut.spanX == shortcut.spanX && 411 modelShortcut.spanY == shortcut.spanY && 412 ((modelShortcut.dropPos == null && shortcut.dropPos == null) || 413 (modelShortcut.dropPos != null && 414 shortcut.dropPos != null && 415 modelShortcut.dropPos[0] == shortcut.dropPos[0] && 416 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) { 417 // For all intents and purposes, this is the same object 418 return; 419 } 420 } 421 422 // the modelItem needs to match up perfectly with item if our model is 423 // to be consistent with the database-- for now, just require 424 // modelItem == item or the equality check above 425 String msg = "item: " + ((item != null) ? item.toString() : "null") + 426 "modelItem: " + 427 ((modelItem != null) ? modelItem.toString() : "null") + 428 "Error: ItemInfo passed to checkItemInfo doesn't match original"; 429 RuntimeException e = new RuntimeException(msg); 430 if (stackTrace != null) { 431 e.setStackTrace(stackTrace); 432 } 433 // TODO: something breaks this in the upgrade path 434 //throw e; 435 } 436 } 437 438 static void checkItemInfo(final ItemInfo item) { 439 final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 440 final long itemId = item.id; 441 Runnable r = new Runnable() { 442 public void run() { 443 synchronized (sBgLock) { 444 checkItemInfoLocked(itemId, item, stackTrace); 445 } 446 } 447 }; 448 runOnWorkerThread(r); 449 } 450 451 static void updateItemInDatabaseHelper(Context context, final ContentValues values, 452 final ItemInfo item, final String callingFunction) { 453 final long itemId = item.id; 454 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); 455 final ContentResolver cr = context.getContentResolver(); 456 457 final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 458 Runnable r = new Runnable() { 459 public void run() { 460 cr.update(uri, values, null, null); 461 updateItemArrays(item, itemId, stackTrace); 462 } 463 }; 464 runOnWorkerThread(r); 465 } 466 467 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList, 468 final ArrayList<ItemInfo> items, final String callingFunction) { 469 final ContentResolver cr = context.getContentResolver(); 470 471 final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 472 Runnable r = new Runnable() { 473 public void run() { 474 ArrayList<ContentProviderOperation> ops = 475 new ArrayList<ContentProviderOperation>(); 476 int count = items.size(); 477 for (int i = 0; i < count; i++) { 478 ItemInfo item = items.get(i); 479 final long itemId = item.id; 480 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); 481 ContentValues values = valuesList.get(i); 482 483 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); 484 updateItemArrays(item, itemId, stackTrace); 485 486 } 487 try { 488 cr.applyBatch(LauncherProvider.AUTHORITY, ops); 489 } catch (Exception e) { 490 e.printStackTrace(); 491 } 492 } 493 }; 494 runOnWorkerThread(r); 495 } 496 497 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) { 498 // Lock on mBgLock *after* the db operation 499 synchronized (sBgLock) { 500 checkItemInfoLocked(itemId, item, stackTrace); 501 502 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP && 503 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 504 // Item is in a folder, make sure this folder exists 505 if (!sBgFolders.containsKey(item.container)) { 506 // An items container is being set to a that of an item which is not in 507 // the list of Folders. 508 String msg = "item: " + item + " container being set to: " + 509 item.container + ", not in the list of folders"; 510 Log.e(TAG, msg); 511 Launcher.dumpDebugLogsToConsole(); 512 } 513 } 514 515 // Items are added/removed from the corresponding FolderInfo elsewhere, such 516 // as in Workspace.onDrop. Here, we just add/remove them from the list of items 517 // that are on the desktop, as appropriate 518 ItemInfo modelItem = sBgItemsIdMap.get(itemId); 519 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || 520 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 521 switch (modelItem.itemType) { 522 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 523 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 524 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 525 if (!sBgWorkspaceItems.contains(modelItem)) { 526 sBgWorkspaceItems.add(modelItem); 527 } 528 break; 529 default: 530 break; 531 } 532 } else { 533 sBgWorkspaceItems.remove(modelItem); 534 } 535 } 536 } 537 538 public void flushWorkerThread() { 539 mFlushingWorkerThread = true; 540 Runnable waiter = new Runnable() { 541 public void run() { 542 synchronized (this) { 543 notifyAll(); 544 mFlushingWorkerThread = false; 545 } 546 } 547 }; 548 549 synchronized(waiter) { 550 runOnWorkerThread(waiter); 551 if (mLoaderTask != null) { 552 synchronized(mLoaderTask) { 553 mLoaderTask.notify(); 554 } 555 } 556 boolean success = false; 557 while (!success) { 558 try { 559 waiter.wait(); 560 success = true; 561 } catch (InterruptedException e) { 562 } 563 } 564 } 565 } 566 567 /** 568 * Move an item in the DB to a new <container, screen, cellX, cellY> 569 */ 570 static void moveItemInDatabase(Context context, final ItemInfo item, final long container, 571 final long screenId, final int cellX, final int cellY) { 572 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + 573 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + 574 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; 575 Launcher.sDumpLogs.add(transaction); 576 Log.d(TAG, transaction); 577 item.container = container; 578 item.cellX = cellX; 579 item.cellY = cellY; 580 581 // We store hotseat items in canonical form which is this orientation invariant position 582 // in the hotseat 583 if (context instanceof Launcher && screenId < 0 && 584 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 585 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); 586 } else { 587 item.screenId = screenId; 588 } 589 590 final ContentValues values = new ContentValues(); 591 values.put(LauncherSettings.Favorites.CONTAINER, item.container); 592 values.put(LauncherSettings.Favorites.CELLX, item.cellX); 593 values.put(LauncherSettings.Favorites.CELLY, item.cellY); 594 values.put(LauncherSettings.Favorites.SCREEN, item.screenId); 595 596 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase"); 597 } 598 599 /** 600 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the 601 * cellX, cellY have already been updated on the ItemInfos. 602 */ 603 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items, 604 final long container, final int screen) { 605 606 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>(); 607 int count = items.size(); 608 609 for (int i = 0; i < count; i++) { 610 ItemInfo item = items.get(i); 611 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " 612 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX 613 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", " 614 + item.cellX + ", " + item.cellY + ")"; 615 Launcher.sDumpLogs.add(transaction); 616 item.container = container; 617 618 // We store hotseat items in canonical form which is this orientation invariant position 619 // in the hotseat 620 if (context instanceof Launcher && screen < 0 && 621 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 622 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX, 623 item.cellY); 624 } else { 625 item.screenId = screen; 626 } 627 628 final ContentValues values = new ContentValues(); 629 values.put(LauncherSettings.Favorites.CONTAINER, item.container); 630 values.put(LauncherSettings.Favorites.CELLX, item.cellX); 631 values.put(LauncherSettings.Favorites.CELLY, item.cellY); 632 values.put(LauncherSettings.Favorites.SCREEN, item.screenId); 633 634 contentValues.add(values); 635 } 636 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase"); 637 } 638 639 /** 640 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY> 641 */ 642 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container, 643 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) { 644 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + 645 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + 646 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; 647 Launcher.sDumpLogs.add(transaction); 648 Log.d(TAG, transaction); 649 item.cellX = cellX; 650 item.cellY = cellY; 651 item.spanX = spanX; 652 item.spanY = spanY; 653 654 // We store hotseat items in canonical form which is this orientation invariant position 655 // in the hotseat 656 if (context instanceof Launcher && screenId < 0 && 657 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 658 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); 659 } else { 660 item.screenId = screenId; 661 } 662 663 final ContentValues values = new ContentValues(); 664 values.put(LauncherSettings.Favorites.CONTAINER, item.container); 665 values.put(LauncherSettings.Favorites.CELLX, item.cellX); 666 values.put(LauncherSettings.Favorites.CELLY, item.cellY); 667 values.put(LauncherSettings.Favorites.SPANX, item.spanX); 668 values.put(LauncherSettings.Favorites.SPANY, item.spanY); 669 values.put(LauncherSettings.Favorites.SCREEN, item.screenId); 670 671 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase"); 672 } 673 674 /** 675 * Update an item to the database in a specified container. 676 */ 677 static void updateItemInDatabase(Context context, final ItemInfo item) { 678 final ContentValues values = new ContentValues(); 679 item.onAddToDatabase(values); 680 item.updateValuesWithCoordinates(values, item.cellX, item.cellY); 681 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase"); 682 } 683 684 /** 685 * Returns true if the shortcuts already exists in the database. 686 * we identify a shortcut by its title and intent. 687 */ 688 static boolean shortcutExists(Context context, String title, Intent intent) { 689 final ContentResolver cr = context.getContentResolver(); 690 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, 691 new String[] { "title", "intent" }, "title=? and intent=?", 692 new String[] { title, intent.toUri(0) }, null); 693 boolean result = false; 694 try { 695 result = c.moveToFirst(); 696 } finally { 697 c.close(); 698 } 699 return result; 700 } 701 702 /** 703 * Returns an ItemInfo array containing all the items in the LauncherModel. 704 * The ItemInfo.id is not set through this function. 705 */ 706 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { 707 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); 708 final ContentResolver cr = context.getContentResolver(); 709 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { 710 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, 711 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, 712 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); 713 714 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); 715 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); 716 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); 717 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); 718 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); 719 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); 720 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); 721 722 try { 723 while (c.moveToNext()) { 724 ItemInfo item = new ItemInfo(); 725 item.cellX = c.getInt(cellXIndex); 726 item.cellY = c.getInt(cellYIndex); 727 item.spanX = c.getInt(spanXIndex); 728 item.spanY = c.getInt(spanYIndex); 729 item.container = c.getInt(containerIndex); 730 item.itemType = c.getInt(itemTypeIndex); 731 item.screenId = c.getInt(screenIndex); 732 733 items.add(item); 734 } 735 } catch (Exception e) { 736 items.clear(); 737 } finally { 738 c.close(); 739 } 740 741 return items; 742 } 743 744 /** 745 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. 746 */ 747 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { 748 final ContentResolver cr = context.getContentResolver(); 749 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, 750 "_id=? and (itemType=? or itemType=?)", 751 new String[] { String.valueOf(id), 752 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); 753 754 try { 755 if (c.moveToFirst()) { 756 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); 757 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); 758 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); 759 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); 760 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); 761 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); 762 763 FolderInfo folderInfo = null; 764 switch (c.getInt(itemTypeIndex)) { 765 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 766 folderInfo = findOrMakeFolder(folderList, id); 767 break; 768 } 769 770 folderInfo.title = c.getString(titleIndex); 771 folderInfo.id = id; 772 folderInfo.container = c.getInt(containerIndex); 773 folderInfo.screenId = c.getInt(screenIndex); 774 folderInfo.cellX = c.getInt(cellXIndex); 775 folderInfo.cellY = c.getInt(cellYIndex); 776 777 return folderInfo; 778 } 779 } finally { 780 c.close(); 781 } 782 783 return null; 784 } 785 786 /** 787 * Add an item to the database in a specified container. Sets the container, screen, cellX and 788 * cellY fields of the item. Also assigns an ID to the item. 789 */ 790 static void addItemToDatabase(Context context, final ItemInfo item, final long container, 791 final long screenId, final int cellX, final int cellY, final boolean notify) { 792 item.container = container; 793 item.cellX = cellX; 794 item.cellY = cellY; 795 // We store hotseat items in canonical form which is this orientation invariant position 796 // in the hotseat 797 if (context instanceof Launcher && screenId < 0 && 798 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 799 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); 800 } else { 801 item.screenId = screenId; 802 } 803 804 final ContentValues values = new ContentValues(); 805 final ContentResolver cr = context.getContentResolver(); 806 item.onAddToDatabase(values); 807 808 LauncherAppState app = LauncherAppState.getInstance(); 809 item.id = app.getLauncherProvider().generateNewItemId(); 810 values.put(LauncherSettings.Favorites._ID, item.id); 811 item.updateValuesWithCoordinates(values, item.cellX, item.cellY); 812 813 Runnable r = new Runnable() { 814 public void run() { 815 String transaction = "DbDebug Add item (" + item.title + ") to db, id: " 816 + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " 817 + cellY + ")"; 818 Launcher.sDumpLogs.add(transaction); 819 Log.d(TAG, transaction); 820 821 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : 822 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); 823 824 // Lock on mBgLock *after* the db operation 825 synchronized (sBgLock) { 826 checkItemInfoLocked(item.id, item, null); 827 sBgItemsIdMap.put(item.id, item); 828 switch (item.itemType) { 829 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 830 sBgFolders.put(item.id, (FolderInfo) item); 831 // Fall through 832 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 833 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 834 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || 835 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 836 sBgWorkspaceItems.add(item); 837 } else { 838 if (!sBgFolders.containsKey(item.container)) { 839 // Adding an item to a folder that doesn't exist. 840 String msg = "adding item: " + item + " to a folder that " + 841 " doesn't exist"; 842 Log.e(TAG, msg); 843 Launcher.dumpDebugLogsToConsole(); 844 } 845 } 846 break; 847 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 848 sBgAppWidgets.add((LauncherAppWidgetInfo) item); 849 break; 850 } 851 } 852 } 853 }; 854 runOnWorkerThread(r); 855 } 856 857 /** 858 * Creates a new unique child id, for a given cell span across all layouts. 859 */ 860 static int getCellLayoutChildId( 861 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { 862 return (((int) container & 0xFF) << 24) 863 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); 864 } 865 866 static int getCellCountX() { 867 return mCellCountX; 868 } 869 870 static int getCellCountY() { 871 return mCellCountY; 872 } 873 874 /** 875 * Updates the model orientation helper to take into account the current layout dimensions 876 * when performing local/canonical coordinate transformations. 877 */ 878 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { 879 mCellCountX = shortAxisCellCount; 880 mCellCountY = longAxisCellCount; 881 } 882 883 /** 884 * Removes the specified item from the database 885 * @param context 886 * @param item 887 */ 888 static void deleteItemFromDatabase(Context context, final ItemInfo item) { 889 final ContentResolver cr = context.getContentResolver(); 890 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); 891 892 Runnable r = new Runnable() { 893 public void run() { 894 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " 895 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + 896 ", " + item.cellY + ")"; 897 Launcher.sDumpLogs.add(transaction); 898 Log.d(TAG, transaction); 899 900 cr.delete(uriToDelete, null, null); 901 902 // Lock on mBgLock *after* the db operation 903 synchronized (sBgLock) { 904 switch (item.itemType) { 905 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 906 sBgFolders.remove(item.id); 907 for (ItemInfo info: sBgItemsIdMap.values()) { 908 if (info.container == item.id) { 909 // We are deleting a folder which still contains items that 910 // think they are contained by that folder. 911 String msg = "deleting a folder (" + item + ") which still " + 912 "contains items (" + info + ")"; 913 Log.e(TAG, msg); 914 Launcher.dumpDebugLogsToConsole(); 915 } 916 } 917 sBgWorkspaceItems.remove(item); 918 break; 919 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 920 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 921 sBgWorkspaceItems.remove(item); 922 break; 923 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 924 sBgAppWidgets.remove((LauncherAppWidgetInfo) item); 925 break; 926 } 927 sBgItemsIdMap.remove(item.id); 928 sBgDbIconCache.remove(item); 929 } 930 } 931 }; 932 runOnWorkerThread(r); 933 } 934 935 /** 936 * Update the order of the workspace screens in the database. The array list contains 937 * a list of screen ids in the order that they should appear. 938 */ 939 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { 940 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); 941 final ContentResolver cr = context.getContentResolver(); 942 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; 943 944 // Remove any negative screen ids -- these aren't persisted 945 Iterator<Long> iter = screensCopy.iterator(); 946 while (iter.hasNext()) { 947 long id = iter.next(); 948 if (id < 0) { 949 iter.remove(); 950 } 951 } 952 953 Runnable r = new Runnable() { 954 @Override 955 public void run() { 956 // Clear the table 957 cr.delete(uri, null, null); 958 int count = screens.size(); 959 ContentValues[] values = new ContentValues[count]; 960 for (int i = 0; i < count; i++) { 961 ContentValues v = new ContentValues(); 962 long screenId = screens.get(i); 963 v.put(LauncherSettings.WorkspaceScreens._ID, screenId); 964 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); 965 values[i] = v; 966 } 967 cr.bulkInsert(uri, values); 968 sBgWorkspaceScreens.clear(); 969 sBgWorkspaceScreens.addAll(screensCopy); 970 } 971 }; 972 runOnWorkerThread(r); 973 } 974 975 /** 976 * Remove the contents of the specified folder from the database 977 */ 978 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { 979 final ContentResolver cr = context.getContentResolver(); 980 981 Runnable r = new Runnable() { 982 public void run() { 983 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); 984 // Lock on mBgLock *after* the db operation 985 synchronized (sBgLock) { 986 sBgItemsIdMap.remove(info.id); 987 sBgFolders.remove(info.id); 988 sBgDbIconCache.remove(info); 989 sBgWorkspaceItems.remove(info); 990 } 991 992 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, 993 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); 994 // Lock on mBgLock *after* the db operation 995 synchronized (sBgLock) { 996 for (ItemInfo childInfo : info.contents) { 997 sBgItemsIdMap.remove(childInfo.id); 998 sBgDbIconCache.remove(childInfo); 999 } 1000 } 1001 } 1002 }; 1003 runOnWorkerThread(r); 1004 } 1005 1006 /** 1007 * Set this as the current Launcher activity object for the loader. 1008 */ 1009 public void initialize(Callbacks callbacks) { 1010 synchronized (mLock) { 1011 mCallbacks = new WeakReference<Callbacks>(callbacks); 1012 } 1013 } 1014 1015 /** 1016 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and 1017 * ACTION_PACKAGE_CHANGED. 1018 */ 1019 @Override 1020 public void onReceive(Context context, Intent intent) { 1021 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); 1022 1023 final String action = intent.getAction(); 1024 1025 if (Intent.ACTION_PACKAGE_CHANGED.equals(action) 1026 || Intent.ACTION_PACKAGE_REMOVED.equals(action) 1027 || Intent.ACTION_PACKAGE_ADDED.equals(action)) { 1028 final String packageName = intent.getData().getSchemeSpecificPart(); 1029 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 1030 1031 int op = PackageUpdatedTask.OP_NONE; 1032 1033 if (packageName == null || packageName.length() == 0) { 1034 // they sent us a bad intent 1035 return; 1036 } 1037 1038 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { 1039 op = PackageUpdatedTask.OP_UPDATE; 1040 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { 1041 if (!replacing) { 1042 op = PackageUpdatedTask.OP_REMOVE; 1043 } 1044 // else, we are replacing the package, so a PACKAGE_ADDED will be sent 1045 // later, we will update the package at this time 1046 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { 1047 if (!replacing) { 1048 op = PackageUpdatedTask.OP_ADD; 1049 } else { 1050 op = PackageUpdatedTask.OP_UPDATE; 1051 } 1052 } 1053 1054 if (op != PackageUpdatedTask.OP_NONE) { 1055 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); 1056 } 1057 1058 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { 1059 // First, schedule to add these apps back in. 1060 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 1061 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); 1062 // Then, rebind everything. 1063 startLoaderFromBackground(); 1064 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 1065 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 1066 enqueuePackageUpdated(new PackageUpdatedTask( 1067 PackageUpdatedTask.OP_UNAVAILABLE, packages)); 1068 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { 1069 // If we have changed locale we need to clear out the labels in all apps/workspace. 1070 forceReload(); 1071 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { 1072 // Check if configuration change was an mcc/mnc change which would affect app resources 1073 // and we would need to clear out the labels in all apps/workspace. Same handling as 1074 // above for ACTION_LOCALE_CHANGED 1075 Configuration currentConfig = context.getResources().getConfiguration(); 1076 if (mPreviousConfigMcc != currentConfig.mcc) { 1077 Log.d(TAG, "Reload apps on config change. curr_mcc:" 1078 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); 1079 forceReload(); 1080 } 1081 // Update previousConfig 1082 mPreviousConfigMcc = currentConfig.mcc; 1083 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || 1084 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { 1085 if (mCallbacks != null) { 1086 Callbacks callbacks = mCallbacks.get(); 1087 if (callbacks != null) { 1088 callbacks.bindSearchablesChanged(); 1089 } 1090 } 1091 } 1092 } 1093 1094 private void forceReload() { 1095 resetLoadedState(true, true); 1096 1097 // Do this here because if the launcher activity is running it will be restarted. 1098 // If it's not running startLoaderFromBackground will merely tell it that it needs 1099 // to reload. 1100 startLoaderFromBackground(); 1101 } 1102 1103 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { 1104 synchronized (mLock) { 1105 // Stop any existing loaders first, so they don't set mAllAppsLoaded or 1106 // mWorkspaceLoaded to true later 1107 stopLoaderLocked(); 1108 if (resetAllAppsLoaded) mAllAppsLoaded = false; 1109 if (resetWorkspaceLoaded) mWorkspaceLoaded = false; 1110 } 1111 } 1112 1113 /** 1114 * When the launcher is in the background, it's possible for it to miss paired 1115 * configuration changes. So whenever we trigger the loader from the background 1116 * tell the launcher that it needs to re-run the loader when it comes back instead 1117 * of doing it now. 1118 */ 1119 public void startLoaderFromBackground() { 1120 boolean runLoader = false; 1121 if (mCallbacks != null) { 1122 Callbacks callbacks = mCallbacks.get(); 1123 if (callbacks != null) { 1124 // Only actually run the loader if they're not paused. 1125 if (!callbacks.setLoadOnResume()) { 1126 runLoader = true; 1127 } 1128 } 1129 } 1130 if (runLoader) { 1131 startLoader(false, -1); 1132 } 1133 } 1134 1135 // If there is already a loader task running, tell it to stop. 1136 // returns true if isLaunching() was true on the old task 1137 private boolean stopLoaderLocked() { 1138 boolean isLaunching = false; 1139 LoaderTask oldTask = mLoaderTask; 1140 if (oldTask != null) { 1141 if (oldTask.isLaunching()) { 1142 isLaunching = true; 1143 } 1144 oldTask.stopLocked(); 1145 } 1146 return isLaunching; 1147 } 1148 1149 public void startLoader(boolean isLaunching, int synchronousBindPage) { 1150 synchronized (mLock) { 1151 if (DEBUG_LOADERS) { 1152 Log.d(TAG, "startLoader isLaunching=" + isLaunching); 1153 } 1154 1155 // Clear any deferred bind-runnables from the synchronized load process 1156 // We must do this before any loading/binding is scheduled below. 1157 mDeferredBindRunnables.clear(); 1158 1159 // Don't bother to start the thread if we know it's not going to do anything 1160 if (mCallbacks != null && mCallbacks.get() != null) { 1161 // If there is already one running, tell it to stop. 1162 // also, don't downgrade isLaunching if we're already running 1163 isLaunching = isLaunching || stopLoaderLocked(); 1164 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); 1165 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { 1166 mLoaderTask.runBindSynchronousPage(synchronousBindPage); 1167 } else { 1168 sWorkerThread.setPriority(Thread.NORM_PRIORITY); 1169 sWorker.post(mLoaderTask); 1170 } 1171 } 1172 } 1173 } 1174 1175 void bindRemainingSynchronousPages() { 1176 // Post the remaining side pages to be loaded 1177 if (!mDeferredBindRunnables.isEmpty()) { 1178 for (final Runnable r : mDeferredBindRunnables) { 1179 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); 1180 } 1181 mDeferredBindRunnables.clear(); 1182 } 1183 } 1184 1185 public void stopLoader() { 1186 synchronized (mLock) { 1187 if (mLoaderTask != null) { 1188 mLoaderTask.stopLocked(); 1189 } 1190 } 1191 } 1192 1193 public boolean isAllAppsLoaded() { 1194 return mAllAppsLoaded; 1195 } 1196 1197 boolean isLoadingWorkspace() { 1198 synchronized (mLock) { 1199 if (mLoaderTask != null) { 1200 return mLoaderTask.isLoadingWorkspace(); 1201 } 1202 } 1203 return false; 1204 } 1205 1206 /** 1207 * Runnable for the thread that loads the contents of the launcher: 1208 * - workspace icons 1209 * - widgets 1210 * - all apps icons 1211 */ 1212 private class LoaderTask implements Runnable { 1213 private Context mContext; 1214 private boolean mIsLaunching; 1215 private boolean mIsLoadingAndBindingWorkspace; 1216 private boolean mStopped; 1217 private boolean mLoadAndBindStepFinished; 1218 private boolean mIsUpgradePath; 1219 1220 private HashMap<Object, CharSequence> mLabelCache; 1221 1222 LoaderTask(Context context, boolean isLaunching) { 1223 mContext = context; 1224 mIsLaunching = isLaunching; 1225 mLabelCache = new HashMap<Object, CharSequence>(); 1226 } 1227 1228 boolean isLaunching() { 1229 return mIsLaunching; 1230 } 1231 1232 boolean isLoadingWorkspace() { 1233 return mIsLoadingAndBindingWorkspace; 1234 } 1235 1236 private void loadAndBindWorkspace() { 1237 mIsLoadingAndBindingWorkspace = true; 1238 1239 // Load the workspace 1240 if (DEBUG_LOADERS) { 1241 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); 1242 } 1243 1244 if (!mWorkspaceLoaded) { 1245 loadWorkspace(); 1246 synchronized (LoaderTask.this) { 1247 if (mStopped) { 1248 return; 1249 } 1250 mWorkspaceLoaded = true; 1251 } 1252 } 1253 1254 // Bind the workspace 1255 bindWorkspace(-1); 1256 } 1257 1258 private void waitForIdle() { 1259 // Wait until the either we're stopped or the other threads are done. 1260 // This way we don't start loading all apps until the workspace has settled 1261 // down. 1262 synchronized (LoaderTask.this) { 1263 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 1264 1265 mHandler.postIdle(new Runnable() { 1266 public void run() { 1267 synchronized (LoaderTask.this) { 1268 mLoadAndBindStepFinished = true; 1269 if (DEBUG_LOADERS) { 1270 Log.d(TAG, "done with previous binding step"); 1271 } 1272 LoaderTask.this.notify(); 1273 } 1274 } 1275 }); 1276 1277 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { 1278 try { 1279 // Just in case mFlushingWorkerThread changes but we aren't woken up, 1280 // wait no longer than 1sec at a time 1281 this.wait(1000); 1282 } catch (InterruptedException ex) { 1283 // Ignore 1284 } 1285 } 1286 if (DEBUG_LOADERS) { 1287 Log.d(TAG, "waited " 1288 + (SystemClock.uptimeMillis()-workspaceWaitTime) 1289 + "ms for previous step to finish binding"); 1290 } 1291 } 1292 } 1293 1294 void runBindSynchronousPage(int synchronousBindPage) { 1295 if (synchronousBindPage < 0) { 1296 // Ensure that we have a valid page index to load synchronously 1297 throw new RuntimeException("Should not call runBindSynchronousPage() without " + 1298 "valid page index"); 1299 } 1300 if (!mAllAppsLoaded || !mWorkspaceLoaded) { 1301 // Ensure that we don't try and bind a specified page when the pages have not been 1302 // loaded already (we should load everything asynchronously in that case) 1303 throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); 1304 } 1305 synchronized (mLock) { 1306 if (mIsLoaderTaskRunning) { 1307 // Ensure that we are never running the background loading at this point since 1308 // we also touch the background collections 1309 throw new RuntimeException("Error! Background loading is already running"); 1310 } 1311 } 1312 1313 // XXX: Throw an exception if we are already loading (since we touch the worker thread 1314 // data structures, we can't allow any other thread to touch that data, but because 1315 // this call is synchronous, we can get away with not locking). 1316 1317 // The LauncherModel is static in the LauncherAppState and mHandler may have queued 1318 // operations from the previous activity. We need to ensure that all queued operations 1319 // are executed before any synchronous binding work is done. 1320 mHandler.flush(); 1321 1322 // Divide the set of loaded items into those that we are binding synchronously, and 1323 // everything else that is to be bound normally (asynchronously). 1324 bindWorkspace(synchronousBindPage); 1325 // XXX: For now, continue posting the binding of AllApps as there are other issues that 1326 // arise from that. 1327 onlyBindAllApps(); 1328 } 1329 1330 public void run() { 1331 synchronized (mLock) { 1332 mIsLoaderTaskRunning = true; 1333 } 1334 // Optimize for end-user experience: if the Launcher is up and // running with the 1335 // All Apps interface in the foreground, load All Apps first. Otherwise, load the 1336 // workspace first (default). 1337 final Callbacks cbk = mCallbacks.get(); 1338 keep_running: { 1339 // Elevate priority when Home launches for the first time to avoid 1340 // starving at boot time. Staring at a blank home is not cool. 1341 synchronized (mLock) { 1342 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + 1343 (mIsLaunching ? "DEFAULT" : "BACKGROUND")); 1344 android.os.Process.setThreadPriority(mIsLaunching 1345 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); 1348 loadAndBindWorkspace(); 1349 1350 if (mStopped) { 1351 break keep_running; 1352 } 1353 1354 // Whew! Hard work done. Slow us down, and wait until the UI thread has 1355 // settled down. 1356 synchronized (mLock) { 1357 if (mIsLaunching) { 1358 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); 1359 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1360 } 1361 } 1362 waitForIdle(); 1363 1364 // second step 1365 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); 1366 loadAndBindAllApps(); 1367 1368 // Restore the default thread priority after we are done loading items 1369 synchronized (mLock) { 1370 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1371 } 1372 } 1373 1374 // Update the saved icons if necessary 1375 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); 1376 synchronized (sBgLock) { 1377 for (Object key : sBgDbIconCache.keySet()) { 1378 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); 1379 } 1380 sBgDbIconCache.clear(); 1381 } 1382 1383 // Clear out this reference, otherwise we end up holding it until all of the 1384 // callback runnables are done. 1385 mContext = null; 1386 1387 synchronized (mLock) { 1388 // If we are still the last one to be scheduled, remove ourselves. 1389 if (mLoaderTask == this) { 1390 mLoaderTask = null; 1391 } 1392 mIsLoaderTaskRunning = false; 1393 } 1394 } 1395 1396 public void stopLocked() { 1397 synchronized (LoaderTask.this) { 1398 mStopped = true; 1399 this.notify(); 1400 } 1401 } 1402 1403 /** 1404 * Gets the callbacks object. If we've been stopped, or if the launcher object 1405 * has somehow been garbage collected, return null instead. Pass in the Callbacks 1406 * object that was around when the deferred message was scheduled, and if there's 1407 * a new Callbacks object around then also return null. This will save us from 1408 * calling onto it with data that will be ignored. 1409 */ 1410 Callbacks tryGetCallbacks(Callbacks oldCallbacks) { 1411 synchronized (mLock) { 1412 if (mStopped) { 1413 return null; 1414 } 1415 1416 if (mCallbacks == null) { 1417 return null; 1418 } 1419 1420 final Callbacks callbacks = mCallbacks.get(); 1421 if (callbacks != oldCallbacks) { 1422 return null; 1423 } 1424 if (callbacks == null) { 1425 Log.w(TAG, "no mCallbacks"); 1426 return null; 1427 } 1428 1429 return callbacks; 1430 } 1431 } 1432 1433 // check & update map of what's occupied; used to discard overlapping/invalid items 1434 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { 1435 long containerIndex = item.screenId; 1436 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1437 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { 1438 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) 1439 [(int) item.screenId][0] != null) { 1440 Log.e(TAG, "Error loading shortcut into hotseat " + item 1441 + " into position (" + item.screenId + ":" + item.cellX + "," 1442 + item.cellY + ") occupied by " 1443 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) 1444 [(int) item.screenId][0]); 1445 return false; 1446 } 1447 } else { 1448 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; 1449 items[(int) item.screenId][0] = item; 1450 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); 1451 return true; 1452 } 1453 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { 1454 // Skip further checking if it is not the hotseat or workspace container 1455 return true; 1456 } 1457 1458 if (!occupied.containsKey(item.screenId)) { 1459 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; 1460 occupied.put(item.screenId, items); 1461 } 1462 1463 ItemInfo[][] screens = occupied.get(item.screenId); 1464 // Check if any workspace icons overlap with each other 1465 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { 1466 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { 1467 if (screens[x][y] != null) { 1468 Log.e(TAG, "Error loading shortcut " + item 1469 + " into cell (" + containerIndex + "-" + item.screenId + ":" 1470 + x + "," + y 1471 + ") occupied by " 1472 + screens[x][y]); 1473 return false; 1474 } 1475 } 1476 } 1477 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { 1478 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { 1479 screens[x][y] = item; 1480 } 1481 } 1482 1483 return true; 1484 } 1485 1486 private void loadWorkspace() { 1487 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 1488 1489 final Context context = mContext; 1490 final ContentResolver contentResolver = context.getContentResolver(); 1491 final PackageManager manager = context.getPackageManager(); 1492 final AppWidgetManager widgets = AppWidgetManager.getInstance(context); 1493 final boolean isSafeMode = manager.isSafeMode(); 1494 1495 // Make sure the default workspace is loaded, if needed 1496 boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb(); 1497 Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI : 1498 LauncherSettings.Favorites.CONTENT_URI; 1499 1500 mIsUpgradePath = loadOldDb; 1501 1502 synchronized (sBgLock) { 1503 sBgWorkspaceItems.clear(); 1504 sBgAppWidgets.clear(); 1505 sBgFolders.clear(); 1506 sBgItemsIdMap.clear(); 1507 sBgDbIconCache.clear(); 1508 sBgWorkspaceScreens.clear(); 1509 1510 final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); 1511 1512 final Cursor c = contentResolver.query(contentUri, null, null, null, null); 1513 1514 // +1 for the hotseat (it can be larger than the workspace) 1515 // Load workspace in reverse order to ensure that latest items are loaded first (and 1516 // before any earlier duplicates) 1517 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); 1518 1519 try { 1520 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); 1521 final int intentIndex = c.getColumnIndexOrThrow 1522 (LauncherSettings.Favorites.INTENT); 1523 final int titleIndex = c.getColumnIndexOrThrow 1524 (LauncherSettings.Favorites.TITLE); 1525 final int iconTypeIndex = c.getColumnIndexOrThrow( 1526 LauncherSettings.Favorites.ICON_TYPE); 1527 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); 1528 final int iconPackageIndex = c.getColumnIndexOrThrow( 1529 LauncherSettings.Favorites.ICON_PACKAGE); 1530 final int iconResourceIndex = c.getColumnIndexOrThrow( 1531 LauncherSettings.Favorites.ICON_RESOURCE); 1532 final int containerIndex = c.getColumnIndexOrThrow( 1533 LauncherSettings.Favorites.CONTAINER); 1534 final int itemTypeIndex = c.getColumnIndexOrThrow( 1535 LauncherSettings.Favorites.ITEM_TYPE); 1536 final int appWidgetIdIndex = c.getColumnIndexOrThrow( 1537 LauncherSettings.Favorites.APPWIDGET_ID); 1538 final int screenIndex = c.getColumnIndexOrThrow( 1539 LauncherSettings.Favorites.SCREEN); 1540 final int cellXIndex = c.getColumnIndexOrThrow 1541 (LauncherSettings.Favorites.CELLX); 1542 final int cellYIndex = c.getColumnIndexOrThrow 1543 (LauncherSettings.Favorites.CELLY); 1544 final int spanXIndex = c.getColumnIndexOrThrow 1545 (LauncherSettings.Favorites.SPANX); 1546 final int spanYIndex = c.getColumnIndexOrThrow( 1547 LauncherSettings.Favorites.SPANY); 1548 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); 1549 //final int displayModeIndex = c.getColumnIndexOrThrow( 1550 // LauncherSettings.Favorites.DISPLAY_MODE); 1551 1552 ShortcutInfo info; 1553 String intentDescription; 1554 LauncherAppWidgetInfo appWidgetInfo; 1555 int container; 1556 long id; 1557 Intent intent; 1558 1559 while (!mStopped && c.moveToNext()) { 1560 try { 1561 int itemType = c.getInt(itemTypeIndex); 1562 1563 switch (itemType) { 1564 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 1565 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 1566 intentDescription = c.getString(intentIndex); 1567 try { 1568 intent = Intent.parseUri(intentDescription, 0); 1569 } catch (URISyntaxException e) { 1570 continue; 1571 } 1572 1573 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { 1574 info = getShortcutInfo(manager, intent, context, c, iconIndex, 1575 titleIndex, mLabelCache); 1576 } else { 1577 info = getShortcutInfo(c, context, iconTypeIndex, 1578 iconPackageIndex, iconResourceIndex, iconIndex, 1579 titleIndex); 1580 1581 // App shortcuts that used to be automatically added to Launcher 1582 // didn't always have the correct intent flags set, so do that 1583 // here 1584 if (intent.getAction() != null && 1585 intent.getCategories() != null && 1586 intent.getAction().equals(Intent.ACTION_MAIN) && 1587 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { 1588 intent.addFlags( 1589 Intent.FLAG_ACTIVITY_NEW_TASK | 1590 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 1591 } 1592 } 1593 1594 if (info != null) { 1595 info.intent = intent; 1596 info.id = c.getLong(idIndex); 1597 container = c.getInt(containerIndex); 1598 info.container = container; 1599 info.screenId = c.getInt(screenIndex); 1600 info.cellX = c.getInt(cellXIndex); 1601 info.cellY = c.getInt(cellYIndex); 1602 // check & update map of what's occupied 1603 if (!checkItemPlacement(occupied, info)) { 1604 break; 1605 } 1606 1607 switch (container) { 1608 case LauncherSettings.Favorites.CONTAINER_DESKTOP: 1609 case LauncherSettings.Favorites.CONTAINER_HOTSEAT: 1610 sBgWorkspaceItems.add(info); 1611 break; 1612 default: 1613 // Item is in a user folder 1614 FolderInfo folderInfo = 1615 findOrMakeFolder(sBgFolders, container); 1616 folderInfo.add(info); 1617 break; 1618 } 1619 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 1620 loadOldDb) { 1621 info.screenId = permuteScreens(info.screenId); 1622 } 1623 sBgItemsIdMap.put(info.id, info); 1624 1625 // now that we've loaded everthing re-save it with the 1626 // icon in case it disappears somehow. 1627 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); 1628 } else { 1629 // Failed to load the shortcut, probably because the 1630 // activity manager couldn't resolve it (maybe the app 1631 // was uninstalled), or the db row was somehow screwed up. 1632 // Delete it. 1633 id = c.getLong(idIndex); 1634 Log.e(TAG, "Error loading shortcut " + id + ", removing it"); 1635 contentResolver.delete(LauncherSettings.Favorites.getContentUri( 1636 id, false), null, null); 1637 } 1638 break; 1639 1640 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 1641 id = c.getLong(idIndex); 1642 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); 1643 1644 folderInfo.title = c.getString(titleIndex); 1645 folderInfo.id = id; 1646 container = c.getInt(containerIndex); 1647 folderInfo.container = container; 1648 folderInfo.screenId = c.getInt(screenIndex); 1649 folderInfo.cellX = c.getInt(cellXIndex); 1650 folderInfo.cellY = c.getInt(cellYIndex); 1651 1652 // check & update map of what's occupied 1653 if (!checkItemPlacement(occupied, folderInfo)) { 1654 break; 1655 } 1656 switch (container) { 1657 case LauncherSettings.Favorites.CONTAINER_DESKTOP: 1658 case LauncherSettings.Favorites.CONTAINER_HOTSEAT: 1659 sBgWorkspaceItems.add(folderInfo); 1660 break; 1661 } 1662 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 1663 loadOldDb) { 1664 folderInfo.screenId = permuteScreens(folderInfo.screenId); 1665 } 1666 1667 sBgItemsIdMap.put(folderInfo.id, folderInfo); 1668 sBgFolders.put(folderInfo.id, folderInfo); 1669 break; 1670 1671 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 1672 // Read all Launcher-specific widget details 1673 int appWidgetId = c.getInt(appWidgetIdIndex); 1674 id = c.getLong(idIndex); 1675 1676 final AppWidgetProviderInfo provider = 1677 widgets.getAppWidgetInfo(appWidgetId); 1678 1679 if (!isSafeMode && (provider == null || provider.provider == null || 1680 provider.provider.getPackageName() == null)) { 1681 String log = "Deleting widget that isn't installed anymore: id=" 1682 + id + " appWidgetId=" + appWidgetId; 1683 Log.e(TAG, log); 1684 Launcher.sDumpLogs.add(log); 1685 itemsToRemove.add(id); 1686 } else { 1687 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, 1688 provider.provider); 1689 appWidgetInfo.id = id; 1690 appWidgetInfo.screenId = c.getInt(screenIndex); 1691 appWidgetInfo.cellX = c.getInt(cellXIndex); 1692 appWidgetInfo.cellY = c.getInt(cellYIndex); 1693 appWidgetInfo.spanX = c.getInt(spanXIndex); 1694 appWidgetInfo.spanY = c.getInt(spanYIndex); 1695 int[] minSpan = Launcher.getMinSpanForWidget(context, provider); 1696 appWidgetInfo.minSpanX = minSpan[0]; 1697 appWidgetInfo.minSpanY = minSpan[1]; 1698 1699 container = c.getInt(containerIndex); 1700 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && 1701 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1702 Log.e(TAG, "Widget found where container != " + 1703 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); 1704 continue; 1705 } 1706 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 1707 loadOldDb) { 1708 appWidgetInfo.screenId = 1709 permuteScreens(appWidgetInfo.screenId); 1710 } 1711 1712 appWidgetInfo.container = c.getInt(containerIndex); 1713 // check & update map of what's occupied 1714 if (!checkItemPlacement(occupied, appWidgetInfo)) { 1715 break; 1716 } 1717 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); 1718 sBgAppWidgets.add(appWidgetInfo); 1719 } 1720 break; 1721 } 1722 } catch (Exception e) { 1723 Log.w(TAG, "Desktop items loading interrupted:", e); 1724 } 1725 } 1726 } finally { 1727 c.close(); 1728 } 1729 1730 if (itemsToRemove.size() > 0) { 1731 ContentProviderClient client = contentResolver.acquireContentProviderClient( 1732 LauncherSettings.Favorites.CONTENT_URI); 1733 // Remove dead items 1734 for (long id : itemsToRemove) { 1735 if (DEBUG_LOADERS) { 1736 Log.d(TAG, "Removed id = " + id); 1737 } 1738 // Don't notify content observers 1739 try { 1740 client.delete(LauncherSettings.Favorites.getContentUri(id, false), 1741 null, null); 1742 } catch (RemoteException e) { 1743 Log.w(TAG, "Could not remove id = " + id); 1744 } 1745 } 1746 } 1747 1748 if (loadOldDb) { 1749 long maxScreenId = 0; 1750 // If we're importing we use the old screen order. 1751 for (ItemInfo item: sBgItemsIdMap.values()) { 1752 long screenId = item.screenId; 1753 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 1754 !sBgWorkspaceScreens.contains(screenId)) { 1755 sBgWorkspaceScreens.add(screenId); 1756 if (screenId > maxScreenId) { 1757 maxScreenId = screenId; 1758 } 1759 } 1760 } 1761 Collections.sort(sBgWorkspaceScreens); 1762 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); 1763 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); 1764 } else { 1765 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; 1766 final Cursor sc = contentResolver.query(screensUri, null, null, null, null); 1767 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); 1768 1769 try { 1770 final int idIndex = sc.getColumnIndexOrThrow( 1771 LauncherSettings.WorkspaceScreens._ID); 1772 final int rankIndex = sc.getColumnIndexOrThrow( 1773 LauncherSettings.WorkspaceScreens.SCREEN_RANK); 1774 while (sc.moveToNext()) { 1775 try { 1776 long screenId = sc.getLong(idIndex); 1777 int rank = sc.getInt(rankIndex); 1778 1779 orderedScreens.put(rank, screenId); 1780 } catch (Exception e) { 1781 Log.w(TAG, "Desktop items loading interrupted:", e); 1782 } 1783 } 1784 } finally { 1785 sc.close(); 1786 } 1787 1788 Iterator<Integer> iter = orderedScreens.keySet().iterator(); 1789 while (iter.hasNext()) { 1790 sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); 1791 } 1792 1793 // Remove any empty screens 1794 ArrayList<Long> unusedScreens = new ArrayList<Long>(); 1795 unusedScreens.addAll(sBgWorkspaceScreens); 1796 1797 for (ItemInfo item: sBgItemsIdMap.values()) { 1798 long screenId = item.screenId; 1799 1800 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 1801 unusedScreens.contains(screenId)) { 1802 unusedScreens.remove(screenId); 1803 } 1804 } 1805 1806 // If there are any empty screens remove them, and update. 1807 if (unusedScreens.size() != 0) { 1808 sBgWorkspaceScreens.removeAll(unusedScreens); 1809 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); 1810 } 1811 } 1812 1813 if (DEBUG_LOADERS) { 1814 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); 1815 Log.d(TAG, "workspace layout: "); 1816 int nScreens = occupied.size(); 1817 for (int y = 0; y < mCellCountY; y++) { 1818 String line = ""; 1819 1820 Iterator<Long> iter = occupied.keySet().iterator(); 1821 while (iter.hasNext()) { 1822 long screenId = iter.next(); 1823 if (screenId > 0) { 1824 line += " | "; 1825 } 1826 for (int x = 0; x < mCellCountX; x++) { 1827 line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); 1828 } 1829 } 1830 Log.d(TAG, "[ " + line + " ]"); 1831 } 1832 } 1833 } 1834 } 1835 1836 // We rearrange the screens from the old launcher 1837 // 12345 -> 34512 1838 private long permuteScreens(long screen) { 1839 if (screen >= 2) { 1840 return screen - 2; 1841 } else { 1842 return screen + 3; 1843 } 1844 } 1845 1846 /** Filters the set of items who are directly or indirectly (via another container) on the 1847 * specified screen. */ 1848 private void filterCurrentWorkspaceItems(int currentScreen, 1849 ArrayList<ItemInfo> allWorkspaceItems, 1850 ArrayList<ItemInfo> currentScreenItems, 1851 ArrayList<ItemInfo> otherScreenItems) { 1852 // Purge any null ItemInfos 1853 Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); 1854 while (iter.hasNext()) { 1855 ItemInfo i = iter.next(); 1856 if (i == null) { 1857 iter.remove(); 1858 } 1859 } 1860 1861 // If we aren't filtering on a screen, then the set of items to load is the full set of 1862 // items given. 1863 if (currentScreen < 0) { 1864 currentScreenItems.addAll(allWorkspaceItems); 1865 } 1866 1867 // Order the set of items by their containers first, this allows use to walk through the 1868 // list sequentially, build up a list of containers that are in the specified screen, 1869 // as well as all items in those containers. 1870 Set<Long> itemsOnScreen = new HashSet<Long>(); 1871 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { 1872 @Override 1873 public int compare(ItemInfo lhs, ItemInfo rhs) { 1874 return (int) (lhs.container - rhs.container); 1875 } 1876 }); 1877 for (ItemInfo info : allWorkspaceItems) { 1878 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 1879 if (info.screenId == currentScreen) { 1880 currentScreenItems.add(info); 1881 itemsOnScreen.add(info.id); 1882 } else { 1883 otherScreenItems.add(info); 1884 } 1885 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1886 currentScreenItems.add(info); 1887 itemsOnScreen.add(info.id); 1888 } else { 1889 if (itemsOnScreen.contains(info.container)) { 1890 currentScreenItems.add(info); 1891 itemsOnScreen.add(info.id); 1892 } else { 1893 otherScreenItems.add(info); 1894 } 1895 } 1896 } 1897 } 1898 1899 /** Filters the set of widgets which are on the specified screen. */ 1900 private void filterCurrentAppWidgets(int currentScreen, 1901 ArrayList<LauncherAppWidgetInfo> appWidgets, 1902 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, 1903 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { 1904 // If we aren't filtering on a screen, then the set of items to load is the full set of 1905 // widgets given. 1906 if (currentScreen < 0) { 1907 currentScreenWidgets.addAll(appWidgets); 1908 } 1909 1910 for (LauncherAppWidgetInfo widget : appWidgets) { 1911 if (widget == null) continue; 1912 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 1913 widget.screenId == currentScreen) { 1914 currentScreenWidgets.add(widget); 1915 } else { 1916 otherScreenWidgets.add(widget); 1917 } 1918 } 1919 } 1920 1921 /** Filters the set of folders which are on the specified screen. */ 1922 private void filterCurrentFolders(int currentScreen, 1923 HashMap<Long, ItemInfo> itemsIdMap, 1924 HashMap<Long, FolderInfo> folders, 1925 HashMap<Long, FolderInfo> currentScreenFolders, 1926 HashMap<Long, FolderInfo> otherScreenFolders) { 1927 // If we aren't filtering on a screen, then the set of items to load is the full set of 1928 // widgets given. 1929 if (currentScreen < 0) { 1930 currentScreenFolders.putAll(folders); 1931 } 1932 1933 for (long id : folders.keySet()) { 1934 ItemInfo info = itemsIdMap.get(id); 1935 FolderInfo folder = folders.get(id); 1936 if (info == null || folder == null) continue; 1937 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 1938 info.screenId == currentScreen) { 1939 currentScreenFolders.put(id, folder); 1940 } else { 1941 otherScreenFolders.put(id, folder); 1942 } 1943 } 1944 } 1945 1946 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to 1947 * right) */ 1948 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { 1949 // XXX: review this 1950 Collections.sort(workspaceItems, new Comparator<ItemInfo>() { 1951 @Override 1952 public int compare(ItemInfo lhs, ItemInfo rhs) { 1953 int cellCountX = LauncherModel.getCellCountX(); 1954 int cellCountY = LauncherModel.getCellCountY(); 1955 int screenOffset = cellCountX * cellCountY; 1956 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat 1957 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + 1958 lhs.cellY * cellCountX + lhs.cellX); 1959 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + 1960 rhs.cellY * cellCountX + rhs.cellX); 1961 return (int) (lr - rr); 1962 } 1963 }); 1964 } 1965 1966 private void bindWorkspaceScreens(final Callbacks oldCallbacks, 1967 final ArrayList<Long> orderedScreens) { 1968 1969 final Runnable r = new Runnable() { 1970 @Override 1971 public void run() { 1972 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 1973 if (callbacks != null) { 1974 callbacks.bindScreens(orderedScreens); 1975 } 1976 } 1977 }; 1978 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); 1979 } 1980 1981 private void bindWorkspaceItems(final Callbacks oldCallbacks, 1982 final ArrayList<ItemInfo> workspaceItems, 1983 final ArrayList<LauncherAppWidgetInfo> appWidgets, 1984 final HashMap<Long, FolderInfo> folders, 1985 ArrayList<Runnable> deferredBindRunnables) { 1986 1987 final boolean postOnMainThread = (deferredBindRunnables != null); 1988 1989 // Bind the workspace items 1990 int N = workspaceItems.size(); 1991 for (int i = 0; i < N; i += ITEMS_CHUNK) { 1992 final int start = i; 1993 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); 1994 final Runnable r = new Runnable() { 1995 @Override 1996 public void run() { 1997 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 1998 if (callbacks != null) { 1999 callbacks.bindItems(workspaceItems, start, start+chunkSize, 2000 false); 2001 } 2002 } 2003 }; 2004 if (postOnMainThread) { 2005 deferredBindRunnables.add(r); 2006 } else { 2007 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); 2008 } 2009 } 2010 2011 // Bind the folders 2012 if (!folders.isEmpty()) { 2013 final Runnable r = new Runnable() { 2014 public void run() { 2015 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2016 if (callbacks != null) { 2017 callbacks.bindFolders(folders); 2018 } 2019 } 2020 }; 2021 if (postOnMainThread) { 2022 deferredBindRunnables.add(r); 2023 } else { 2024 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); 2025 } 2026 } 2027 2028 // Bind the widgets, one at a time 2029 N = appWidgets.size(); 2030 for (int i = 0; i < N; i++) { 2031 final LauncherAppWidgetInfo widget = appWidgets.get(i); 2032 final Runnable r = new Runnable() { 2033 public void run() { 2034 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2035 if (callbacks != null) { 2036 callbacks.bindAppWidget(widget); 2037 } 2038 } 2039 }; 2040 if (postOnMainThread) { 2041 deferredBindRunnables.add(r); 2042 } else { 2043 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); 2044 } 2045 } 2046 } 2047 2048 /** 2049 * Binds all loaded data to actual views on the main thread. 2050 */ 2051 private void bindWorkspace(int synchronizeBindPage) { 2052 final long t = SystemClock.uptimeMillis(); 2053 Runnable r; 2054 2055 // Don't use these two variables in any of the callback runnables. 2056 // Otherwise we hold a reference to them. 2057 final Callbacks oldCallbacks = mCallbacks.get(); 2058 if (oldCallbacks == null) { 2059 // This launcher has exited and nobody bothered to tell us. Just bail. 2060 Log.w(TAG, "LoaderTask running with no launcher"); 2061 return; 2062 } 2063 2064 final boolean isLoadingSynchronously = (synchronizeBindPage > -1); 2065 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : 2066 oldCallbacks.getCurrentWorkspaceScreen(); 2067 2068 // Load all the items that are on the current page first (and in the process, unbind 2069 // all the existing workspace items before we call startBinding() below. 2070 unbindWorkspaceItemsOnMainThread(); 2071 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); 2072 ArrayList<LauncherAppWidgetInfo> appWidgets = 2073 new ArrayList<LauncherAppWidgetInfo>(); 2074 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); 2075 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); 2076 ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); 2077 synchronized (sBgLock) { 2078 workspaceItems.addAll(sBgWorkspaceItems); 2079 appWidgets.addAll(sBgAppWidgets); 2080 folders.putAll(sBgFolders); 2081 itemsIdMap.putAll(sBgItemsIdMap); 2082 orderedScreenIds.addAll(sBgWorkspaceScreens); 2083 } 2084 2085 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); 2086 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); 2087 ArrayList<LauncherAppWidgetInfo> currentAppWidgets = 2088 new ArrayList<LauncherAppWidgetInfo>(); 2089 ArrayList<LauncherAppWidgetInfo> otherAppWidgets = 2090 new ArrayList<LauncherAppWidgetInfo>(); 2091 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); 2092 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); 2093 2094 // Separate the items that are on the current screen, and all the other remaining items 2095 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, 2096 otherWorkspaceItems); 2097 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, 2098 otherAppWidgets); 2099 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, 2100 otherFolders); 2101 sortWorkspaceItemsSpatially(currentWorkspaceItems); 2102 sortWorkspaceItemsSpatially(otherWorkspaceItems); 2103 2104 // Tell the workspace that we're about to start binding items 2105 r = new Runnable() { 2106 public void run() { 2107 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2108 if (callbacks != null) { 2109 callbacks.startBinding(); 2110 } 2111 } 2112 }; 2113 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); 2114 2115 bindWorkspaceScreens(oldCallbacks, orderedScreenIds); 2116 2117 // Load items on the current page 2118 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, 2119 currentFolders, null); 2120 if (isLoadingSynchronously) { 2121 r = new Runnable() { 2122 public void run() { 2123 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2124 if (callbacks != null) { 2125 callbacks.onPageBoundSynchronously(currentScreen); 2126 } 2127 } 2128 }; 2129 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); 2130 } 2131 2132 // Load all the remaining pages (if we are loading synchronously, we want to defer this 2133 // work until after the first render) 2134 mDeferredBindRunnables.clear(); 2135 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, 2136 (isLoadingSynchronously ? mDeferredBindRunnables : null)); 2137 2138 // Tell the workspace that we're done binding items 2139 r = new Runnable() { 2140 public void run() { 2141 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2142 if (callbacks != null) { 2143 callbacks.finishBindingItems(mIsUpgradePath); 2144 } 2145 2146 // If we're profiling, ensure this is the last thing in the queue. 2147 if (DEBUG_LOADERS) { 2148 Log.d(TAG, "bound workspace in " 2149 + (SystemClock.uptimeMillis()-t) + "ms"); 2150 } 2151 2152 mIsLoadingAndBindingWorkspace = false; 2153 } 2154 }; 2155 if (isLoadingSynchronously) { 2156 mDeferredBindRunnables.add(r); 2157 } else { 2158 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); 2159 } 2160 } 2161 2162 private void loadAndBindAllApps() { 2163 if (DEBUG_LOADERS) { 2164 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); 2165 } 2166 if (!mAllAppsLoaded) { 2167 loadAllApps(); 2168 synchronized (LoaderTask.this) { 2169 if (mStopped) { 2170 return; 2171 } 2172 mAllAppsLoaded = true; 2173 } 2174 } else { 2175 onlyBindAllApps(); 2176 } 2177 } 2178 2179 private void onlyBindAllApps() { 2180 final Callbacks oldCallbacks = mCallbacks.get(); 2181 if (oldCallbacks == null) { 2182 // This launcher has exited and nobody bothered to tell us. Just bail. 2183 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); 2184 return; 2185 } 2186 2187 // shallow copy 2188 @SuppressWarnings("unchecked") 2189 final ArrayList<ApplicationInfo> list 2190 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); 2191 Runnable r = new Runnable() { 2192 public void run() { 2193 final long t = SystemClock.uptimeMillis(); 2194 final Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2195 if (callbacks != null) { 2196 callbacks.bindAllApplications(list); 2197 } 2198 if (DEBUG_LOADERS) { 2199 Log.d(TAG, "bound all " + list.size() + " apps from cache in " 2200 + (SystemClock.uptimeMillis()-t) + "ms"); 2201 } 2202 } 2203 }; 2204 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); 2205 if (isRunningOnMainThread) { 2206 r.run(); 2207 } else { 2208 mHandler.post(r); 2209 } 2210 } 2211 2212 private void loadAllApps() { 2213 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 2214 2215 // Don't use these two variables in any of the callback runnables. 2216 // Otherwise we hold a reference to them. 2217 final Callbacks oldCallbacks = mCallbacks.get(); 2218 if (oldCallbacks == null) { 2219 // This launcher has exited and nobody bothered to tell us. Just bail. 2220 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); 2221 return; 2222 } 2223 2224 final PackageManager packageManager = mContext.getPackageManager(); 2225 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 2226 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 2227 2228 // Clear the list of apps 2229 mBgAllAppsList.clear(); 2230 2231 // Query for the set of apps 2232 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 2233 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); 2234 if (DEBUG_LOADERS) { 2235 Log.d(TAG, "queryIntentActivities took " 2236 + (SystemClock.uptimeMillis()-qiaTime) + "ms"); 2237 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); 2238 } 2239 // Fail if we don't have any apps 2240 if (apps == null || apps.isEmpty()) { 2241 return; 2242 } 2243 // Sort the applications by name 2244 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 2245 Collections.sort(apps, 2246 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); 2247 if (DEBUG_LOADERS) { 2248 Log.d(TAG, "sort took " 2249 + (SystemClock.uptimeMillis()-sortTime) + "ms"); 2250 } 2251 2252 // Create the ApplicationInfos 2253 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 2254 for (int i = 0; i < apps.size(); i++) { 2255 // This builds the icon bitmaps. 2256 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), 2257 mIconCache, mLabelCache)); 2258 } 2259 2260 final Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2261 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; 2262 mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); 2263 2264 // Post callback on main thread 2265 mHandler.post(new Runnable() { 2266 public void run() { 2267 final long bindTime = SystemClock.uptimeMillis(); 2268 if (callbacks != null) { 2269 callbacks.bindAllApplications(added); 2270 if (DEBUG_LOADERS) { 2271 Log.d(TAG, "bound " + added.size() + " apps in " 2272 + (SystemClock.uptimeMillis() - bindTime) + "ms"); 2273 } 2274 } else { 2275 Log.i(TAG, "not binding apps: no Launcher activity"); 2276 } 2277 } 2278 }); 2279 2280 if (DEBUG_LOADERS) { 2281 Log.d(TAG, "Icons processed in " 2282 + (SystemClock.uptimeMillis() - loadTime) + "ms"); 2283 } 2284 } 2285 2286 public void dumpState() { 2287 synchronized (sBgLock) { 2288 Log.d(TAG, "mLoaderTask.mContext=" + mContext); 2289 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); 2290 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); 2291 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); 2292 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); 2293 } 2294 } 2295 } 2296 2297 void enqueuePackageUpdated(PackageUpdatedTask task) { 2298 sWorker.post(task); 2299 } 2300 2301 private class PackageUpdatedTask implements Runnable { 2302 int mOp; 2303 String[] mPackages; 2304 2305 public static final int OP_NONE = 0; 2306 public static final int OP_ADD = 1; 2307 public static final int OP_UPDATE = 2; 2308 public static final int OP_REMOVE = 3; // uninstlled 2309 public static final int OP_UNAVAILABLE = 4; // external media unmounted 2310 2311 2312 public PackageUpdatedTask(int op, String[] packages) { 2313 mOp = op; 2314 mPackages = packages; 2315 } 2316 2317 public void run() { 2318 final Context context = mApp.getContext(); 2319 2320 final String[] packages = mPackages; 2321 final int N = packages.length; 2322 switch (mOp) { 2323 case OP_ADD: 2324 for (int i=0; i<N; i++) { 2325 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); 2326 mBgAllAppsList.addPackage(context, packages[i]); 2327 } 2328 break; 2329 case OP_UPDATE: 2330 for (int i=0; i<N; i++) { 2331 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); 2332 mBgAllAppsList.updatePackage(context, packages[i]); 2333 WidgetPreviewLoader.removeFromDb( 2334 mApp.getWidgetPreviewCacheDb(), packages[i]); 2335 } 2336 break; 2337 case OP_REMOVE: 2338 case OP_UNAVAILABLE: 2339 for (int i=0; i<N; i++) { 2340 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); 2341 mBgAllAppsList.removePackage(packages[i]); 2342 WidgetPreviewLoader.removeFromDb( 2343 mApp.getWidgetPreviewCacheDb(), packages[i]); 2344 } 2345 break; 2346 } 2347 2348 ArrayList<ApplicationInfo> added = null; 2349 ArrayList<ApplicationInfo> modified = null; 2350 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); 2351 2352 if (mBgAllAppsList.added.size() > 0) { 2353 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); 2354 mBgAllAppsList.added.clear(); 2355 } 2356 if (mBgAllAppsList.modified.size() > 0) { 2357 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); 2358 mBgAllAppsList.modified.clear(); 2359 } 2360 if (mBgAllAppsList.removed.size() > 0) { 2361 removedApps.addAll(mBgAllAppsList.removed); 2362 mBgAllAppsList.removed.clear(); 2363 } 2364 2365 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; 2366 if (callbacks == null) { 2367 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); 2368 return; 2369 } 2370 2371 if (added != null) { 2372 // Ensure that we add all the workspace applications to the db 2373 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; 2374 addAndBindAddedApps(context, added, cb); 2375 } 2376 if (modified != null) { 2377 final ArrayList<ApplicationInfo> modifiedFinal = modified; 2378 2379 // Update the launcher db to reflect the changes 2380 for (ApplicationInfo a : modifiedFinal) { 2381 ArrayList<ItemInfo> infos = 2382 getItemInfoForComponentName(a.componentName); 2383 for (ItemInfo i : infos) { 2384 if (isShortcutInfoUpdateable(i)) { 2385 ShortcutInfo info = (ShortcutInfo) i; 2386 info.title = a.title.toString(); 2387 updateItemInDatabase(context, info); 2388 } 2389 } 2390 } 2391 2392 mHandler.post(new Runnable() { 2393 public void run() { 2394 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; 2395 if (callbacks == cb && cb != null) { 2396 callbacks.bindAppsUpdated(modifiedFinal); 2397 } 2398 } 2399 }); 2400 } 2401 // If a package has been removed, or an app has been removed as a result of 2402 // an update (for example), make the removed callback. 2403 if (mOp == OP_REMOVE || !removedApps.isEmpty()) { 2404 final boolean packageRemoved = (mOp == OP_REMOVE); 2405 final ArrayList<String> removedPackageNames = 2406 new ArrayList<String>(Arrays.asList(packages)); 2407 2408 // Update the launcher db to reflect the removal of apps 2409 if (packageRemoved) { 2410 for (String pn : removedPackageNames) { 2411 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); 2412 for (ItemInfo i : infos) { 2413 deleteItemFromDatabase(context, i); 2414 } 2415 } 2416 } else { 2417 for (ApplicationInfo a : removedApps) { 2418 ArrayList<ItemInfo> infos = 2419 getItemInfoForComponentName(a.componentName); 2420 for (ItemInfo i : infos) { 2421 deleteItemFromDatabase(context, i); 2422 } 2423 } 2424 } 2425 2426 mHandler.post(new Runnable() { 2427 public void run() { 2428 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; 2429 if (callbacks == cb && cb != null) { 2430 callbacks.bindComponentsRemoved(removedPackageNames, 2431 removedApps, packageRemoved); 2432 } 2433 } 2434 }); 2435 } 2436 2437 final ArrayList<Object> widgetsAndShortcuts = 2438 getSortedWidgetsAndShortcuts(context); 2439 mHandler.post(new Runnable() { 2440 @Override 2441 public void run() { 2442 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; 2443 if (callbacks == cb && cb != null) { 2444 callbacks.bindPackagesUpdated(widgetsAndShortcuts); 2445 } 2446 } 2447 }); 2448 } 2449 } 2450 2451 // Returns a list of ResolveInfos/AppWindowInfos in sorted order 2452 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { 2453 PackageManager packageManager = context.getPackageManager(); 2454 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); 2455 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); 2456 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); 2457 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); 2458 Collections.sort(widgetsAndShortcuts, 2459 new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); 2460 return widgetsAndShortcuts; 2461 } 2462 2463 /** 2464 * This is called from the code that adds shortcuts from the intent receiver. This 2465 * doesn't have a Cursor, but 2466 */ 2467 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { 2468 return getShortcutInfo(manager, intent, context, null, -1, -1, null); 2469 } 2470 2471 /** 2472 * Make an ShortcutInfo object for a shortcut that is an application. 2473 * 2474 * If c is not null, then it will be used to fill in missing data like the title and icon. 2475 */ 2476 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, 2477 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { 2478 Bitmap icon = null; 2479 final ShortcutInfo info = new ShortcutInfo(); 2480 2481 ComponentName componentName = intent.getComponent(); 2482 if (componentName == null) { 2483 return null; 2484 } 2485 2486 try { 2487 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); 2488 if (!pi.applicationInfo.enabled) { 2489 // If we return null here, the corresponding item will be removed from the launcher 2490 // db and will not appear in the workspace. 2491 return null; 2492 } 2493 } catch (NameNotFoundException e) { 2494 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); 2495 } 2496 2497 // TODO: See if the PackageManager knows about this case. If it doesn't 2498 // then return null & delete this. 2499 2500 // the resource -- This may implicitly give us back the fallback icon, 2501 // but don't worry about that. All we're doing with usingFallbackIcon is 2502 // to avoid saving lots of copies of that in the database, and most apps 2503 // have icons anyway. 2504 2505 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and 2506 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info 2507 // via resolveActivity(). 2508 ResolveInfo resolveInfo = null; 2509 ComponentName oldComponent = intent.getComponent(); 2510 Intent newIntent = new Intent(intent.getAction(), null); 2511 newIntent.addCategory(Intent.CATEGORY_LAUNCHER); 2512 newIntent.setPackage(oldComponent.getPackageName()); 2513 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); 2514 for (ResolveInfo i : infos) { 2515 ComponentName cn = new ComponentName(i.activityInfo.packageName, 2516 i.activityInfo.name); 2517 if (cn.equals(oldComponent)) { 2518 resolveInfo = i; 2519 } 2520 } 2521 if (resolveInfo == null) { 2522 resolveInfo = manager.resolveActivity(intent, 0); 2523 } 2524 if (resolveInfo != null) { 2525 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); 2526 } 2527 // the db 2528 if (icon == null) { 2529 if (c != null) { 2530 icon = getIconFromCursor(c, iconIndex, context); 2531 } 2532 } 2533 // the fallback icon 2534 if (icon == null) { 2535 icon = getFallbackIcon(); 2536 info.usingFallbackIcon = true; 2537 } 2538 info.setIcon(icon); 2539 2540 // from the resource 2541 if (resolveInfo != null) { 2542 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); 2543 if (labelCache != null && labelCache.containsKey(key)) { 2544 info.title = labelCache.get(key); 2545 } else { 2546 info.title = resolveInfo.activityInfo.loadLabel(manager); 2547 if (labelCache != null) { 2548 labelCache.put(key, info.title); 2549 } 2550 } 2551 } 2552 // from the db 2553 if (info.title == null) { 2554 if (c != null) { 2555 info.title = c.getString(titleIndex); 2556 } 2557 } 2558 // fall back to the class name of the activity 2559 if (info.title == null) { 2560 info.title = componentName.getClassName(); 2561 } 2562 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; 2563 return info; 2564 } 2565 2566 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, 2567 ItemInfoFilter f) { 2568 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); 2569 for (ItemInfo i : infos) { 2570 if (i instanceof ShortcutInfo) { 2571 ShortcutInfo info = (ShortcutInfo) i; 2572 ComponentName cn = info.intent.getComponent(); 2573 if (cn != null && f.filterItem(null, info, cn)) { 2574 filtered.add(info); 2575 } 2576 } else if (i instanceof FolderInfo) { 2577 FolderInfo info = (FolderInfo) i; 2578 for (ShortcutInfo s : info.contents) { 2579 ComponentName cn = s.intent.getComponent(); 2580 if (cn != null && f.filterItem(info, s, cn)) { 2581 filtered.add(s); 2582 } 2583 } 2584 } else if (i instanceof LauncherAppWidgetInfo) { 2585 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; 2586 ComponentName cn = info.providerName; 2587 if (cn != null && f.filterItem(null, info, cn)) { 2588 filtered.add(info); 2589 } 2590 } 2591 } 2592 return new ArrayList<ItemInfo>(filtered); 2593 } 2594 2595 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { 2596 HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 2597 ItemInfoFilter filter = new ItemInfoFilter() { 2598 @Override 2599 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { 2600 return cn.getPackageName().equals(pn); 2601 } 2602 }; 2603 return filterItemInfos(sBgItemsIdMap.values(), filter); 2604 } 2605 2606 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { 2607 HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 2608 ItemInfoFilter filter = new ItemInfoFilter() { 2609 @Override 2610 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { 2611 return cn.equals(cname); 2612 } 2613 }; 2614 return filterItemInfos(sBgItemsIdMap.values(), filter); 2615 } 2616 2617 public static boolean isShortcutInfoUpdateable(ItemInfo i) { 2618 if (i instanceof ShortcutInfo) { 2619 ShortcutInfo info = (ShortcutInfo) i; 2620 // We need to check for ACTION_MAIN otherwise getComponent() might 2621 // return null for some shortcuts (for instance, for shortcuts to 2622 // web pages.) 2623 Intent intent = info.intent; 2624 ComponentName name = intent.getComponent(); 2625 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 2626 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 2627 return true; 2628 } 2629 } 2630 return false; 2631 } 2632 2633 /** 2634 * Make an ShortcutInfo object for a shortcut that isn't an application. 2635 */ 2636 private ShortcutInfo getShortcutInfo(Cursor c, Context context, 2637 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, 2638 int titleIndex) { 2639 2640 Bitmap icon = null; 2641 final ShortcutInfo info = new ShortcutInfo(); 2642 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; 2643 2644 // TODO: If there's an explicit component and we can't install that, delete it. 2645 2646 info.title = c.getString(titleIndex); 2647 2648 int iconType = c.getInt(iconTypeIndex); 2649 switch (iconType) { 2650 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: 2651 String packageName = c.getString(iconPackageIndex); 2652 String resourceName = c.getString(iconResourceIndex); 2653 PackageManager packageManager = context.getPackageManager(); 2654 info.customIcon = false; 2655 // the resource 2656 try { 2657 Resources resources = packageManager.getResourcesForApplication(packageName); 2658 if (resources != null) { 2659 final int id = resources.getIdentifier(resourceName, null, null); 2660 icon = Utilities.createIconBitmap( 2661 mIconCache.getFullResIcon(resources, id), context); 2662 } 2663 } catch (Exception e) { 2664 // drop this. we have other places to look for icons 2665 } 2666 // the db 2667 if (icon == null) { 2668 icon = getIconFromCursor(c, iconIndex, context); 2669 } 2670 // the fallback icon 2671 if (icon == null) { 2672 icon = getFallbackIcon(); 2673 info.usingFallbackIcon = true; 2674 } 2675 break; 2676 case LauncherSettings.Favorites.ICON_TYPE_BITMAP: 2677 icon = getIconFromCursor(c, iconIndex, context); 2678 if (icon == null) { 2679 icon = getFallbackIcon(); 2680 info.customIcon = false; 2681 info.usingFallbackIcon = true; 2682 } else { 2683 info.customIcon = true; 2684 } 2685 break; 2686 default: 2687 icon = getFallbackIcon(); 2688 info.usingFallbackIcon = true; 2689 info.customIcon = false; 2690 break; 2691 } 2692 info.setIcon(icon); 2693 return info; 2694 } 2695 2696 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { 2697 @SuppressWarnings("all") // suppress dead code warning 2698 final boolean debug = false; 2699 if (debug) { 2700 Log.d(TAG, "getIconFromCursor app=" 2701 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); 2702 } 2703 byte[] data = c.getBlob(iconIndex); 2704 try { 2705 return Utilities.createIconBitmap( 2706 BitmapFactory.decodeByteArray(data, 0, data.length), context); 2707 } catch (Exception e) { 2708 return null; 2709 } 2710 } 2711 2712 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, 2713 int cellX, int cellY, boolean notify) { 2714 final ShortcutInfo info = infoFromShortcutIntent(context, data, null); 2715 if (info == null) { 2716 return null; 2717 } 2718 addItemToDatabase(context, info, container, screen, cellX, cellY, notify); 2719 2720 return info; 2721 } 2722 2723 /** 2724 * Attempts to find an AppWidgetProviderInfo that matches the given component. 2725 */ 2726 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, 2727 ComponentName component) { 2728 List<AppWidgetProviderInfo> widgets = 2729 AppWidgetManager.getInstance(context).getInstalledProviders(); 2730 for (AppWidgetProviderInfo info : widgets) { 2731 if (info.provider.equals(component)) { 2732 return info; 2733 } 2734 } 2735 return null; 2736 } 2737 2738 /** 2739 * Returns a list of all the widgets that can handle configuration with a particular mimeType. 2740 */ 2741 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { 2742 final PackageManager packageManager = context.getPackageManager(); 2743 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = 2744 new ArrayList<WidgetMimeTypeHandlerData>(); 2745 2746 final Intent supportsIntent = 2747 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); 2748 supportsIntent.setType(mimeType); 2749 2750 // Create a set of widget configuration components that we can test against 2751 final List<AppWidgetProviderInfo> widgets = 2752 AppWidgetManager.getInstance(context).getInstalledProviders(); 2753 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = 2754 new HashMap<ComponentName, AppWidgetProviderInfo>(); 2755 for (AppWidgetProviderInfo info : widgets) { 2756 configurationComponentToWidget.put(info.configure, info); 2757 } 2758 2759 // Run through each of the intents that can handle this type of clip data, and cross 2760 // reference them with the components that are actual configuration components 2761 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, 2762 PackageManager.MATCH_DEFAULT_ONLY); 2763 for (ResolveInfo info : activities) { 2764 final ActivityInfo activityInfo = info.activityInfo; 2765 final ComponentName infoComponent = new ComponentName(activityInfo.packageName, 2766 activityInfo.name); 2767 if (configurationComponentToWidget.containsKey(infoComponent)) { 2768 supportedConfigurationActivities.add( 2769 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, 2770 configurationComponentToWidget.get(infoComponent))); 2771 } 2772 } 2773 return supportedConfigurationActivities; 2774 } 2775 2776 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { 2777 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); 2778 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); 2779 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); 2780 2781 if (intent == null) { 2782 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null 2783 Log.e(TAG, "Can't construct ShorcutInfo with null intent"); 2784 return null; 2785 } 2786 2787 Bitmap icon = null; 2788 boolean customIcon = false; 2789 ShortcutIconResource iconResource = null; 2790 2791 if (bitmap != null && bitmap instanceof Bitmap) { 2792 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); 2793 customIcon = true; 2794 } else { 2795 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); 2796 if (extra != null && extra instanceof ShortcutIconResource) { 2797 try { 2798 iconResource = (ShortcutIconResource) extra; 2799 final PackageManager packageManager = context.getPackageManager(); 2800 Resources resources = packageManager.getResourcesForApplication( 2801 iconResource.packageName); 2802 final int id = resources.getIdentifier(iconResource.resourceName, null, null); 2803 icon = Utilities.createIconBitmap( 2804 mIconCache.getFullResIcon(resources, id), context); 2805 } catch (Exception e) { 2806 Log.w(TAG, "Could not load shortcut icon: " + extra); 2807 } 2808 } 2809 } 2810 2811 final ShortcutInfo info = new ShortcutInfo(); 2812 2813 if (icon == null) { 2814 if (fallbackIcon != null) { 2815 icon = fallbackIcon; 2816 } else { 2817 icon = getFallbackIcon(); 2818 info.usingFallbackIcon = true; 2819 } 2820 } 2821 info.setIcon(icon); 2822 2823 info.title = name; 2824 info.intent = intent; 2825 info.customIcon = customIcon; 2826 info.iconResource = iconResource; 2827 2828 return info; 2829 } 2830 2831 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, 2832 int iconIndex) { 2833 // If apps can't be on SD, don't even bother. 2834 if (!mAppsCanBeOnExternalStorage) { 2835 return false; 2836 } 2837 // If this icon doesn't have a custom icon, check to see 2838 // what's stored in the DB, and if it doesn't match what 2839 // we're going to show, store what we are going to show back 2840 // into the DB. We do this so when we're loading, if the 2841 // package manager can't find an icon (for example because 2842 // the app is on SD) then we can use that instead. 2843 if (!info.customIcon && !info.usingFallbackIcon) { 2844 cache.put(info, c.getBlob(iconIndex)); 2845 return true; 2846 } 2847 return false; 2848 } 2849 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { 2850 boolean needSave = false; 2851 try { 2852 if (data != null) { 2853 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); 2854 Bitmap loaded = info.getIcon(mIconCache); 2855 needSave = !saved.sameAs(loaded); 2856 } else { 2857 needSave = true; 2858 } 2859 } catch (Exception e) { 2860 needSave = true; 2861 } 2862 if (needSave) { 2863 Log.d(TAG, "going to save icon bitmap for info=" + info); 2864 // This is slower than is ideal, but this only happens once 2865 // or when the app is updated with a new icon. 2866 updateItemInDatabase(context, info); 2867 } 2868 } 2869 2870 /** 2871 * Return an existing FolderInfo object if we have encountered this ID previously, 2872 * or make a new one. 2873 */ 2874 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { 2875 // See if a placeholder was created for us already 2876 FolderInfo folderInfo = folders.get(id); 2877 if (folderInfo == null) { 2878 // No placeholder -- create a new instance 2879 folderInfo = new FolderInfo(); 2880 folders.put(id, folderInfo); 2881 } 2882 return folderInfo; 2883 } 2884 2885 public static final Comparator<ApplicationInfo> getAppNameComparator() { 2886 final Collator collator = Collator.getInstance(); 2887 return new Comparator<ApplicationInfo>() { 2888 public final int compare(ApplicationInfo a, ApplicationInfo b) { 2889 int result = collator.compare(a.title.toString(), b.title.toString()); 2890 if (result == 0) { 2891 result = a.componentName.compareTo(b.componentName); 2892 } 2893 return result; 2894 } 2895 }; 2896 } 2897 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR 2898 = new Comparator<ApplicationInfo>() { 2899 public final int compare(ApplicationInfo a, ApplicationInfo b) { 2900 if (a.firstInstallTime < b.firstInstallTime) return 1; 2901 if (a.firstInstallTime > b.firstInstallTime) return -1; 2902 return 0; 2903 } 2904 }; 2905 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { 2906 final Collator collator = Collator.getInstance(); 2907 return new Comparator<AppWidgetProviderInfo>() { 2908 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { 2909 return collator.compare(a.label.toString(), b.label.toString()); 2910 } 2911 }; 2912 } 2913 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { 2914 if (info.activityInfo != null) { 2915 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); 2916 } else { 2917 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); 2918 } 2919 } 2920 public static class ShortcutNameComparator implements Comparator<ResolveInfo> { 2921 private Collator mCollator; 2922 private PackageManager mPackageManager; 2923 private HashMap<Object, CharSequence> mLabelCache; 2924 ShortcutNameComparator(PackageManager pm) { 2925 mPackageManager = pm; 2926 mLabelCache = new HashMap<Object, CharSequence>(); 2927 mCollator = Collator.getInstance(); 2928 } 2929 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { 2930 mPackageManager = pm; 2931 mLabelCache = labelCache; 2932 mCollator = Collator.getInstance(); 2933 } 2934 public final int compare(ResolveInfo a, ResolveInfo b) { 2935 CharSequence labelA, labelB; 2936 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); 2937 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); 2938 if (mLabelCache.containsKey(keyA)) { 2939 labelA = mLabelCache.get(keyA); 2940 } else { 2941 labelA = a.loadLabel(mPackageManager).toString(); 2942 2943 mLabelCache.put(keyA, labelA); 2944 } 2945 if (mLabelCache.containsKey(keyB)) { 2946 labelB = mLabelCache.get(keyB); 2947 } else { 2948 labelB = b.loadLabel(mPackageManager).toString(); 2949 2950 mLabelCache.put(keyB, labelB); 2951 } 2952 return mCollator.compare(labelA, labelB); 2953 } 2954 }; 2955 public static class WidgetAndShortcutNameComparator implements Comparator<Object> { 2956 private Collator mCollator; 2957 private PackageManager mPackageManager; 2958 private HashMap<Object, String> mLabelCache; 2959 WidgetAndShortcutNameComparator(PackageManager pm) { 2960 mPackageManager = pm; 2961 mLabelCache = new HashMap<Object, String>(); 2962 mCollator = Collator.getInstance(); 2963 } 2964 public final int compare(Object a, Object b) { 2965 String labelA, labelB; 2966 if (mLabelCache.containsKey(a)) { 2967 labelA = mLabelCache.get(a); 2968 } else { 2969 labelA = (a instanceof AppWidgetProviderInfo) ? 2970 ((AppWidgetProviderInfo) a).label : 2971 ((ResolveInfo) a).loadLabel(mPackageManager).toString(); 2972 mLabelCache.put(a, labelA); 2973 } 2974 if (mLabelCache.containsKey(b)) { 2975 labelB = mLabelCache.get(b); 2976 } else { 2977 labelB = (b instanceof AppWidgetProviderInfo) ? 2978 ((AppWidgetProviderInfo) b).label : 2979 ((ResolveInfo) b).loadLabel(mPackageManager).toString(); 2980 mLabelCache.put(b, labelB); 2981 } 2982 return mCollator.compare(labelA, labelB); 2983 } 2984 }; 2985 2986 public void dumpState() { 2987 Log.d(TAG, "mCallbacks=" + mCallbacks); 2988 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); 2989 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); 2990 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); 2991 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); 2992 if (mLoaderTask != null) { 2993 mLoaderTask.dumpState(); 2994 } else { 2995 Log.d(TAG, "mLoaderTask=null"); 2996 } 2997 } 2998} 2999