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