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